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.mapTypeFor;
45 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
47 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
50 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
52 import com.google.common.base.Splitter;
53 import com.google.common.collect.Iterables;
54 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
55 import java.util.AbstractMap.SimpleImmutableEntry;
56 import java.util.ArrayList;
57 import java.util.Collection;
58 import java.util.Collections;
59 import java.util.Comparator;
60 import java.util.HashMap;
61 import java.util.HashSet;
62 import java.util.Iterator;
63 import java.util.List;
65 import java.util.Optional;
66 import org.eclipse.jdt.annotation.NonNull;
67 import org.eclipse.jdt.annotation.Nullable;
68 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
69 import org.opendaylight.mdsal.binding.model.api.Constant;
70 import org.opendaylight.mdsal.binding.model.api.DefaultType;
71 import org.opendaylight.mdsal.binding.model.api.Enumeration;
72 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
73 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
74 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
75 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
76 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
77 import org.opendaylight.mdsal.binding.model.api.Restrictions;
78 import org.opendaylight.mdsal.binding.model.api.Type;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
87 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
88 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
89 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
90 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
91 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
92 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
93 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
94 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
95 import org.opendaylight.yangtools.yang.common.QName;
96 import org.opendaylight.yangtools.yang.common.QNameModule;
97 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
98 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
99 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
106 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
109 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
110 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
111 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
112 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.Module;
117 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
118 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
119 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
120 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
121 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
123 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
125 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.UsesNode;
127 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
128 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
129 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
130 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
131 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
132 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
133 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
134 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
135 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
136 import org.slf4j.Logger;
137 import org.slf4j.LoggerFactory;
139 abstract class AbstractTypeGenerator {
140 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
141 private static final Splitter COLON_SPLITTER = Splitter.on(':');
142 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
143 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
144 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
147 * Comparator based on augment target path.
149 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
150 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
151 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
153 while (thisIt.hasNext()) {
154 if (!otherIt.hasNext()) {
158 final int comp = thisIt.next().compareTo(otherIt.next());
164 return otherIt.hasNext() ? -1 : 0;
168 * Constant with the concrete name of identifier.
170 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
173 * Constant with the concrete name of namespace.
175 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
177 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
180 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
181 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
182 * for schema node specified in key part.
184 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
187 * Provide methods for converting YANG types to JAVA types.
189 private final AbstractTypeProvider typeProvider;
192 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
194 private final @NonNull EffectiveModelContext schemaContext;
197 * Holds renamed elements.
199 private final Map<SchemaNode, JavaTypeName> renames;
201 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
202 final Map<SchemaNode, JavaTypeName> renames) {
203 this.schemaContext = requireNonNull(context);
204 this.typeProvider = requireNonNull(typeProvider);
205 this.renames = requireNonNull(renames);
207 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
208 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
209 for (final Module contextModule : contextModules) {
210 contexts.add(moduleToGenTypes(contextModule));
213 contexts.forEach(this::allAugmentsToGenTypes);
216 final @NonNull EffectiveModelContext schemaContext() {
217 return schemaContext;
220 final Collection<ModuleContext> moduleContexts() {
221 return genCtx.values();
224 final ModuleContext moduleContext(final QNameModule module) {
225 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
228 final AbstractTypeProvider typeProvider() {
232 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
234 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
236 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
237 Collection<? extends SchemaNode> nodes);
239 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
241 private ModuleContext moduleToGenTypes(final Module module) {
242 final ModuleContext context = new ModuleContext(module);
243 genCtx.put(module.getQNameModule(), context);
244 allTypeDefinitionsToGenTypes(context);
245 groupingsToGenTypes(context, module.getGroupings());
246 allIdentitiesToGenTypes(context);
248 if (!module.getChildNodes().isEmpty()) {
249 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
250 context.addModuleNode(moduleType);
251 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
254 // Resolve RPCs and notifications only after we have created instantiated tree
255 rpcMethodsToGenType(context);
256 notificationsToGenType(context);
261 * Converts all extended type definitions of module to the list of
262 * <code>Type</code> objects.
265 * module from which is obtained set of type definitions
266 * @throws IllegalArgumentException
268 * <li>if module is null</li>
269 * <li>if name of module is null</li>
271 * @throws IllegalStateException
272 * if set of type definitions from module is null
274 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
275 final Module module = context.module();
276 checkArgument(module.getName() != null, "Module name cannot be NULL.");
278 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
279 if (typedef != null) {
280 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
282 context.addTypedefType(typedef, type);
283 context.addTypeToSchema(type,typedef);
289 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
290 final DataSchemaNode node, final boolean inGrouping) {
291 if (node.isAugmenting() || node.isAddedByUses()) {
294 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
295 addConcreteInterfaceMethods(genType);
296 annotateDeprecatedIfNecessary(node, genType);
298 final Module module = context.module();
299 genType.setModuleName(module.getName());
300 addCodegenInformation(genType, module, node);
301 genType.setSchemaPath(node.getPath());
302 if (node instanceof DataNodeContainer) {
303 context.addChildNodeType(node, genType);
304 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
305 processUsesAugments((DataNodeContainer) node, context, inGrouping);
310 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
311 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
312 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
313 if (genType != null) {
314 constructGetter(parent, genType, node);
315 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
316 actionsToGenType(context, genType, node, null, inGrouping);
317 notificationsToGenType(context, genType, node, null, inGrouping);
321 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
322 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
323 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
324 if (genType != null) {
325 final List<String> listKeys = listKeys(node);
326 final GeneratedTOBuilder keyTypeBuilder;
327 if (!listKeys.isEmpty()) {
328 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
329 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
330 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
331 .addImplementsType(identifier(genType));
332 genType.addImplementsType(identifiable(keyTypeBuilder));
334 keyTypeBuilder = null;
337 // Decide whether to generate a List or a Map
338 final ParameterizedType listType;
339 if (keyTypeBuilder != null && !node.isUserOrdered()) {
340 listType = mapTypeFor(keyTypeBuilder, genType);
342 listType = listTypeFor(genType);
345 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
346 constructNonnull(parent, listType, node);
348 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
349 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
351 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
352 if (!schemaNode.isAugmenting()) {
353 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
358 if (keyTypeBuilder != null) {
359 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
360 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
361 keyTypeBuilder.setSUID(prop);
364 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
368 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
369 final boolean inGrouping) {
370 for (final UsesNode usesNode : node.getUses()) {
371 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
372 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
373 processUsesAugments(augment, context, inGrouping);
379 * Converts all <b>augmentation</b> of the module to the list
380 * <code>Type</code> objects.
383 * module from which is obtained list of all augmentation objects
384 * to iterate over them
385 * @throws IllegalArgumentException
387 * <li>if the module is null</li>
388 * <li>if the name of module is null</li>
390 * @throws IllegalStateException
391 * if set of augmentations from module is null
393 private void allAugmentsToGenTypes(final ModuleContext context) {
394 final Module module = context.module();
395 checkArgument(module != null, "Module reference cannot be NULL.");
396 checkArgument(module.getName() != null, "Module name cannot be NULL.");
397 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
399 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
400 augmentationToGenTypes(context, augment);
405 * Returns list of <code>AugmentationSchema</code> objects. The objects are
406 * sorted according to the length of their target path from the shortest to
410 * module from which is obtained list of all augmentation objects
411 * @return list of sorted <code>AugmentationSchema</code> objects obtained
412 * from <code>module</code>
413 * @throws IllegalArgumentException
415 * @throws IllegalStateException
416 * if set of module augmentations is null
418 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
419 checkArgument(module != null, "Module reference cannot be NULL.");
420 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
422 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
423 sortedAugmentations.sort(AUGMENT_COMP);
425 return sortedAugmentations;
429 * Create GeneratedTypeBuilder object from module argument.
432 * Module object from which builder will be created
433 * @return <code>GeneratedTypeBuilder</code> which is internal
434 * representation of the module
435 * @throws IllegalArgumentException
438 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
439 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
440 final Module module = context.module();
441 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
442 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
443 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
444 // top level DataRoot object
445 if (module.getUses().size() > 1) {
446 narrowImplementedInterface(moduleDataTypeBuilder);
449 addCodegenInformation(moduleDataTypeBuilder, module);
450 return moduleDataTypeBuilder;
453 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
454 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
455 for (final ActionDefinition action : parentSchema.getActions()) {
456 if (action.isAugmenting()) {
460 final GeneratedType input;
461 final GeneratedType output;
462 if (action.isAddedByUses()) {
463 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
464 // Original definition may live in a different module, make sure we account for that
465 final ModuleContext origContext = moduleContext(
466 orig.getPath().getPathFromRoot().iterator().next().getModule());
467 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
468 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
470 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
471 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
474 if (!(parentSchema instanceof GroupingDefinition)) {
475 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
476 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
477 // and do not capture an actual instantiation.
478 final QName qname = action.getQName();
479 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
480 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
481 BindingMapping.getClassName(qname)));
482 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
484 annotateDeprecatedIfNecessary(action, builder);
485 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
486 : action(parent, input, output));
488 addCodegenInformation(builder, context.module(), action);
489 context.addChildNodeType(action, builder);
494 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
495 final QName qname = action.getQName();
496 for (UsesNode uses : parent.getUses()) {
497 final GroupingDefinition grp = uses.getSourceGrouping();
498 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
500 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
501 if (found.isPresent()) {
502 final ActionDefinition result = found.get();
503 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
507 return Optional.empty();
510 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
511 final ContainerSchemaNode schema, final boolean inGrouping) {
512 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
513 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
514 return genType.build();
518 * Converts all <b>RPCs</b> input and output substatements of the module
519 * to the list of <code>Type</code> objects. In addition are to containers
520 * and lists which belong to input or output also part of returning list.
523 * module from which is obtained set of all rpc objects to
525 * @throws IllegalArgumentException
527 * <li>if the module is null</li>
528 * <li>if the name of module is null</li>
530 * @throws IllegalStateException
531 * if set of rpcs from module is null
533 private void rpcMethodsToGenType(final ModuleContext context) {
534 final Module module = context.module();
535 checkArgument(module.getName() != null, "Module name cannot be NULL.");
536 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
537 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
538 if (rpcDefinitions.isEmpty()) {
542 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
543 interfaceBuilder.addImplementsType(RPC_SERVICE);
545 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
547 for (final RpcDefinition rpc : rpcDefinitions) {
549 final String rpcName = BindingMapping.getClassName(rpc.getQName());
550 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
551 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
553 // Do not refer to annotation class, as it may not be available at runtime
554 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
555 addComment(method, rpc);
557 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
558 method.setReturnType(listenableFutureTypeFor(
559 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
563 context.addTopLevelNodeType(interfaceBuilder);
566 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
567 final ContainerSchemaNode schema, final Type type) {
568 processUsesAugments(schema, context, false);
569 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
570 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
572 addImplementedInterfaceFromUses(schema, outType);
573 outType.addImplementsType(type);
574 outType.addImplementsType(augmentable(outType));
575 addConcreteInterfaceMethods(outType);
576 annotateDeprecatedIfNecessary(rpc, outType);
577 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
578 context.addChildNodeType(schema, outType);
579 return outType.build();
583 * Converts all <b>notifications</b> of the module to the list of
584 * <code>Type</code> objects. In addition are to this list added containers
585 * and lists which are part of this notification.
588 * module from which is obtained set of all notification objects
589 * to iterate over them
590 * @throws IllegalArgumentException
592 * <li>if the module equals null</li>
593 * <li>if the name of module equals null</li>
595 * @throws IllegalStateException
596 * if set of notifications from module is null
598 private void notificationsToGenType(final ModuleContext context) {
599 final Module module = context.module();
600 checkArgument(module.getName() != null, "Module name cannot be NULL.");
601 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
602 if (notifications.isEmpty()) {
606 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
607 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
609 for (final NotificationDefinition notification : notifications) {
610 if (notification != null) {
611 processUsesAugments(notification, context, false);
613 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
614 context.modulePackageName(), notification, DATA_OBJECT, context);
615 addConcreteInterfaceMethods(notificationInterface);
616 annotateDeprecatedIfNecessary(notification, notificationInterface);
617 notificationInterface.addImplementsType(NOTIFICATION);
618 context.addChildNodeType(notification, notificationInterface);
620 // Notification object
621 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
622 notification.getChildNodes(), false);
624 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
625 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
626 .setReturnType(primitiveVoidType()), notification);
630 addCodegenInformation(listenerInterface, module, "notifications", notifications);
631 context.addTopLevelNodeType(listenerInterface);
634 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
635 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
636 final boolean inGrouping) {
637 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
638 if (notifications.isEmpty()) {
642 for (NotificationDefinition notif : notifications) {
643 if (notif.isAugmenting()) {
646 if (parentSchema instanceof GroupingDefinition) {
647 // Notifications cannot be really established, as they lack instantiation context, which would be
648 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
652 processUsesAugments(notif, context, false);
654 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
655 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
656 addConcreteInterfaceMethods(notifInterface);
657 annotateDeprecatedIfNecessary(notif, notifInterface);
659 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
660 : instanceNotification(notifInterface, parent));
661 context.addChildNodeType(notif, notifInterface);
663 // Notification object
664 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
669 * Converts all <b>identities</b> of the module to the list of
670 * <code>Type</code> objects.
673 * module from which is obtained set of all identity objects to
675 * @param schemaContext
676 * schema context only used as input parameter for method
677 * {@link BindingGeneratorImpl#identityToGenType}
680 private void allIdentitiesToGenTypes(final ModuleContext context) {
681 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
683 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
684 for (final IdentitySchemaNode identity : schemaIdentities) {
685 identityToGenType(context, identity);
691 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
692 * created transport object builder. If identity contains base identity then
693 * reference to base identity is added to superior identity as its extend.
694 * If identity doesn't contain base identity then only reference to abstract
695 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
696 * BaseIdentity} is added
700 * @param basePackageName
701 * string contains the module package name
703 * IdentitySchemaNode which contains data about identity
705 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
706 if (identity == null) {
710 JavaTypeName name = renames.get(identity);
712 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
713 BindingMapping.getClassName(identity.getQName()));
716 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
717 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
718 if (!baseIdentities.isEmpty()) {
719 for (IdentitySchemaNode baseIdentity : baseIdentities) {
720 JavaTypeName base = renames.get(baseIdentity);
722 final QName qname = baseIdentity.getQName();
723 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
724 BindingMapping.getClassName(qname));
727 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
728 newType.addImplementsType(gto);
731 newType.addImplementsType(BASE_IDENTITY);
734 final Module module = context.module();
735 addCodegenInformation(newType, module, identity);
736 newType.setModuleName(module.getName());
737 newType.setSchemaPath(identity.getPath());
739 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
741 context.addIdentityType(identity, newType);
744 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
745 final JavaTypeName yangModuleInfo, final String localName) {
746 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
747 new SimpleImmutableEntry<>(yangModuleInfo, localName));
751 * Converts all <b>groupings</b> of the module to the list of
752 * <code>Type</code> objects. Firstly are groupings sorted according mutual
753 * dependencies. At least dependent (independent) groupings are in the list
754 * saved at first positions. For every grouping the record is added to map
755 * {@link ModuleContext#groupings allGroupings}
760 * collection of groupings from which types will be generated
763 private void groupingsToGenTypes(final ModuleContext context,
764 final Collection<? extends GroupingDefinition> groupings) {
765 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
766 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
767 // node of grouping is resolved to the method.
768 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
769 narrowImplementedInterface(genType);
770 annotateDeprecatedIfNecessary(grouping, genType);
771 context.addGroupingType(grouping, genType);
772 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
773 groupingsToGenTypes(context, grouping.getGroupings());
774 processUsesAugments(grouping, context, true);
775 actionsToGenType(context, genType, grouping, null, true);
776 notificationsToGenType(context, genType, grouping, null, true);
781 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
782 * <code>enumTypeDef</code> item is added to builder with its name and value.
784 * @param enumTypeDef EnumTypeDefinition contains enum data
785 * @param enumName string contains name which will be assigned to enumeration builder
786 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
787 * @param module Module in which type should be generated
788 * @return enumeration builder which contains data from <code>enumTypeDef</code>
790 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
791 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
792 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
793 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
794 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
795 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
796 context.addTypeToSchema(ret, enumTypeDef);
797 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
802 * Generates type builder for <code>module</code>.
804 * @param module Module which is source of package name for generated type builder
805 * @param postfix string which is added to the module class name representation as suffix
806 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
807 * @throws IllegalArgumentException if <code>module</code> is null
809 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
810 final Module module = context.module();
811 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
812 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
813 JavaTypeName.create(context.modulePackageName(), moduleName));
815 moduleBuilder.setModuleName(moduleName);
816 addCodegenInformation(moduleBuilder, module);
817 return moduleBuilder;
821 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
822 * In addition there are also generated types for all containers, list and choices which are child of
823 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
825 * @param augmentPackageName string with the name of the package to which the augmentation belongs
826 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
827 * @param module current module
828 * @throws IllegalArgumentException
830 * <li>if <code>augmentPackageName</code> equals null</li>
831 * <li>if <code>augSchema</code> equals null</li>
833 * @throws IllegalStateException
834 * if augment target path is null
836 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
837 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
838 checkState(augSchema.getTargetPath() != null,
839 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
841 processUsesAugments(augSchema, context, false);
842 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
843 SchemaNode targetSchemaNode = null;
845 // FIXME: can we use findDataSchemaNode() instead?
846 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
847 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
848 if (targetSchemaNode instanceof DerivableSchemaNode) {
849 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
851 if (targetSchemaNode == null) {
852 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
853 + " in module " + context.module().getName());
856 if (targetSchemaNode == null) {
857 throw new IllegalArgumentException("augment target not found: " + targetPath);
860 if (targetSchemaNode instanceof ChoiceSchemaNode) {
861 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
862 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
863 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
864 augSchema.getChildNodes(), null, false);
868 final JavaTypeName targetName;
869 if (targetSchemaNode instanceof CaseSchemaNode) {
870 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
871 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
872 targetName = builder.getIdentifier();
874 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
875 if (builder == null) {
876 targetName = findAliasByPath(targetSchemaNode.getPath());
877 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
879 targetName = builder.getIdentifier();
883 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
886 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
887 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
888 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
889 checkState(augSchema.getTargetPath() != null,
890 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
892 processUsesAugments(augSchema, context, inGrouping);
893 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
894 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
895 if (targetSchemaNode == null) {
896 throw new IllegalArgumentException("augment target not found: " + targetPath);
899 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
900 if (targetTypeBuilder == null) {
901 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
903 if (targetTypeBuilder == null) {
904 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
907 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
908 if (usesNodeParent instanceof SchemaNode) {
909 addRawAugmentGenTypeDefinition(context,
910 packageNameForAugmentedGeneratedType(context.modulePackageName(),
911 ((SchemaNode) usesNodeParent).getPath()),
912 targetTypeBuilder.build(), augSchema, inGrouping);
914 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
917 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
918 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
923 * Convenient method to find node added by uses statement.
925 * @param targetPath node path
926 * @param parentUsesNode parent of uses node
927 * @return node from its original location in grouping
929 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
930 final UsesNode parentUsesNode) {
931 SchemaNode result = parentUsesNode.getSourceGrouping();
932 for (final QName node : targetPath.getNodeIdentifiers()) {
933 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
934 if (result instanceof DataNodeContainer) {
935 final QName resultNode = node.bindTo(result.getQName().getModule());
937 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
939 if (result instanceof ActionNodeContainer) {
940 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
942 if (found == null && result instanceof NotificationNodeContainer) {
943 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
947 } else if (result instanceof ChoiceSchemaNode) {
948 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
949 } else if (result instanceof ActionDefinition) {
950 final ActionDefinition action = (ActionDefinition) result;
951 final QName resultNode = node.bindTo(result.getQName().getModule());
953 final ContainerSchemaNode input = action.getInput();
954 final ContainerSchemaNode output = action.getOutput();
955 if (resultNode.equals(input.getQName())) {
957 } else if (resultNode.equals(output.getQName())) {
962 } else if (result != null) {
963 throw new IllegalStateException("Cannot handle " + result);
966 if (result == null) {
970 if (result instanceof DerivableSchemaNode) {
971 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
972 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
973 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
974 result = originalNode.get();
978 if (result instanceof DataSchemaNode) {
979 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
980 if (resultDataSchemaNode.isAddedByUses()) {
981 // The original node is required, but we have only the copy of
982 // the original node.
983 // Maybe this indicates a bug in Yang parser.
984 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
987 return resultDataSchemaNode;
990 throw new IllegalStateException(
991 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
996 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
997 * of augmented node with serial number as suffix.
999 * @param context current module
1000 * @param augmentPackageName string with contains the package name to which the augment belongs
1001 * @param basePackageName string with the package name to which the augmented node belongs
1002 * @param targetTypeRef target type
1003 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1004 * @return generated type builder for augment
1006 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1007 final String augmentPackageName, final Type targetTypeRef,
1008 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1009 Map<String, GeneratedTypeBuilder> augmentBuilders =
1010 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1011 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1014 if (augIdentifier != null) {
1015 augTypeName = BindingMapping.getClassName(augIdentifier);
1017 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1020 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1021 JavaTypeName.create(augmentPackageName, augTypeName));
1023 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1024 addConcreteInterfaceMethods(augTypeBuilder);
1026 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1027 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1029 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1030 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1031 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1033 augmentBuilders.put(augTypeName, augTypeBuilder);
1035 if (!augSchema.getChildNodes().isEmpty()) {
1036 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1039 context.addAugmentType(augTypeBuilder);
1040 return augTypeBuilder;
1043 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1044 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1045 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1049 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1050 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1051 final QName nodeType = unknownSchemaNode.getNodeType();
1052 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1053 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1054 return unknownSchemaNode.getNodeParameter();
1061 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1062 * consists from name of augmented node and serial number of its augmentation.
1064 * @param builders map of builders which were created in the package to which the augmentation belongs
1065 * @param genTypeName string with name of augmented node
1066 * @return string with unique name for augmentation builder
1068 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1070 if (builders != null) {
1071 while (builders.containsKey(genTypeName + index)) {
1075 return genTypeName + index;
1079 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1080 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1081 * already part of them).
1083 * @param module current module
1084 * @param parent generated type builder which represents any node. The subnodes of this node are added
1085 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1086 * container, choice.
1087 * @param childOf parent type
1088 * @param schemaNodes set of data schema nodes which are the children of the node for which
1089 * <code>typeBuilder</code> was created
1090 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1091 * child nodes) could be added to it.
1093 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1094 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1095 final boolean inGrouping) {
1096 if (schemaNodes != null && parent != null) {
1097 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1098 for (final DataSchemaNode schemaNode : schemaNodes) {
1099 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1100 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1108 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1111 * @param module current module
1112 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1113 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1114 * container, choice.
1115 * @param childOf parent type
1116 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1118 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1119 * The getter method could be added to it.
1121 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1122 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1123 final boolean inGrouping) {
1124 if (schemaNodes != null && typeBuilder != null) {
1125 final Type baseInterface = childOf(typeBuilder);
1126 for (final DataSchemaNode schemaNode : schemaNodes) {
1127 if (!schemaNode.isAugmenting()) {
1128 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1136 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1138 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1139 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1140 * @param childOf parent type
1141 * @param module current module
1143 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1144 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1145 if (node != null && typeBuilder != null) {
1146 if (node instanceof LeafSchemaNode) {
1147 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1148 } else if (node instanceof LeafListSchemaNode) {
1149 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1150 } else if (node instanceof ContainerSchemaNode) {
1151 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1152 } else if (node instanceof ListSchemaNode) {
1153 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1154 } else if (node instanceof ChoiceSchemaNode) {
1155 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1156 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1157 opaqueToGeneratedType(context, typeBuilder, node);
1159 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1160 typeBuilder.getFullyQualifiedName());
1166 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1167 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1168 * and names of all parents node.
1170 * @param context current module
1171 * @param basePackageName string with the module package name
1172 * @param parent parent type
1173 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1175 * @throws IllegalArgumentException
1177 * <li>if <code>basePackageName</code> is null</li>
1178 * <li>if <code>choiceNode</code> is null</li>
1181 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1182 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1183 if (!choiceNode.isAddedByUses()) {
1184 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1185 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1186 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1187 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1188 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1189 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1191 final GeneratedType choiceType = choiceTypeBuilder.build();
1192 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1194 constructGetter(parent, choiceType, choiceNode);
1198 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1199 final DataSchemaNode anyNode) {
1200 if (!anyNode.isAddedByUses()) {
1201 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1202 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1203 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1204 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1205 defaultImplementedInterace(anyxmlTypeBuilder);
1206 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1207 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1209 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1214 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1215 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1216 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1217 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1219 * @param context current module context
1220 * @param refChoiceType type which represents superior <i>case</i>
1221 * @param choiceNode choice case node which is mapped to generated type
1222 * @throws IllegalArgumentException
1224 * <li>if <code>refChoiceType</code> equals null</li>
1225 * <li>if <code>caseNodes</code> equals null</li>
1228 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1229 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1230 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1231 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1233 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1234 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1235 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1236 caseTypeBuilder.addImplementsType(refChoiceType);
1237 addConcreteInterfaceMethods(caseTypeBuilder);
1238 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1239 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1240 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1241 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1242 if (caseChildNodes != null) {
1243 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1245 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1246 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1248 if (parent instanceof AugmentationSchemaNode) {
1249 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1250 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1251 // FIXME: can we use findDataSchemaNode?
1252 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1253 targetPath.getNodeIdentifiers());
1254 if (targetSchemaNode instanceof DataSchemaNode
1255 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1256 if (targetSchemaNode instanceof DerivableSchemaNode) {
1257 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1260 if (targetSchemaNode == null) {
1261 throw new IllegalStateException(
1262 "Failed to find target node from grouping for augmentation " + augSchema
1263 + " in module " + context.module().getName());
1266 parent = targetSchemaNode;
1269 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1270 Type childOfType = findChildNodeByPath(parent.getPath());
1271 if (childOfType == null) {
1272 childOfType = findGroupingByPath(parent.getPath());
1274 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1276 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1281 processUsesAugments(caseNode, context, inGrouping);
1286 * Generates list of generated types for all the cases of a choice which are added to the choice through
1289 * @param module current module
1290 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1291 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1292 * of the augmenting choice will belong to pcg2.
1293 * @param targetType Type which represents target choice
1294 * @param targetNode node which represents target choice
1295 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1297 * @throws IllegalArgumentException
1299 * <li>if <code>basePackageName</code> is null</li>
1300 * <li>if <code>targetType</code> is null</li>
1301 * <li>if <code>augmentedNodes</code> is null</li>
1304 // FIXME: nullness rules need to untangled in this method
1305 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1306 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1307 final Type targetType, final ChoiceSchemaNode targetNode,
1308 final Iterable<? extends DataSchemaNode> augmentedNodes,
1309 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1310 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1311 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1313 for (final DataSchemaNode caseNode : augmentedNodes) {
1314 if (caseNode != null) {
1315 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1316 caseTypeBuilder.addImplementsType(targetType);
1317 addConcreteInterfaceMethods(caseTypeBuilder);
1319 CaseSchemaNode node = null;
1320 final String caseLocalName = caseNode.getQName().getLocalName();
1321 if (caseNode instanceof CaseSchemaNode) {
1322 node = (CaseSchemaNode) caseNode;
1323 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1324 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1325 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1326 if (dataSchemaNode instanceof ChoiceSchemaNode
1327 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1328 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1333 node = findNamedCase(targetNode, caseLocalName);
1335 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1336 if (childNodes != null) {
1337 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1340 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1341 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1346 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1347 final SchemaPath nodePath = targetNode.getPath();
1348 final SchemaPath parentSp = nodePath.getParent();
1349 if (parentSp.getParent() == null) {
1350 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1353 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1354 GeneratedTypeBuilder childOfType = null;
1355 if (parent instanceof CaseSchemaNode) {
1356 childOfType = findCaseByPath(parent.getPath());
1357 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1358 childOfType = findChildNodeByPath(parent.getPath());
1359 } else if (parent instanceof GroupingDefinition) {
1360 childOfType = findGroupingByPath(parent.getPath());
1363 if (childOfType == null) {
1364 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1370 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1371 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1372 return cases.isEmpty() ? null : cases.get(0);
1375 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1376 // New parser with encapsulated type
1377 if (leaf.getPath().equals(type.getPath())) {
1381 // Embedded type definition with new parser. Also takes care of the old parser with bits
1382 if (leaf.getPath().equals(type.getPath().getParent())) {
1389 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1390 final List<PatternConstraint> patternConstraints) {
1391 if (!patternConstraints.isEmpty()) {
1392 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1393 .append(BindingMapping.getPropertyName(leafName));
1394 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1395 typeProvider.resolveRegExpressions(patternConstraints));
1400 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1402 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1403 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1404 * @param module Module in which type was defined
1405 * @return boolean value
1407 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1409 * <li>true - in other cases</li>
1412 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1413 final ModuleContext context, final boolean inGrouping) {
1414 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1418 final Module parentModule = findParentModule(schemaContext, leaf);
1419 Type returnType = null;
1421 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1422 if (isInnerType(leaf, typeDef)) {
1423 if (typeDef instanceof EnumTypeDefinition) {
1424 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1425 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1426 typeProvider.putReferencedType(leaf.getPath(), returnType);
1427 } else if (typeDef instanceof UnionTypeDefinition) {
1428 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1429 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1430 // Store the inner type within the union so that we can find the reference for it
1431 context.addInnerTypedefType(typeDef.getPath(), returnType);
1432 } else if (typeDef instanceof BitsTypeDefinition) {
1433 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1435 if (genTOBuilder != null) {
1436 returnType = genTOBuilder.build();
1439 // It is constrained version of already declared type (inner declared type exists, only for special
1440 // cases (Enum, Union, Bits), which were already checked.
1441 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1443 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1444 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1445 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1446 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1447 final SchemaNode leafrefTarget =
1448 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1449 if (leafrefTarget instanceof TypedDataSchemaNode) {
1450 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1453 if (returnType == null) {
1454 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1455 restrictions, inGrouping);
1458 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1461 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1462 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1463 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1466 if (returnType == null) {
1470 if (typeDef instanceof EnumTypeDefinition) {
1471 typeProvider.putReferencedType(leaf.getPath(), returnType);
1474 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1475 processContextRefExtension(leaf, getter, parentModule);
1479 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1480 // Returns DerivedType in case of new parser.
1481 final TypeDefinition<?> baseType = typeDef.getBaseType();
1482 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1485 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1486 final Module module) {
1487 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1488 final QName nodeType = node.getNodeType();
1489 if ("context-reference".equals(nodeType.getLocalName())) {
1490 final String nodeParam = node.getNodeParameter();
1491 IdentitySchemaNode identity = null;
1492 String basePackageName = null;
1493 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1494 final Iterator<String> iterator = splittedElement.iterator();
1495 final int length = Iterables.size(splittedElement);
1497 identity = findIdentityByName(module.getIdentities(), iterator.next());
1498 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1499 } else if (length == 2) {
1500 final String prefix = iterator.next();
1501 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1502 if (dependentModule == null) {
1503 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1506 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1507 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1509 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1512 if (identity == null) {
1513 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1517 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1518 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1519 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1520 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1525 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1526 final String name) {
1527 for (final IdentitySchemaNode id : identities) {
1528 if (id.getQName().getLocalName().equals(name)) {
1535 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1536 for (final ModuleImport imp : imports) {
1537 if (imp.getPrefix().equals(prefix)) {
1538 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1544 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1545 final boolean isReadOnly) {
1546 if (leaf != null && toBuilder != null) {
1548 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1549 if (typeDef instanceof UnionTypeDefinition) {
1550 // GeneratedType for this type definition should have be already created
1551 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1552 returnType = mc.getTypedefs().get(typeDef.getPath());
1553 if (returnType == null) {
1554 // This may still be an inner type, try to find it
1555 returnType = mc.getInnerType(typeDef.getPath());
1557 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1558 // Annonymous enumeration (already generated, since it is inherited via uses).
1559 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1560 QName qname = originalLeaf.getQName();
1561 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1563 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1565 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1571 * Converts <code>leaf</code> schema node to property of generated TO builder.
1573 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1574 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1575 * @param returnType property type
1576 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1577 * @return boolean value
1579 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1580 * name equals null or if leaf is added by <i>uses</i>.</li>
1581 * <li>true - other cases</li>
1584 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1585 final Type returnType, final boolean isReadOnly) {
1586 if (returnType == null) {
1589 final String leafName = leaf.getQName().getLocalName();
1590 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1591 propBuilder.setReadOnly(isReadOnly);
1592 propBuilder.setReturnType(returnType);
1593 addComment(propBuilder, leaf);
1595 toBuilder.addEqualsIdentity(propBuilder);
1596 toBuilder.addHashIdentity(propBuilder);
1597 toBuilder.addToStringProperty(propBuilder);
1602 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1604 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1605 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1606 * @param module module
1607 * @return boolean value
1609 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1610 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1611 * <li>false - other cases</li>
1614 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1615 final ModuleContext context, final boolean inGrouping) {
1616 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1620 final QName nodeName = node.getQName();
1622 final TypeDefinition<?> typeDef = node.getType();
1623 final Module parentModule = findParentModule(schemaContext, node);
1625 Type returnType = null;
1626 if (typeDef.getBaseType() == null) {
1627 if (typeDef instanceof EnumTypeDefinition) {
1628 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1629 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1630 typeProvider.putReferencedType(node.getPath(), returnType);
1631 } else if (typeDef instanceof UnionTypeDefinition) {
1632 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1633 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1634 } else if (typeDef instanceof BitsTypeDefinition) {
1635 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1636 node, parentModule);
1637 returnType = genTOBuilder.build();
1639 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1640 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1641 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1644 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1645 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1646 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1649 constructGetter(typeBuilder, listTypeFor(returnType), node);
1653 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1654 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1655 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1656 returnTypeBuilder.setIsUnion(true);
1657 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1658 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1659 returnTypeBuilder.setModuleName(parentModule.getName());
1660 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1662 genTOBuilder.setTypedef(true);
1663 genTOBuilder.setIsUnion(true);
1664 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1666 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1670 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1671 final GeneratedTransferObject returnType, final Module parentModule) {
1672 // Append enclosing path hierarchy without dots
1673 final StringBuilder sb = new StringBuilder();
1674 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1675 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1676 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1677 unionBuilder.setIsUnionBuilder(true);
1679 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1680 method.setReturnType(returnType);
1681 method.addParameter(STRING, "defaultValue");
1682 method.setAccessModifier(AccessModifier.PUBLIC);
1683 method.setStatic(true);
1685 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1686 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1689 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1690 final SchemaNode schemaNode) {
1691 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1694 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1695 final SchemaNode schemaNode, final Type baseInterface) {
1696 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1697 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1701 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1702 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1703 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1704 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1705 * If <code>schemaNode</code> is instance of
1706 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1707 * which are specified in <i>uses</i>.
1709 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1710 * @param schemaNode schema node for which is created generated type builder
1711 * @param parent parent type (can be null)
1712 * @return generated type builder <code>schemaNode</code>
1714 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1715 final Type baseInterface, final ModuleContext context) {
1716 JavaTypeName name = renames.get(schemaNode);
1718 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1721 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1722 it.addImplementsType(baseInterface);
1723 if (!(schemaNode instanceof GroupingDefinition)) {
1724 it.addImplementsType(augmentable(it));
1726 if (schemaNode instanceof DataNodeContainer) {
1727 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1728 groupingsToGenTypes(context, containerSchema.getGroupings());
1729 addImplementedInterfaceFromUses(containerSchema, it);
1736 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1737 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1738 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1740 * @param packageName string with the package name to which returning generated type builder belongs
1741 * @param schemaNode schema node which provide data about the schema node name
1742 * @param prefix return type name prefix
1743 * @return generated type builder for <code>schemaNode</code>
1744 * @throws IllegalArgumentException
1746 * <li>if <code>schemaNode</code> is null</li>
1747 * <li>if <code>packageName</code> is null</li>
1748 * <li>if QName of schema node is null</li>
1749 * <li>if schemaNode name is null</li>
1752 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1753 final SchemaNode schemaNode) {
1754 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1755 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1756 final String schemaNodeName = schemaNode.getQName().getLocalName();
1757 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1759 // FIXME: Validation of name conflict
1760 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1761 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1763 final Module module = context.module();
1764 addCodegenInformation(newType, module, schemaNode);
1765 newType.setSchemaPath(schemaNode.getPath());
1766 newType.setModuleName(module.getName());
1768 final String packageName = identifier.packageName();
1769 final String simpleName = identifier.simpleName();
1770 if (!genTypeBuilders.containsKey(packageName)) {
1771 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1772 builders.put(simpleName, newType);
1773 genTypeBuilders.put(packageName, builders);
1775 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1776 if (!builders.containsKey(simpleName)) {
1777 builders.put(simpleName, newType);
1784 * Creates the name of the getter method name from <code>localName</code>.
1786 * @param localName string with the name of the getter method
1787 * @param returnType return type
1788 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1790 public static String getterMethodName(final String localName, final Type returnType) {
1791 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1795 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1796 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1797 * and <code>returnType</code> information are added to the builder.
1799 * @param interfaceBuilder generated type builder for which the getter method should be created
1800 * @param returnType type which represents the return type of the getter method
1801 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1802 * @param comment string with comment for the getter method
1803 * @param status status from yang file, for deprecated annotation
1804 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1806 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1807 final SchemaNode node) {
1808 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1809 getterMethodName(node.getQName().getLocalName(), returnType));
1810 getMethod.setReturnType(returnType);
1812 annotateDeprecatedIfNecessary(node, getMethod);
1813 addComment(getMethod, node);
1818 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1819 final ListSchemaNode node) {
1820 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1821 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1822 getMethod.setReturnType(returnType).setDefault(true);
1823 annotateDeprecatedIfNecessary(node, getMethod);
1827 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1830 * @param basePackageName string contains the module package name
1831 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1832 * or as a property to <code>genTOBuilder</code> if is part of the list key
1833 * @param typeBuilder generated type builder for the list schema node
1834 * @param genTOBuilder generated TO builder for the list keys
1835 * @param listKeys list of string which contains names of the list keys
1836 * @param module current module
1837 * @throws IllegalArgumentException
1839 * <li>if <code>schemaNode</code> equals null</li>
1840 * <li>if <code>typeBuilder</code> equals null</li>
1843 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1844 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1845 final List<String> listKeys, final boolean inGrouping) {
1846 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1847 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1849 if (schemaNode instanceof LeafSchemaNode) {
1850 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1851 final String leafName = leaf.getQName().getLocalName();
1852 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1853 if (listKeys.contains(leafName)) {
1855 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1857 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1860 } else if (!schemaNode.isAddedByUses()) {
1861 if (schemaNode instanceof LeafListSchemaNode) {
1862 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1863 } else if (schemaNode instanceof ContainerSchemaNode) {
1864 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1865 (ContainerSchemaNode) schemaNode, inGrouping);
1866 } else if (schemaNode instanceof ChoiceSchemaNode) {
1867 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1868 } else if (schemaNode instanceof ListSchemaNode) {
1869 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1870 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1871 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1876 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1877 final GeneratedTOBuilder genTOBuilder) {
1878 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1880 if (genTOBuilder != null) {
1881 final GeneratedTransferObject genTO = genTOBuilder.build();
1882 // Add Identifiable.getKey() for items
1883 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1884 .addAnnotation(OVERRIDE_ANNOTATION);
1885 context.addGeneratedTOBuilder(genTOBuilder);
1890 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1892 * @param list of string with names of the list keys
1893 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1894 * an empty list is returned.
1896 private static List<String> listKeys(final ListSchemaNode list) {
1897 final List<QName> keyDefinition = list.getKeyDefinition();
1898 switch (keyDefinition.size()) {
1900 return Collections.emptyList();
1902 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1904 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1905 for (final QName keyDef : keyDefinition) {
1906 listKeys.add(keyDef.getLocalName());
1913 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1914 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1915 * enclosing transfer objects.
1917 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1918 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1919 * @param leaf string with name for generated TO builder
1920 * @param parentModule parent module
1921 * @return generated TO builder for <code>typeDef</code>
1923 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1924 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1925 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1926 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1928 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1929 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1930 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1931 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1932 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1934 for (GeneratedTOBuilder builder : types) {
1935 if (builder.isUnion()) {
1936 final GeneratedTransferObject type = builder.build();
1937 createUnionBuilder(builder, typeBuilder, type, parentModule);
1941 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1945 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1946 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1947 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1950 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1951 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1952 * @param leaf string with name for generated TO builder
1953 * @param parentModule parent module
1954 * @return generated TO builder for <code>typeDef</code>
1956 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1957 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1958 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1959 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1960 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1961 return genTOBuilder;
1965 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1966 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1967 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1968 * to <code>builder</code>
1970 * @param dataNodeContainer element which contains the list of used YANG groupings
1971 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1972 * @return generated type builder with all implemented types
1974 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1975 final GeneratedTypeBuilder builder) {
1976 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1977 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1978 if (genType == null) {
1979 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1980 + " is not resolved for " + builder.getFullyQualifiedName());
1983 builder.addImplementsType(genType.build());
1988 private JavaTypeName findAliasByPath(final SchemaPath path) {
1989 for (final ModuleContext ctx : genCtx.values()) {
1990 final JavaTypeName result = ctx.getAlias(path);
1991 if (result != null) {
1998 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1999 for (final ModuleContext ctx : genCtx.values()) {
2000 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2001 if (result != null) {
2008 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2009 for (final ModuleContext ctx : genCtx.values()) {
2010 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2011 if (result != null) {
2018 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2019 for (final ModuleContext ctx : genCtx.values()) {
2020 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2021 if (result != null) {
2028 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2029 for (final ModuleContext ctx : genCtx.values()) {
2030 final GeneratedTypeBuilder result = ctx.getCase(path);
2031 if (result != null) {
2038 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2039 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2040 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2043 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2044 switch (node.getStatus()) {
2046 // FIXME: we really want to use a pre-made annotation
2047 builder.addAnnotation(DEPRECATED_ANNOTATION);
2050 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2056 throw new IllegalStateException("Unhandled status in " + node);
2060 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2061 defaultImplementedInterace(typeBuilder);
2063 typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2064 .setAccessModifier(AccessModifier.PUBLIC)
2066 .setReturnType(primitiveIntType());
2067 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2068 .setAccessModifier(AccessModifier.PUBLIC)
2070 .setReturnType(STRING);
2073 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2074 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2077 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2078 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2081 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2082 final Type classType) {
2083 final MethodSignatureBuilder ret = typeBuilder
2084 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2085 .setAccessModifier(AccessModifier.PUBLIC)
2086 .setReturnType(classType(classType));
2087 ret.addAnnotation(OVERRIDE_ANNOTATION);