2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
45 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
50 import com.google.common.base.Splitter;
51 import com.google.common.collect.Iterables;
52 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
53 import java.util.AbstractMap.SimpleImmutableEntry;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Collections;
57 import java.util.Comparator;
58 import java.util.HashMap;
59 import java.util.HashSet;
60 import java.util.Iterator;
61 import java.util.List;
63 import java.util.Optional;
65 import org.eclipse.jdt.annotation.Nullable;
66 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
67 import org.opendaylight.mdsal.binding.model.api.Constant;
68 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
69 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
70 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
71 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
72 import org.opendaylight.mdsal.binding.model.api.Restrictions;
73 import org.opendaylight.mdsal.binding.model.api.Type;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
83 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
84 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
85 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
86 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
87 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
88 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
89 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
90 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
91 import org.opendaylight.yangtools.yang.common.QName;
92 import org.opendaylight.yangtools.yang.common.QNameModule;
93 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
94 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
95 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
102 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
106 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
107 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.Module;
112 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
113 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
114 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
115 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
116 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
117 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
119 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
120 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.UsesNode;
122 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
123 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
125 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
126 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
127 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
128 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
129 import org.slf4j.Logger;
130 import org.slf4j.LoggerFactory;
132 abstract class AbstractTypeGenerator {
133 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
134 private static final Splitter COLON_SPLITTER = Splitter.on(':');
135 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
136 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
137 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
140 * Comparator based on augment target path.
142 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
143 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
144 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
146 while (thisIt.hasNext()) {
147 if (!otherIt.hasNext()) {
151 final int comp = thisIt.next().compareTo(otherIt.next());
157 return otherIt.hasNext() ? -1 : 0;
161 * Constant with the concrete name of identifier.
163 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
166 * Constant with the concrete name of namespace.
168 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
170 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
173 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
174 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
175 * for schema node specified in key part.
177 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
180 * Provide methods for converting YANG types to JAVA types.
182 private final AbstractTypeProvider typeProvider;
185 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
187 private final SchemaContext schemaContext;
190 * Holds renamed elements.
192 private final Map<SchemaNode, JavaTypeName> renames;
194 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
195 final Map<SchemaNode, JavaTypeName> renames) {
196 this.schemaContext = requireNonNull(context);
197 this.typeProvider = requireNonNull(typeProvider);
198 this.renames = requireNonNull(renames);
200 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
201 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
202 for (final Module contextModule : contextModules) {
203 contexts.add(moduleToGenTypes(contextModule));
206 contexts.forEach(this::allAugmentsToGenTypes);
209 final Collection<ModuleContext> moduleContexts() {
210 return genCtx.values();
213 final ModuleContext moduleContext(final QNameModule module) {
214 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
217 final AbstractTypeProvider typeProvider() {
221 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
223 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
225 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
226 Set<? extends SchemaNode> nodes);
228 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
230 private ModuleContext moduleToGenTypes(final Module module) {
231 final ModuleContext context = new ModuleContext(module);
232 genCtx.put(module.getQNameModule(), context);
233 allTypeDefinitionsToGenTypes(context);
234 groupingsToGenTypes(context, module.getGroupings());
235 rpcMethodsToGenType(context);
236 allIdentitiesToGenTypes(context);
237 notificationsToGenType(context);
239 if (!module.getChildNodes().isEmpty()) {
240 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
241 context.addModuleNode(moduleType);
242 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
248 * Converts all extended type definitions of module to the list of
249 * <code>Type</code> objects.
252 * module from which is obtained set of type definitions
253 * @throws IllegalArgumentException
255 * <li>if module is null</li>
256 * <li>if name of module is null</li>
258 * @throws IllegalStateException
259 * if set of type definitions from module is null
261 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
262 final Module module = context.module();
263 checkArgument(module.getName() != null, "Module name cannot be NULL.");
265 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
266 if (typedef != null) {
267 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
269 context.addTypedefType(typedef, type);
270 context.addTypeToSchema(type,typedef);
276 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
277 final DataSchemaNode node, final boolean inGrouping) {
278 if (node.isAugmenting() || node.isAddedByUses()) {
281 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
282 defaultImplementedInterace(genType);
283 annotateDeprecatedIfNecessary(node, genType);
285 final Module module = context.module();
286 genType.setModuleName(module.getName());
287 addCodegenInformation(genType, module, node);
288 genType.setSchemaPath(node.getPath());
289 if (node instanceof DataNodeContainer) {
290 context.addChildNodeType(node, genType);
291 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
292 processUsesAugments((DataNodeContainer) node, context, inGrouping);
297 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
298 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
299 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
300 if (genType != null) {
301 constructGetter(parent, genType, node);
302 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
303 actionsToGenType(context, genType, node, null, inGrouping);
304 notificationsToGenType(context, genType, node, null, inGrouping);
308 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
309 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
310 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
311 if (genType != null) {
312 final List<String> listKeys = listKeys(node);
313 final GeneratedTOBuilder keyTypeBuilder;
314 if (!listKeys.isEmpty()) {
315 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
316 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
317 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
318 .addImplementsType(identifier(genType));
319 genType.addImplementsType(identifiable(keyTypeBuilder));
321 keyTypeBuilder = null;
324 final ParameterizedType listType = listTypeFor(genType);
325 constructGetter(parent, listType, node);
326 constructNonnull(parent, listType, node);
328 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
329 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
331 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
332 if (!schemaNode.isAugmenting()) {
333 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
338 if (keyTypeBuilder != null) {
339 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
340 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
341 keyTypeBuilder.setSUID(prop);
344 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
348 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
349 final boolean inGrouping) {
350 for (final UsesNode usesNode : node.getUses()) {
351 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
352 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
353 processUsesAugments(augment, context, inGrouping);
359 * Converts all <b>augmentation</b> of the module to the list
360 * <code>Type</code> objects.
363 * module from which is obtained list of all augmentation objects
364 * to iterate over them
365 * @throws IllegalArgumentException
367 * <li>if the module is null</li>
368 * <li>if the name of module is null</li>
370 * @throws IllegalStateException
371 * if set of augmentations from module is null
373 private void allAugmentsToGenTypes(final ModuleContext context) {
374 final Module module = context.module();
375 checkArgument(module != null, "Module reference cannot be NULL.");
376 checkArgument(module.getName() != null, "Module name cannot be NULL.");
377 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
379 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
380 augmentationToGenTypes(context, augment);
385 * Returns list of <code>AugmentationSchema</code> objects. The objects are
386 * sorted according to the length of their target path from the shortest to
390 * module from which is obtained list of all augmentation objects
391 * @return list of sorted <code>AugmentationSchema</code> objects obtained
392 * from <code>module</code>
393 * @throws IllegalArgumentException
395 * @throws IllegalStateException
396 * if set of module augmentations is null
398 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
399 checkArgument(module != null, "Module reference cannot be NULL.");
400 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
402 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
403 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
404 sortedAugmentations.sort(AUGMENT_COMP);
406 return sortedAugmentations;
410 * Create GeneratedTypeBuilder object from module argument.
413 * Module object from which builder will be created
414 * @return <code>GeneratedTypeBuilder</code> which is internal
415 * representation of the module
416 * @throws IllegalArgumentException
419 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
420 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
421 final Module module = context.module();
422 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
423 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
425 addCodegenInformation(moduleDataTypeBuilder, module);
426 return moduleDataTypeBuilder;
429 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
430 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
431 for (final ActionDefinition action : parentSchema.getActions()) {
432 if (action.isAugmenting()) {
436 final GeneratedType input;
437 final GeneratedType output;
438 if (action.isAddedByUses()) {
439 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
440 // Original definition may live in a different module, make sure we account for that
441 final ModuleContext origContext = moduleContext(
442 orig.getPath().getPathFromRoot().iterator().next().getModule());
443 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
444 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
446 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
447 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
450 if (!(parentSchema instanceof GroupingDefinition)) {
451 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
452 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
453 // and do not capture an actual instantiation.
454 final QName qname = action.getQName();
455 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
456 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
457 BindingMapping.getClassName(qname)));
458 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
459 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
461 annotateDeprecatedIfNecessary(action, builder);
462 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
463 : action(parent, input, output));
465 addCodegenInformation(builder, context.module(), action);
466 context.addChildNodeType(action, builder);
471 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
472 final QName qname = action.getQName();
473 for (UsesNode uses : parent.getUses()) {
474 final GroupingDefinition grp = findUsedGrouping(uses);
475 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
477 final Optional<ActionDefinition> found = grp.findAction(qname.withModule(grp.getQName().getModule()));
478 if (found.isPresent()) {
479 final ActionDefinition result = found.get();
480 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
484 return Optional.empty();
487 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
488 final ContainerSchemaNode schema, final boolean inGrouping) {
489 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
490 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
491 return genType.build();
495 * Converts all <b>RPCs</b> input and output substatements of the module
496 * to the list of <code>Type</code> objects. In addition are to containers
497 * and lists which belong to input or output also part of returning list.
500 * module from which is obtained set of all rpc objects to
502 * @throws IllegalArgumentException
504 * <li>if the module is null</li>
505 * <li>if the name of module is null</li>
507 * @throws IllegalStateException
508 * if set of rpcs from module is null
510 private void rpcMethodsToGenType(final ModuleContext context) {
511 final Module module = context.module();
512 checkArgument(module.getName() != null, "Module name cannot be NULL.");
513 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
514 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
515 if (rpcDefinitions.isEmpty()) {
519 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
520 interfaceBuilder.addImplementsType(RPC_SERVICE);
522 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
524 for (final RpcDefinition rpc : rpcDefinitions) {
526 final String rpcName = BindingMapping.getClassName(rpc.getQName());
527 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
528 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
530 // Do not refer to annotation class, as it may not be available at runtime
531 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
532 addComment(method, rpc);
534 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
535 method.setReturnType(listenableFutureTypeFor(
536 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
540 context.addTopLevelNodeType(interfaceBuilder);
543 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
544 final ContainerSchemaNode schema, final Type type) {
545 processUsesAugments(schema, context, false);
546 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
547 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
549 addImplementedInterfaceFromUses(schema, outType);
550 outType.addImplementsType(type);
551 outType.addImplementsType(augmentable(outType));
552 defaultImplementedInterace(outType);
553 annotateDeprecatedIfNecessary(rpc, outType);
554 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
555 context.addChildNodeType(schema, outType);
556 return outType.build();
560 * Converts all <b>notifications</b> of the module to the list of
561 * <code>Type</code> objects. In addition are to this list added containers
562 * and lists which are part of this notification.
565 * module from which is obtained set of all notification objects
566 * to iterate over them
567 * @throws IllegalArgumentException
569 * <li>if the module equals null</li>
570 * <li>if the name of module equals null</li>
572 * @throws IllegalStateException
573 * if set of notifications from module is null
575 private void notificationsToGenType(final ModuleContext context) {
576 final Module module = context.module();
577 checkArgument(module.getName() != null, "Module name cannot be NULL.");
578 final Set<NotificationDefinition> notifications = module.getNotifications();
579 if (notifications.isEmpty()) {
583 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
584 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
586 for (final NotificationDefinition notification : notifications) {
587 if (notification != null) {
588 processUsesAugments(notification, context, false);
590 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
591 context.modulePackageName(), notification, DATA_OBJECT, context);
592 defaultImplementedInterace(notificationInterface);
593 annotateDeprecatedIfNecessary(notification, notificationInterface);
594 notificationInterface.addImplementsType(NOTIFICATION);
595 context.addChildNodeType(notification, notificationInterface);
597 // Notification object
598 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
599 notification.getChildNodes(), false);
601 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
602 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
603 .setReturnType(primitiveVoidType()), notification);
607 addCodegenInformation(listenerInterface, module, "notifications", notifications);
608 context.addTopLevelNodeType(listenerInterface);
611 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
612 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
613 final boolean inGrouping) {
614 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
615 if (notifications.isEmpty()) {
619 for (NotificationDefinition notif : notifications) {
620 if (notif.isAugmenting()) {
623 if (parentSchema instanceof GroupingDefinition) {
624 // Notifications cannot be really established, as they lack instantiation context, which would be
625 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
629 processUsesAugments(notif, context, false);
631 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
632 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
633 defaultImplementedInterace(notifInterface);
634 annotateDeprecatedIfNecessary(notif, notifInterface);
636 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
637 : instanceNotification(notifInterface, parent));
638 context.addChildNodeType(notif, notifInterface);
640 // Notification object
641 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
646 * Converts all <b>identities</b> of the module to the list of
647 * <code>Type</code> objects.
650 * module from which is obtained set of all identity objects to
652 * @param schemaContext
653 * schema context only used as input parameter for method
654 * {@link BindingGeneratorImpl#identityToGenType}
657 private void allIdentitiesToGenTypes(final ModuleContext context) {
658 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
660 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
661 for (final IdentitySchemaNode identity : schemaIdentities) {
662 identityToGenType(context, identity);
668 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
669 * created transport object builder. If identity contains base identity then
670 * reference to base identity is added to superior identity as its extend.
671 * If identity doesn't contain base identity then only reference to abstract
672 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
673 * BaseIdentity} is added
677 * @param basePackageName
678 * string contains the module package name
680 * IdentitySchemaNode which contains data about identity
682 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
683 if (identity == null) {
687 JavaTypeName name = renames.get(identity);
689 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
690 BindingMapping.getClassName(identity.getQName()));
693 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
694 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
695 if (!baseIdentities.isEmpty()) {
696 for (IdentitySchemaNode baseIdentity : baseIdentities) {
697 JavaTypeName base = renames.get(baseIdentity);
699 final QName qname = baseIdentity.getQName();
700 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
701 BindingMapping.getClassName(qname));
704 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
705 newType.addImplementsType(gto);
708 newType.addImplementsType(BASE_IDENTITY);
711 final Module module = context.module();
712 addCodegenInformation(newType, module, identity);
713 newType.setModuleName(module.getName());
714 newType.setSchemaPath(identity.getPath());
716 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
717 identity.getQName().getLocalName());
719 context.addIdentityType(identity, newType);
722 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
723 final JavaTypeName yangModuleInfo, final String localName) {
724 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
725 new SimpleImmutableEntry<>(yangModuleInfo, localName));
729 * Converts all <b>groupings</b> of the module to the list of
730 * <code>Type</code> objects. Firstly are groupings sorted according mutual
731 * dependencies. At least dependent (independent) groupings are in the list
732 * saved at first positions. For every grouping the record is added to map
733 * {@link ModuleContext#groupings allGroupings}
738 * collection of groupings from which types will be generated
741 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
742 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
743 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
744 // node of grouping is resolved to the method.
745 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
746 narrowImplementedInterface(genType);
747 annotateDeprecatedIfNecessary(grouping, genType);
748 context.addGroupingType(grouping, genType);
749 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
750 groupingsToGenTypes(context, grouping.getGroupings());
751 processUsesAugments(grouping, context, true);
752 actionsToGenType(context, genType, grouping, null, true);
753 notificationsToGenType(context, genType, grouping, null, true);
758 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
759 * <code>enumTypeDef</code> item is added to builder with its name and value.
761 * @param enumTypeDef EnumTypeDefinition contains enum data
762 * @param enumName string contains name which will be assigned to enumeration builder
763 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
764 * @param module Module in which type should be generated
765 * @return enumeration builder which contains data from <code>enumTypeDef</code>
767 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
768 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
769 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
770 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
771 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
772 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
773 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
780 * Generates type builder for <code>module</code>.
782 * @param module Module which is source of package name for generated type builder
783 * @param postfix string which is added to the module class name representation as suffix
784 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
785 * @throws IllegalArgumentException if <code>module</code> is null
787 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
788 final Module module = context.module();
789 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
790 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
791 JavaTypeName.create(context.modulePackageName(), moduleName));
793 moduleBuilder.setModuleName(moduleName);
794 addCodegenInformation(moduleBuilder, module);
795 return moduleBuilder;
799 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
800 * In addition there are also generated types for all containers, list and choices which are child of
801 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
803 * @param augmentPackageName string with the name of the package to which the augmentation belongs
804 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
805 * @param module current module
806 * @throws IllegalArgumentException
808 * <li>if <code>augmentPackageName</code> equals null</li>
809 * <li>if <code>augSchema</code> equals null</li>
811 * @throws IllegalStateException
812 * if augment target path is null
814 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
815 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
816 checkState(augSchema.getTargetPath() != null,
817 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
819 processUsesAugments(augSchema, context, false);
820 final SchemaPath targetPath = augSchema.getTargetPath();
821 SchemaNode targetSchemaNode = null;
823 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
824 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
825 if (targetSchemaNode instanceof DerivableSchemaNode) {
826 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
828 if (targetSchemaNode == null) {
829 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
830 + " in module " + context.module().getName());
833 if (targetSchemaNode == null) {
834 throw new IllegalArgumentException("augment target not found: " + targetPath);
837 if (targetSchemaNode instanceof ChoiceSchemaNode) {
838 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
839 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
840 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
841 augSchema.getChildNodes(), null, false);
845 final JavaTypeName targetName;
846 if (targetSchemaNode instanceof CaseSchemaNode) {
847 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
848 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
849 targetName = builder.getIdentifier();
851 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
852 if (builder == null) {
853 targetName = findAliasByPath(targetSchemaNode.getPath());
854 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
856 targetName = builder.getIdentifier();
860 addRawAugmentGenTypeDefinition(context, new ReferencedTypeImpl(targetName), augSchema, false);
863 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
864 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
865 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
866 checkState(augSchema.getTargetPath() != null,
867 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
869 processUsesAugments(augSchema, context, inGrouping);
870 final SchemaPath targetPath = augSchema.getTargetPath();
871 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
872 if (targetSchemaNode == null) {
873 throw new IllegalArgumentException("augment target not found: " + targetPath);
876 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
877 if (targetTypeBuilder == null) {
878 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
880 if (targetTypeBuilder == null) {
881 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
884 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
885 if (usesNodeParent instanceof SchemaNode) {
886 addRawAugmentGenTypeDefinition(context,
887 packageNameForAugmentedGeneratedType(context.modulePackageName(),
888 ((SchemaNode) usesNodeParent).getPath()),
889 targetTypeBuilder.build(), augSchema, inGrouping);
891 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
894 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
895 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
899 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
900 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
902 if (targetGrouping instanceof GroupingDefinition) {
903 return (GroupingDefinition) targetGrouping;
906 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
910 * Convenient method to find node added by uses statement.
912 * @param targetPath node path
913 * @param parentUsesNode parent of uses node
914 * @return node from its original location in grouping
916 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
917 SchemaNode result = findUsedGrouping(parentUsesNode);
918 for (final QName node : targetPath.getPathFromRoot()) {
919 if (result instanceof DataNodeContainer) {
920 final QName resultNode = node.withModule(result.getQName().getModule());
921 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
922 } else if (result instanceof ChoiceSchemaNode) {
923 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
926 if (result == null) {
930 if (result instanceof DerivableSchemaNode) {
931 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
932 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
933 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
934 result = originalNode.get();
938 if (result instanceof DataSchemaNode) {
939 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
940 if (resultDataSchemaNode.isAddedByUses()) {
941 // The original node is required, but we have only the copy of
942 // the original node.
943 // Maybe this indicates a bug in Yang parser.
944 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
947 return resultDataSchemaNode;
950 throw new IllegalStateException(
951 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
956 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
957 * of augmented node with serial number as suffix.
959 * @param context current module
960 * @param augmentPackageName string with contains the package name to which the augment belongs
961 * @param basePackageName string with the package name to which the augmented node belongs
962 * @param targetTypeRef target type
963 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
964 * @return generated type builder for augment
966 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
967 final String augmentPackageName, final Type targetTypeRef,
968 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
969 Map<String, GeneratedTypeBuilder> augmentBuilders =
970 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
971 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
974 if (augIdentifier != null) {
975 augTypeName = BindingMapping.getClassName(augIdentifier);
977 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
980 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
981 JavaTypeName.create(augmentPackageName, augTypeName));
983 augTypeBuilder.addImplementsType(DATA_OBJECT);
984 defaultImplementedInterace(augTypeBuilder);
986 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
987 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
988 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
990 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
991 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
992 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
994 augmentBuilders.put(augTypeName, augTypeBuilder);
996 if (!augSchema.getChildNodes().isEmpty()) {
997 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1000 context.addAugmentType(augTypeBuilder);
1001 return augTypeBuilder;
1004 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1005 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1006 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1010 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1011 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1012 final QName nodeType = unknownSchemaNode.getNodeType();
1013 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1014 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1015 return unknownSchemaNode.getNodeParameter();
1022 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1023 * consists from name of augmented node and serial number of its augmentation.
1025 * @param builders map of builders which were created in the package to which the augmentation belongs
1026 * @param genTypeName string with name of augmented node
1027 * @return string with unique name for augmentation builder
1029 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1031 if (builders != null) {
1032 while (builders.containsKey(genTypeName + index)) {
1036 return genTypeName + index;
1040 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1041 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1042 * already part of them).
1044 * @param module current module
1045 * @param parent generated type builder which represents any node. The subnodes of this node are added
1046 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1047 * container, choice.
1048 * @param childOf parent type
1049 * @param schemaNodes set of data schema nodes which are the children of the node for which
1050 * <code>typeBuilder</code> was created
1051 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1052 * child nodes) could be added to it.
1054 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1055 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1056 if (schemaNodes != null && parent != null) {
1057 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1058 for (final DataSchemaNode schemaNode : schemaNodes) {
1059 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1060 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1068 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1071 * @param module current module
1072 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1073 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1074 * container, choice.
1075 * @param childOf parent type
1076 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1078 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1079 * The getter method could be added to it.
1081 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1082 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1083 final boolean inGrouping) {
1084 if (schemaNodes != null && typeBuilder != null) {
1085 final Type baseInterface = childOf(typeBuilder);
1086 for (final DataSchemaNode schemaNode : schemaNodes) {
1087 if (!schemaNode.isAugmenting()) {
1088 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1096 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1098 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1099 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1100 * @param childOf parent type
1101 * @param module current module
1103 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1104 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1105 if (node != null && typeBuilder != null) {
1106 if (node instanceof LeafSchemaNode) {
1107 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1108 } else if (node instanceof LeafListSchemaNode) {
1109 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1110 } else if (node instanceof ContainerSchemaNode) {
1111 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1112 } else if (node instanceof ListSchemaNode) {
1113 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1114 } else if (node instanceof ChoiceSchemaNode) {
1115 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1116 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1117 opaqueToGeneratedType(context, typeBuilder, node);
1119 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1120 typeBuilder.getFullyQualifiedName());
1126 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1127 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1128 * and names of all parents node.
1130 * @param context current module
1131 * @param basePackageName string with the module package name
1132 * @param parent parent type
1133 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1135 * @throws IllegalArgumentException
1137 * <li>if <code>basePackageName</code> is null</li>
1138 * <li>if <code>choiceNode</code> is null</li>
1141 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1142 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1143 if (!choiceNode.isAddedByUses()) {
1144 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1145 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1146 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1147 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1148 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1149 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1151 final GeneratedType choiceType = choiceTypeBuilder.build();
1152 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1154 constructGetter(parent, choiceType, choiceNode);
1158 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1159 final DataSchemaNode anyNode) {
1160 if (!anyNode.isAddedByUses()) {
1161 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1162 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1163 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1164 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1165 defaultImplementedInterace(anyxmlTypeBuilder);
1166 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1167 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1169 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1174 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1175 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1176 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1177 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1179 * @param context current module context
1180 * @param refChoiceType type which represents superior <i>case</i>
1181 * @param choiceNode choice case node which is mapped to generated type
1182 * @throws IllegalArgumentException
1184 * <li>if <code>refChoiceType</code> equals null</li>
1185 * <li>if <code>caseNodes</code> equals null</li>
1188 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1189 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1190 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1191 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1193 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1194 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1195 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1196 caseTypeBuilder.addImplementsType(refChoiceType);
1197 defaultImplementedInterace(caseTypeBuilder);
1198 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1199 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1200 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1201 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1202 if (caseChildNodes != null) {
1203 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1205 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1206 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1208 if (parent instanceof AugmentationSchemaNode) {
1209 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1210 final SchemaPath targetPath = augSchema.getTargetPath();
1211 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1212 if (targetSchemaNode instanceof DataSchemaNode
1213 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1214 if (targetSchemaNode instanceof DerivableSchemaNode) {
1215 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1218 if (targetSchemaNode == null) {
1219 throw new IllegalStateException(
1220 "Failed to find target node from grouping for augmentation " + augSchema
1221 + " in module " + context.module().getName());
1224 parent = targetSchemaNode;
1227 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1228 Type childOfType = findChildNodeByPath(parent.getPath());
1229 if (childOfType == null) {
1230 childOfType = findGroupingByPath(parent.getPath());
1232 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1234 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1239 processUsesAugments(caseNode, context, inGrouping);
1244 * Generates list of generated types for all the cases of a choice which are added to the choice through
1247 * @param module current module
1248 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1249 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1250 * of the augmenting choice will belong to pcg2.
1251 * @param targetType Type which represents target choice
1252 * @param targetNode node which represents target choice
1253 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1255 * @throws IllegalArgumentException
1257 * <li>if <code>basePackageName</code> is null</li>
1258 * <li>if <code>targetType</code> is null</li>
1259 * <li>if <code>augmentedNodes</code> is null</li>
1262 // FIXME: nullness rules need to untangled in this method
1263 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1264 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1265 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1266 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1267 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1268 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1270 for (final DataSchemaNode caseNode : augmentedNodes) {
1271 if (caseNode != null) {
1272 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1273 caseTypeBuilder.addImplementsType(targetType);
1274 defaultImplementedInterace(caseTypeBuilder);
1276 CaseSchemaNode node = null;
1277 final String caseLocalName = caseNode.getQName().getLocalName();
1278 if (caseNode instanceof CaseSchemaNode) {
1279 node = (CaseSchemaNode) caseNode;
1280 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1281 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1282 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1283 if (dataSchemaNode instanceof ChoiceSchemaNode
1284 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1285 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1290 node = findNamedCase(targetNode, caseLocalName);
1292 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1293 if (childNodes != null) {
1294 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1297 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1298 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1303 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1304 final SchemaPath nodePath = targetNode.getPath();
1305 final SchemaPath parentSp = nodePath.getParent();
1306 if (parentSp.getParent() == null) {
1307 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1310 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1311 GeneratedTypeBuilder childOfType = null;
1312 if (parent instanceof CaseSchemaNode) {
1313 childOfType = findCaseByPath(parent.getPath());
1314 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1315 childOfType = findChildNodeByPath(parent.getPath());
1316 } else if (parent instanceof GroupingDefinition) {
1317 childOfType = findGroupingByPath(parent.getPath());
1320 if (childOfType == null) {
1321 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1327 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1328 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1329 return cases.isEmpty() ? null : cases.get(0);
1332 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1333 // New parser with encapsulated type
1334 if (leaf.getPath().equals(type.getPath())) {
1338 // Embedded type definition with new parser. Also takes care of the old parser with bits
1339 if (leaf.getPath().equals(type.getPath().getParent())) {
1346 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1347 final List<PatternConstraint> patternConstraints) {
1348 if (!patternConstraints.isEmpty()) {
1349 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1350 .append(BindingMapping.getPropertyName(leafName));
1351 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1352 typeProvider.resolveRegExpressions(patternConstraints));
1357 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1359 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1360 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1361 * @param module Module in which type was defined
1362 * @return boolean value
1364 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1366 * <li>true - in other cases</li>
1369 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1370 final ModuleContext context, final boolean inGrouping) {
1371 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1375 final Module parentModule = findParentModule(schemaContext, leaf);
1376 Type returnType = null;
1378 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1379 if (isInnerType(leaf, typeDef)) {
1380 if (typeDef instanceof EnumTypeDefinition) {
1381 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1382 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1383 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1384 typeBuilder, context);
1385 if (enumBuilder != null) {
1386 returnType = enumBuilder.toInstance(typeBuilder);
1388 typeProvider.putReferencedType(leaf.getPath(), returnType);
1389 } else if (typeDef instanceof UnionTypeDefinition) {
1390 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1391 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1392 // Store the inner type within the union so that we can find the reference for it
1393 context.addInnerTypedefType(typeDef.getPath(), returnType);
1394 } else if (typeDef instanceof BitsTypeDefinition) {
1395 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1397 if (genTOBuilder != null) {
1398 returnType = genTOBuilder.build();
1401 // It is constrained version of already declared type (inner declared type exists,
1402 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1403 // In order to get proper class we need to look up closest derived type
1404 // and apply restrictions from leaf type
1405 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1406 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1407 restrictions, inGrouping);
1408 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1411 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1412 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1413 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1416 if (returnType == null) {
1420 if (typeDef instanceof EnumTypeDefinition) {
1421 typeProvider.putReferencedType(leaf.getPath(), returnType);
1424 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1425 processContextRefExtension(leaf, getter, parentModule);
1429 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1430 // Returns DerivedType in case of new parser.
1431 final TypeDefinition<?> baseType = typeDef.getBaseType();
1432 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1435 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1436 final Module module) {
1437 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1438 final QName nodeType = node.getNodeType();
1439 if ("context-reference".equals(nodeType.getLocalName())) {
1440 final String nodeParam = node.getNodeParameter();
1441 IdentitySchemaNode identity = null;
1442 String basePackageName = null;
1443 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1444 final Iterator<String> iterator = splittedElement.iterator();
1445 final int length = Iterables.size(splittedElement);
1447 identity = findIdentityByName(module.getIdentities(), iterator.next());
1448 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1449 } else if (length == 2) {
1450 final String prefix = iterator.next();
1451 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1452 if (dependentModule == null) {
1453 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1456 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1457 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1459 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1462 if (identity == null) {
1463 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1467 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1468 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1469 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1470 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1475 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1476 for (final IdentitySchemaNode id : identities) {
1477 if (id.getQName().getLocalName().equals(name)) {
1484 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1485 for (final ModuleImport imp : imports) {
1486 if (imp.getPrefix().equals(prefix)) {
1487 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1493 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1494 final boolean isReadOnly) {
1495 if (leaf != null && toBuilder != null) {
1497 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1498 if (typeDef instanceof UnionTypeDefinition) {
1499 // GeneratedType for this type definition should have be already created
1500 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1501 returnType = mc.getTypedefs().get(typeDef.getPath());
1502 if (returnType == null) {
1503 // This may still be an inner type, try to find it
1504 returnType = mc.getInnerType(typeDef.getPath());
1506 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1507 // Annonymous enumeration (already generated, since it is inherited via uses).
1508 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1509 QName qname = originalLeaf.getQName();
1510 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1512 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1514 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1520 * Converts <code>leaf</code> schema node to property of generated TO builder.
1522 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1523 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1524 * @param returnType property type
1525 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1526 * @return boolean value
1528 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1529 * name equals null or if leaf is added by <i>uses</i>.</li>
1530 * <li>true - other cases</li>
1533 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1534 final Type returnType, final boolean isReadOnly) {
1535 if (returnType == null) {
1538 final String leafName = leaf.getQName().getLocalName();
1539 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1540 propBuilder.setReadOnly(isReadOnly);
1541 propBuilder.setReturnType(returnType);
1542 addComment(propBuilder, leaf);
1544 toBuilder.addEqualsIdentity(propBuilder);
1545 toBuilder.addHashIdentity(propBuilder);
1546 toBuilder.addToStringProperty(propBuilder);
1551 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1553 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1554 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1555 * @param module module
1556 * @return boolean value
1558 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1559 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1560 * <li>false - other cases</li>
1563 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1564 final ModuleContext context, final boolean inGrouping) {
1565 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1569 final QName nodeName = node.getQName();
1571 final TypeDefinition<?> typeDef = node.getType();
1572 final Module parentModule = findParentModule(schemaContext, node);
1574 Type returnType = null;
1575 if (typeDef.getBaseType() == null) {
1576 if (typeDef instanceof EnumTypeDefinition) {
1577 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1578 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1579 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1580 typeBuilder, context);
1581 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1582 typeProvider.putReferencedType(node.getPath(), returnType);
1583 } else if (typeDef instanceof UnionTypeDefinition) {
1584 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1585 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1586 } else if (typeDef instanceof BitsTypeDefinition) {
1587 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1588 node, parentModule);
1589 returnType = genTOBuilder.build();
1591 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1592 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1593 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1596 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1597 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1598 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1601 constructGetter(typeBuilder, listTypeFor(returnType), node);
1605 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1606 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1607 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1608 returnTypeBuilder.setIsUnion(true);
1609 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1610 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1611 returnTypeBuilder.setModuleName(parentModule.getName());
1612 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1614 genTOBuilder.setTypedef(true);
1615 genTOBuilder.setIsUnion(true);
1616 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1618 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1622 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1623 final GeneratedTransferObject returnType, final Module parentModule) {
1624 // Append enclosing path hierarchy without dots
1625 final StringBuilder sb = new StringBuilder();
1626 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1627 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1628 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1629 unionBuilder.setIsUnionBuilder(true);
1631 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1632 method.setReturnType(returnType);
1633 method.addParameter(STRING, "defaultValue");
1634 method.setAccessModifier(AccessModifier.PUBLIC);
1635 method.setStatic(true);
1637 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1638 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1641 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1642 final SchemaNode schemaNode) {
1643 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1646 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1647 final SchemaNode schemaNode, final Type baseInterface) {
1648 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1649 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1653 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1654 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1655 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1656 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1657 * If <code>schemaNode</code> is instance of
1658 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1659 * which are specified in <i>uses</i>.
1661 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1662 * @param schemaNode schema node for which is created generated type builder
1663 * @param parent parent type (can be null)
1664 * @return generated type builder <code>schemaNode</code>
1666 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1667 final Type baseInterface, final ModuleContext context) {
1668 JavaTypeName name = renames.get(schemaNode);
1670 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1673 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1674 it.addImplementsType(baseInterface);
1675 if (!(schemaNode instanceof GroupingDefinition)) {
1676 it.addImplementsType(augmentable(it));
1678 if (schemaNode instanceof DataNodeContainer) {
1679 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1680 groupingsToGenTypes(context, containerSchema.getGroupings());
1681 addImplementedInterfaceFromUses(containerSchema, it);
1688 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1689 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1690 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1692 * @param packageName string with the package name to which returning generated type builder belongs
1693 * @param schemaNode schema node which provide data about the schema node name
1694 * @param prefix return type name prefix
1695 * @return generated type builder for <code>schemaNode</code>
1696 * @throws IllegalArgumentException
1698 * <li>if <code>schemaNode</code> is null</li>
1699 * <li>if <code>packageName</code> is null</li>
1700 * <li>if QName of schema node is null</li>
1701 * <li>if schemaNode name is null</li>
1704 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1705 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1706 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1707 final String schemaNodeName = schemaNode.getQName().getLocalName();
1708 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1710 // FIXME: Validation of name conflict
1711 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1712 final Module module = findParentModule(schemaContext, schemaNode);
1713 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1714 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1716 addCodegenInformation(newType, module, schemaNode);
1717 newType.setSchemaPath(schemaNode.getPath());
1718 newType.setModuleName(module.getName());
1720 final String packageName = identifier.packageName();
1721 final String simpleName = identifier.simpleName();
1722 if (!genTypeBuilders.containsKey(packageName)) {
1723 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1724 builders.put(simpleName, newType);
1725 genTypeBuilders.put(packageName, builders);
1727 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1728 if (!builders.containsKey(simpleName)) {
1729 builders.put(simpleName, newType);
1736 * Creates the name of the getter method name from <code>localName</code>.
1738 * @param localName string with the name of the getter method
1739 * @param returnType return type
1740 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1742 public static String getterMethodName(final String localName, final Type returnType) {
1743 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1747 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1748 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1749 * and <code>returnType</code> information are added to the builder.
1751 * @param interfaceBuilder generated type builder for which the getter method should be created
1752 * @param returnType type which represents the return type of the getter method
1753 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1754 * @param comment string with comment for the getter method
1755 * @param status status from yang file, for deprecated annotation
1756 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1758 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1759 final SchemaNode node) {
1760 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1761 getterMethodName(node.getQName().getLocalName(), returnType));
1762 getMethod.setReturnType(returnType);
1764 annotateDeprecatedIfNecessary(node, getMethod);
1765 addComment(getMethod, node);
1770 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1771 final ListSchemaNode node) {
1772 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1773 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1774 getMethod.setReturnType(returnType).setDefault(true);
1775 annotateDeprecatedIfNecessary(node, getMethod);
1779 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1782 * @param basePackageName string contains the module package name
1783 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1784 * or as a property to <code>genTOBuilder</code> if is part of the list key
1785 * @param typeBuilder generated type builder for the list schema node
1786 * @param genTOBuilder generated TO builder for the list keys
1787 * @param listKeys list of string which contains names of the list keys
1788 * @param module current module
1789 * @throws IllegalArgumentException
1791 * <li>if <code>schemaNode</code> equals null</li>
1792 * <li>if <code>typeBuilder</code> equals null</li>
1795 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1796 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1797 final List<String> listKeys, final boolean inGrouping) {
1798 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1799 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1801 if (schemaNode instanceof LeafSchemaNode) {
1802 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1803 final String leafName = leaf.getQName().getLocalName();
1804 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1805 if (listKeys.contains(leafName)) {
1807 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1809 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1812 } else if (!schemaNode.isAddedByUses()) {
1813 if (schemaNode instanceof LeafListSchemaNode) {
1814 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1815 } else if (schemaNode instanceof ContainerSchemaNode) {
1816 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1817 (ContainerSchemaNode) schemaNode, inGrouping);
1818 } else if (schemaNode instanceof ChoiceSchemaNode) {
1819 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1820 } else if (schemaNode instanceof ListSchemaNode) {
1821 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1822 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1823 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1828 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1829 final GeneratedTOBuilder genTOBuilder) {
1830 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1832 if (genTOBuilder != null) {
1833 final GeneratedTransferObject genTO = genTOBuilder.build();
1834 // Add Identifiable.getKey() for items
1835 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1836 .addAnnotation(OVERRIDE_ANNOTATION);
1837 context.addGeneratedTOBuilder(genTOBuilder);
1842 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1844 * @param list of string with names of the list keys
1845 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1846 * an empty list is returned.
1848 private static List<String> listKeys(final ListSchemaNode list) {
1849 final List<QName> keyDefinition = list.getKeyDefinition();
1850 switch (keyDefinition.size()) {
1852 return Collections.emptyList();
1854 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1856 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1857 for (final QName keyDef : keyDefinition) {
1858 listKeys.add(keyDef.getLocalName());
1865 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1866 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1867 * enclosing transfer objects.
1869 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1870 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1871 * @param leaf string with name for generated TO builder
1872 * @param parentModule parent module
1873 * @return generated TO builder for <code>typeDef</code>
1875 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1876 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1877 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1878 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1880 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1881 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1882 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1883 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1884 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1886 for (GeneratedTOBuilder builder : types) {
1887 if (builder.isUnion()) {
1888 final GeneratedTransferObject type = builder.build();
1889 createUnionBuilder(builder, typeBuilder, type, parentModule);
1893 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1897 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1898 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1899 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1902 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1903 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1904 * @param leaf string with name for generated TO builder
1905 * @param parentModule parent module
1906 * @return generated TO builder for <code>typeDef</code>
1908 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1909 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1910 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1911 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1912 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1913 return genTOBuilder;
1917 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1918 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1919 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1920 * to <code>builder</code>
1922 * @param dataNodeContainer element which contains the list of used YANG groupings
1923 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1924 * @return generated type builder with all implemented types
1926 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1927 final GeneratedTypeBuilder builder) {
1928 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1929 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1930 if (genType == null) {
1931 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1932 + builder.getName());
1935 builder.addImplementsType(genType.build());
1940 private JavaTypeName findAliasByPath(final SchemaPath path) {
1941 for (final ModuleContext ctx : genCtx.values()) {
1942 final JavaTypeName result = ctx.getAlias(path);
1943 if (result != null) {
1950 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1951 for (final ModuleContext ctx : genCtx.values()) {
1952 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1953 if (result != null) {
1960 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1961 for (final ModuleContext ctx : genCtx.values()) {
1962 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1963 if (result != null) {
1970 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1971 for (final ModuleContext ctx : genCtx.values()) {
1972 final GeneratedTypeBuilder result = ctx.getCase(path);
1973 if (result != null) {
1980 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1981 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1982 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1985 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1986 switch (node.getStatus()) {
1988 // FIXME: we really want to use a pre-made annotation
1989 builder.addAnnotation(DEPRECATED_ANNOTATION);
1992 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
1998 throw new IllegalStateException("Unhandled status in " + node);
2002 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2003 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2006 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2007 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
2011 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2012 final Type classType) {
2013 final MethodSignatureBuilder ret = typeBuilder
2014 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2015 .setAccessModifier(AccessModifier.PUBLIC)
2016 .setReturnType(classType(classType));
2017 ret.addAnnotation(OVERRIDE_ANNOTATION);