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 input = context.getChildNode(orig.getInput().getPath()).build();
441 output = context.getChildNode(orig.getOutput().getPath()).build();
443 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
444 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
447 if (!(parentSchema instanceof GroupingDefinition)) {
448 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
449 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
450 // and do not capture an actual instantiation.
451 final QName qname = action.getQName();
452 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
453 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
454 BindingMapping.getClassName(qname)));
455 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
456 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
458 annotateDeprecatedIfNecessary(action, builder);
459 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
460 : action(parent, input, output));
462 addCodegenInformation(builder, context.module(), action);
463 context.addChildNodeType(action, builder);
468 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
469 for (UsesNode uses : parent.getUses()) {
470 final GroupingDefinition grp = findUsedGrouping(uses);
471 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
472 if (found.isPresent()) {
473 final ActionDefinition result = found.get();
474 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
478 return Optional.empty();
481 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
482 final ContainerSchemaNode schema, final boolean inGrouping) {
483 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
484 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
485 return genType.build();
489 * Converts all <b>RPCs</b> input and output substatements of the module
490 * to the list of <code>Type</code> objects. In addition are to containers
491 * and lists which belong to input or output also part of returning list.
494 * module from which is obtained set of all rpc objects to
496 * @throws IllegalArgumentException
498 * <li>if the module is null</li>
499 * <li>if the name of module is null</li>
501 * @throws IllegalStateException
502 * if set of rpcs from module is null
504 private void rpcMethodsToGenType(final ModuleContext context) {
505 final Module module = context.module();
506 checkArgument(module.getName() != null, "Module name cannot be NULL.");
507 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
508 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
509 if (rpcDefinitions.isEmpty()) {
513 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
514 interfaceBuilder.addImplementsType(RPC_SERVICE);
516 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
518 for (final RpcDefinition rpc : rpcDefinitions) {
520 final String rpcName = BindingMapping.getClassName(rpc.getQName());
521 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
522 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
524 // Do not refer to annotation class, as it may not be available at runtime
525 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
526 addComment(method, rpc);
528 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
529 method.setReturnType(listenableFutureTypeFor(
530 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
534 context.addTopLevelNodeType(interfaceBuilder);
537 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
538 final ContainerSchemaNode schema, final Type type) {
539 processUsesAugments(schema, context, false);
540 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
541 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
543 addImplementedInterfaceFromUses(schema, outType);
544 outType.addImplementsType(type);
545 outType.addImplementsType(augmentable(outType));
546 defaultImplementedInterace(outType);
547 annotateDeprecatedIfNecessary(rpc, outType);
548 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
549 context.addChildNodeType(schema, outType);
550 return outType.build();
554 * Converts all <b>notifications</b> of the module to the list of
555 * <code>Type</code> objects. In addition are to this list added containers
556 * and lists which are part of this notification.
559 * module from which is obtained set of all notification objects
560 * to iterate over them
561 * @throws IllegalArgumentException
563 * <li>if the module equals null</li>
564 * <li>if the name of module equals null</li>
566 * @throws IllegalStateException
567 * if set of notifications from module is null
569 private void notificationsToGenType(final ModuleContext context) {
570 final Module module = context.module();
571 checkArgument(module.getName() != null, "Module name cannot be NULL.");
572 final Set<NotificationDefinition> notifications = module.getNotifications();
573 if (notifications.isEmpty()) {
577 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
578 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
580 for (final NotificationDefinition notification : notifications) {
581 if (notification != null) {
582 processUsesAugments(notification, context, false);
584 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
585 context.modulePackageName(), notification, DATA_OBJECT, context);
586 defaultImplementedInterace(notificationInterface);
587 annotateDeprecatedIfNecessary(notification, notificationInterface);
588 notificationInterface.addImplementsType(NOTIFICATION);
589 context.addChildNodeType(notification, notificationInterface);
591 // Notification object
592 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
593 notification.getChildNodes(), false);
595 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
596 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
597 .setReturnType(primitiveVoidType()), notification);
601 addCodegenInformation(listenerInterface, module, "notifications", notifications);
602 context.addTopLevelNodeType(listenerInterface);
605 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
606 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
607 final boolean inGrouping) {
608 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
609 if (notifications.isEmpty()) {
613 for (NotificationDefinition notif : notifications) {
614 if (notif.isAugmenting()) {
617 if (parentSchema instanceof GroupingDefinition) {
618 // Notifications cannot be really established, as they lack instantiation context, which would be
619 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
623 processUsesAugments(notif, context, false);
625 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
626 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
627 defaultImplementedInterace(notifInterface);
628 annotateDeprecatedIfNecessary(notif, notifInterface);
630 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
631 : instanceNotification(notifInterface, parent));
632 context.addChildNodeType(notif, notifInterface);
634 // Notification object
635 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
640 * Converts all <b>identities</b> of the module to the list of
641 * <code>Type</code> objects.
644 * module from which is obtained set of all identity objects to
646 * @param schemaContext
647 * schema context only used as input parameter for method
648 * {@link BindingGeneratorImpl#identityToGenType}
651 private void allIdentitiesToGenTypes(final ModuleContext context) {
652 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
654 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
655 for (final IdentitySchemaNode identity : schemaIdentities) {
656 identityToGenType(context, identity);
662 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
663 * created transport object builder. If identity contains base identity then
664 * reference to base identity is added to superior identity as its extend.
665 * If identity doesn't contain base identity then only reference to abstract
666 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
667 * BaseIdentity} is added
671 * @param basePackageName
672 * string contains the module package name
674 * IdentitySchemaNode which contains data about identity
676 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
677 if (identity == null) {
681 JavaTypeName name = renames.get(identity);
683 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
684 BindingMapping.getClassName(identity.getQName()));
687 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
688 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
689 if (!baseIdentities.isEmpty()) {
690 for (IdentitySchemaNode baseIdentity : baseIdentities) {
691 JavaTypeName base = renames.get(baseIdentity);
693 final QName qname = baseIdentity.getQName();
694 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
695 BindingMapping.getClassName(qname));
698 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
699 newType.addImplementsType(gto);
702 newType.addImplementsType(BASE_IDENTITY);
705 final Module module = context.module();
706 addCodegenInformation(newType, module, identity);
707 newType.setModuleName(module.getName());
708 newType.setSchemaPath(identity.getPath());
710 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
711 identity.getQName().getLocalName());
713 context.addIdentityType(identity, newType);
716 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
717 final JavaTypeName yangModuleInfo, final String localName) {
718 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
719 new SimpleImmutableEntry<>(yangModuleInfo, localName));
723 * Converts all <b>groupings</b> of the module to the list of
724 * <code>Type</code> objects. Firstly are groupings sorted according mutual
725 * dependencies. At least dependent (independent) groupings are in the list
726 * saved at first positions. For every grouping the record is added to map
727 * {@link ModuleContext#groupings allGroupings}
732 * collection of groupings from which types will be generated
735 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
736 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
737 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
738 // node of grouping is resolved to the method.
739 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
740 narrowImplementedInterface(genType);
741 annotateDeprecatedIfNecessary(grouping, genType);
742 context.addGroupingType(grouping, genType);
743 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
744 groupingsToGenTypes(context, grouping.getGroupings());
745 processUsesAugments(grouping, context, true);
746 actionsToGenType(context, genType, grouping, null, true);
747 notificationsToGenType(context, genType, grouping, null, true);
752 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
753 * <code>enumTypeDef</code> item is added to builder with its name and value.
755 * @param enumTypeDef EnumTypeDefinition contains enum data
756 * @param enumName string contains name which will be assigned to enumeration builder
757 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
758 * @param module Module in which type should be generated
759 * @return enumeration builder which contains data from <code>enumTypeDef</code>
761 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
762 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
763 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
764 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
765 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
766 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
767 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
774 * Generates type builder for <code>module</code>.
776 * @param module Module which is source of package name for generated type builder
777 * @param postfix string which is added to the module class name representation as suffix
778 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
779 * @throws IllegalArgumentException if <code>module</code> is null
781 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
782 final Module module = context.module();
783 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
784 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
785 JavaTypeName.create(context.modulePackageName(), moduleName));
787 moduleBuilder.setModuleName(moduleName);
788 addCodegenInformation(moduleBuilder, module);
789 return moduleBuilder;
793 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
794 * In addition there are also generated types for all containers, list and choices which are child of
795 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
797 * @param augmentPackageName string with the name of the package to which the augmentation belongs
798 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
799 * @param module current module
800 * @throws IllegalArgumentException
802 * <li>if <code>augmentPackageName</code> equals null</li>
803 * <li>if <code>augSchema</code> equals null</li>
805 * @throws IllegalStateException
806 * if augment target path is null
808 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
809 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
810 checkState(augSchema.getTargetPath() != null,
811 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
813 processUsesAugments(augSchema, context, false);
814 final SchemaPath targetPath = augSchema.getTargetPath();
815 SchemaNode targetSchemaNode = null;
817 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
818 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
819 if (targetSchemaNode instanceof DerivableSchemaNode) {
820 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
822 if (targetSchemaNode == null) {
823 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
824 + " in module " + context.module().getName());
827 if (targetSchemaNode == null) {
828 throw new IllegalArgumentException("augment target not found: " + targetPath);
831 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
832 if (targetTypeBuilder == null) {
833 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
835 if (targetTypeBuilder == null) {
836 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
839 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
840 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
841 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
844 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
845 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
849 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
850 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
851 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
852 checkState(augSchema.getTargetPath() != null,
853 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
855 processUsesAugments(augSchema, context, inGrouping);
856 final SchemaPath targetPath = augSchema.getTargetPath();
857 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
858 if (targetSchemaNode == null) {
859 throw new IllegalArgumentException("augment target not found: " + targetPath);
862 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
863 if (targetTypeBuilder == null) {
864 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
866 if (targetTypeBuilder == null) {
867 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
870 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
871 if (usesNodeParent instanceof SchemaNode) {
872 addRawAugmentGenTypeDefinition(context,
873 packageNameForAugmentedGeneratedType(context.modulePackageName(),
874 ((SchemaNode) usesNodeParent).getPath()),
875 targetTypeBuilder.build(), augSchema, inGrouping);
877 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
880 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
881 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
885 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
886 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
888 if (targetGrouping instanceof GroupingDefinition) {
889 return (GroupingDefinition) targetGrouping;
892 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
896 * Convenient method to find node added by uses statement.
898 * @param targetPath node path
899 * @param parentUsesNode parent of uses node
900 * @return node from its original location in grouping
902 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
903 SchemaNode result = findUsedGrouping(parentUsesNode);
904 for (final QName node : targetPath.getPathFromRoot()) {
905 if (result instanceof DataNodeContainer) {
906 final QName resultNode = node.withModule(result.getQName().getModule());
907 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
908 } else if (result instanceof ChoiceSchemaNode) {
909 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
912 if (result == null) {
916 if (result instanceof DerivableSchemaNode) {
917 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
918 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
919 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
920 result = originalNode.get();
924 if (result instanceof DataSchemaNode) {
925 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
926 if (resultDataSchemaNode.isAddedByUses()) {
927 // The original node is required, but we have only the copy of
928 // the original node.
929 // Maybe this indicates a bug in Yang parser.
930 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
933 return resultDataSchemaNode;
936 throw new IllegalStateException(
937 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
942 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
943 * of augmented node with serial number as suffix.
945 * @param context current module
946 * @param augmentPackageName string with contains the package name to which the augment belongs
947 * @param basePackageName string with the package name to which the augmented node belongs
948 * @param targetTypeRef target type
949 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
950 * @return generated type builder for augment
952 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
953 final String augmentPackageName, final Type targetTypeRef,
954 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
955 Map<String, GeneratedTypeBuilder> augmentBuilders =
956 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
957 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
960 if (augIdentifier != null) {
961 augTypeName = BindingMapping.getClassName(augIdentifier);
963 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
966 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
967 JavaTypeName.create(augmentPackageName, augTypeName));
969 augTypeBuilder.addImplementsType(DATA_OBJECT);
970 defaultImplementedInterace(augTypeBuilder);
972 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
973 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
974 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
976 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
977 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
978 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
980 augmentBuilders.put(augTypeName, augTypeBuilder);
982 if (!augSchema.getChildNodes().isEmpty()) {
983 context.addTypeToAugmentation(augTypeBuilder, augSchema);
986 context.addAugmentType(augTypeBuilder);
987 return augTypeBuilder;
990 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
991 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
992 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
996 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
997 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
998 final QName nodeType = unknownSchemaNode.getNodeType();
999 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1000 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1001 return unknownSchemaNode.getNodeParameter();
1008 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1009 * consists from name of augmented node and serial number of its augmentation.
1011 * @param builders map of builders which were created in the package to which the augmentation belongs
1012 * @param genTypeName string with name of augmented node
1013 * @return string with unique name for augmentation builder
1015 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1017 if (builders != null) {
1018 while (builders.containsKey(genTypeName + index)) {
1022 return genTypeName + index;
1026 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1027 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1028 * already part of them).
1030 * @param module current module
1031 * @param parent generated type builder which represents any node. The subnodes of this node are added
1032 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1033 * container, choice.
1034 * @param childOf parent type
1035 * @param schemaNodes set of data schema nodes which are the children of the node for which
1036 * <code>typeBuilder</code> was created
1037 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1038 * child nodes) could be added to it.
1040 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1041 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1042 if (schemaNodes != null && parent != null) {
1043 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1044 for (final DataSchemaNode schemaNode : schemaNodes) {
1045 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1046 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1054 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1057 * @param module current module
1058 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1059 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1060 * container, choice.
1061 * @param childOf parent type
1062 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1064 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1065 * The getter method could be added to it.
1067 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1068 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1069 final boolean inGrouping) {
1070 if (schemaNodes != null && typeBuilder != null) {
1071 final Type baseInterface = childOf(typeBuilder);
1072 for (final DataSchemaNode schemaNode : schemaNodes) {
1073 if (!schemaNode.isAugmenting()) {
1074 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1082 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1084 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1085 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1086 * @param childOf parent type
1087 * @param module current module
1089 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1090 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1091 if (node != null && typeBuilder != null) {
1092 if (node instanceof LeafSchemaNode) {
1093 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1094 } else if (node instanceof LeafListSchemaNode) {
1095 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1096 } else if (node instanceof ContainerSchemaNode) {
1097 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1098 } else if (node instanceof ListSchemaNode) {
1099 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1100 } else if (node instanceof ChoiceSchemaNode) {
1101 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1102 } else if (node instanceof AnyXmlSchemaNode || node instanceof AnyDataSchemaNode) {
1103 opaqueToGeneratedType(context, typeBuilder, node);
1105 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1106 typeBuilder.getFullyQualifiedName());
1112 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1113 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1114 * and names of all parents node.
1116 * @param context current module
1117 * @param basePackageName string with the module package name
1118 * @param parent parent type
1119 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1121 * @throws IllegalArgumentException
1123 * <li>if <code>basePackageName</code> is null</li>
1124 * <li>if <code>choiceNode</code> is null</li>
1127 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1128 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1129 if (!choiceNode.isAddedByUses()) {
1130 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1131 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1132 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1133 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1134 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1135 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1137 final GeneratedType choiceType = choiceTypeBuilder.build();
1138 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1140 constructGetter(parent, choiceType, choiceNode);
1144 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1145 final DataSchemaNode anyNode) {
1146 if (!anyNode.isAddedByUses()) {
1147 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1148 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1149 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1150 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1151 defaultImplementedInterace(anyxmlTypeBuilder);
1152 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1153 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1155 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1160 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1161 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1162 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1163 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1165 * @param context current module context
1166 * @param refChoiceType type which represents superior <i>case</i>
1167 * @param choiceNode choice case node which is mapped to generated type
1168 * @throws IllegalArgumentException
1170 * <li>if <code>refChoiceType</code> equals null</li>
1171 * <li>if <code>caseNodes</code> equals null</li>
1174 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1175 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1176 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1177 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1179 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1180 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1181 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1182 caseTypeBuilder.addImplementsType(refChoiceType);
1183 defaultImplementedInterace(caseTypeBuilder);
1184 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1185 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1186 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1187 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1188 if (caseChildNodes != null) {
1189 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1191 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1192 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1194 if (parent instanceof AugmentationSchemaNode) {
1195 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1196 final SchemaPath targetPath = augSchema.getTargetPath();
1197 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1198 if (targetSchemaNode instanceof DataSchemaNode
1199 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1200 if (targetSchemaNode instanceof DerivableSchemaNode) {
1201 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1204 if (targetSchemaNode == null) {
1205 throw new IllegalStateException(
1206 "Failed to find target node from grouping for augmentation " + augSchema
1207 + " in module " + context.module().getName());
1210 parent = targetSchemaNode;
1213 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1214 Type childOfType = findChildNodeByPath(parent.getPath());
1215 if (childOfType == null) {
1216 childOfType = findGroupingByPath(parent.getPath());
1218 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1220 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1225 processUsesAugments(caseNode, context, inGrouping);
1230 * Generates list of generated types for all the cases of a choice which are added to the choice through
1233 * @param module current module
1234 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1235 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1236 * of the augmenting choice will belong to pcg2.
1237 * @param targetType Type which represents target choice
1238 * @param targetNode node which represents target choice
1239 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1241 * @throws IllegalArgumentException
1243 * <li>if <code>basePackageName</code> is null</li>
1244 * <li>if <code>targetType</code> is null</li>
1245 * <li>if <code>augmentedNodes</code> is null</li>
1248 // FIXME: nullness rules need to untangled in this method
1249 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1250 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1251 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1252 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1253 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1254 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1256 for (final DataSchemaNode caseNode : augmentedNodes) {
1257 if (caseNode != null) {
1258 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1259 caseTypeBuilder.addImplementsType(targetType);
1260 defaultImplementedInterace(caseTypeBuilder);
1262 CaseSchemaNode node = null;
1263 final String caseLocalName = caseNode.getQName().getLocalName();
1264 if (caseNode instanceof CaseSchemaNode) {
1265 node = (CaseSchemaNode) caseNode;
1266 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1267 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1268 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1269 if (dataSchemaNode instanceof ChoiceSchemaNode
1270 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1271 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1276 node = findNamedCase(targetNode, caseLocalName);
1278 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1279 if (childNodes != null) {
1280 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1283 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1284 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1289 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1290 final SchemaPath nodePath = targetNode.getPath();
1291 final SchemaPath parentSp = nodePath.getParent();
1292 if (parentSp.getParent() == null) {
1293 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1296 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1297 GeneratedTypeBuilder childOfType = null;
1298 if (parent instanceof CaseSchemaNode) {
1299 childOfType = findCaseByPath(parent.getPath());
1300 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1301 childOfType = findChildNodeByPath(parent.getPath());
1302 } else if (parent instanceof GroupingDefinition) {
1303 childOfType = findGroupingByPath(parent.getPath());
1306 if (childOfType == null) {
1307 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1313 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1314 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1315 return cases.isEmpty() ? null : cases.get(0);
1318 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1319 // New parser with encapsulated type
1320 if (leaf.getPath().equals(type.getPath())) {
1324 // Embedded type definition with new parser. Also takes care of the old parser with bits
1325 if (leaf.getPath().equals(type.getPath().getParent())) {
1332 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1333 final List<PatternConstraint> patternConstraints) {
1334 if (!patternConstraints.isEmpty()) {
1335 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1336 .append(BindingMapping.getPropertyName(leafName));
1337 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1338 typeProvider.resolveRegExpressions(patternConstraints));
1343 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1345 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1346 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1347 * @param module Module in which type was defined
1348 * @return boolean value
1350 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1352 * <li>true - in other cases</li>
1355 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1356 final ModuleContext context, final boolean inGrouping) {
1357 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1361 final Module parentModule = findParentModule(schemaContext, leaf);
1362 Type returnType = null;
1364 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1365 if (isInnerType(leaf, typeDef)) {
1366 if (typeDef instanceof EnumTypeDefinition) {
1367 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1368 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1369 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1370 typeBuilder, context);
1371 if (enumBuilder != null) {
1372 returnType = enumBuilder.toInstance(typeBuilder);
1374 typeProvider.putReferencedType(leaf.getPath(), returnType);
1375 } else if (typeDef instanceof UnionTypeDefinition) {
1376 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1377 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1378 // Store the inner type within the union so that we can find the reference for it
1379 context.addInnerTypedefType(typeDef.getPath(), returnType);
1380 } else if (typeDef instanceof BitsTypeDefinition) {
1381 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1383 if (genTOBuilder != null) {
1384 returnType = genTOBuilder.build();
1387 // It is constrained version of already declared type (inner declared type exists,
1388 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1389 // In order to get proper class we need to look up closest derived type
1390 // and apply restrictions from leaf type
1391 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1392 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1393 restrictions, inGrouping);
1394 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1397 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1398 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1399 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1402 if (returnType == null) {
1406 if (typeDef instanceof EnumTypeDefinition) {
1407 typeProvider.putReferencedType(leaf.getPath(), returnType);
1410 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1411 processContextRefExtension(leaf, getter, parentModule);
1415 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1416 // Returns DerivedType in case of new parser.
1417 final TypeDefinition<?> baseType = typeDef.getBaseType();
1418 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1421 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1422 final Module module) {
1423 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1424 final QName nodeType = node.getNodeType();
1425 if ("context-reference".equals(nodeType.getLocalName())) {
1426 final String nodeParam = node.getNodeParameter();
1427 IdentitySchemaNode identity = null;
1428 String basePackageName = null;
1429 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1430 final Iterator<String> iterator = splittedElement.iterator();
1431 final int length = Iterables.size(splittedElement);
1433 identity = findIdentityByName(module.getIdentities(), iterator.next());
1434 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1435 } else if (length == 2) {
1436 final String prefix = iterator.next();
1437 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1438 if (dependentModule == null) {
1439 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1442 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1443 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1445 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1448 if (identity == null) {
1449 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1453 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1454 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1455 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1456 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1461 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1462 for (final IdentitySchemaNode id : identities) {
1463 if (id.getQName().getLocalName().equals(name)) {
1470 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1471 for (final ModuleImport imp : imports) {
1472 if (imp.getPrefix().equals(prefix)) {
1473 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1479 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1480 final boolean isReadOnly) {
1481 if (leaf != null && toBuilder != null) {
1483 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1484 if (typeDef instanceof UnionTypeDefinition) {
1485 // GeneratedType for this type definition should have be already created
1486 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1487 returnType = mc.getTypedefs().get(typeDef.getPath());
1488 if (returnType == null) {
1489 // This may still be an inner type, try to find it
1490 returnType = mc.getInnerType(typeDef.getPath());
1492 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1493 // Annonymous enumeration (already generated, since it is inherited via uses).
1494 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1495 QName qname = originalLeaf.getQName();
1496 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1498 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1500 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1506 * Converts <code>leaf</code> schema node to property of generated TO builder.
1508 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1509 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1510 * @param returnType property type
1511 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1512 * @return boolean value
1514 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1515 * name equals null or if leaf is added by <i>uses</i>.</li>
1516 * <li>true - other cases</li>
1519 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1520 final Type returnType, final boolean isReadOnly) {
1521 if (returnType == null) {
1524 final String leafName = leaf.getQName().getLocalName();
1525 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1526 propBuilder.setReadOnly(isReadOnly);
1527 propBuilder.setReturnType(returnType);
1528 addComment(propBuilder, leaf);
1530 toBuilder.addEqualsIdentity(propBuilder);
1531 toBuilder.addHashIdentity(propBuilder);
1532 toBuilder.addToStringProperty(propBuilder);
1537 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1539 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1540 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1541 * @param module module
1542 * @return boolean value
1544 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1545 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1546 * <li>false - other cases</li>
1549 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1550 final ModuleContext context, final boolean inGrouping) {
1551 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1555 final QName nodeName = node.getQName();
1557 final TypeDefinition<?> typeDef = node.getType();
1558 final Module parentModule = findParentModule(schemaContext, node);
1560 Type returnType = null;
1561 if (typeDef.getBaseType() == null) {
1562 if (typeDef instanceof EnumTypeDefinition) {
1563 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1564 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1565 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1566 typeBuilder, context);
1567 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1568 typeProvider.putReferencedType(node.getPath(), returnType);
1569 } else if (typeDef instanceof UnionTypeDefinition) {
1570 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1571 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1572 } else if (typeDef instanceof BitsTypeDefinition) {
1573 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1574 node, parentModule);
1575 returnType = genTOBuilder.build();
1577 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1578 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1579 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1582 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1583 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1584 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1587 constructGetter(typeBuilder, listTypeFor(returnType), node);
1591 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1592 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1593 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1594 returnTypeBuilder.setIsUnion(true);
1595 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1596 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1597 returnTypeBuilder.setModuleName(parentModule.getName());
1598 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1600 genTOBuilder.setTypedef(true);
1601 genTOBuilder.setIsUnion(true);
1602 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1604 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1608 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1609 final GeneratedTransferObject returnType, final Module parentModule) {
1610 // Append enclosing path hierarchy without dots
1611 final StringBuilder sb = new StringBuilder();
1612 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1613 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1614 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1615 unionBuilder.setIsUnionBuilder(true);
1617 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1618 method.setReturnType(returnType);
1619 method.addParameter(STRING, "defaultValue");
1620 method.setAccessModifier(AccessModifier.PUBLIC);
1621 method.setStatic(true);
1623 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1624 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1627 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1628 final SchemaNode schemaNode) {
1629 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1632 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1633 final SchemaNode schemaNode, final Type baseInterface) {
1634 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1635 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1639 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1640 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1641 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1642 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1643 * If <code>schemaNode</code> is instance of
1644 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1645 * which are specified in <i>uses</i>.
1647 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1648 * @param schemaNode schema node for which is created generated type builder
1649 * @param parent parent type (can be null)
1650 * @return generated type builder <code>schemaNode</code>
1652 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1653 final Type baseInterface, final ModuleContext context) {
1654 JavaTypeName name = renames.get(schemaNode);
1656 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1659 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1660 it.addImplementsType(baseInterface);
1661 if (!(schemaNode instanceof GroupingDefinition)) {
1662 it.addImplementsType(augmentable(it));
1664 if (schemaNode instanceof DataNodeContainer) {
1665 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1666 groupingsToGenTypes(context, containerSchema.getGroupings());
1667 addImplementedInterfaceFromUses(containerSchema, it);
1674 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1675 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1676 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1678 * @param packageName string with the package name to which returning generated type builder belongs
1679 * @param schemaNode schema node which provide data about the schema node name
1680 * @param prefix return type name prefix
1681 * @return generated type builder for <code>schemaNode</code>
1682 * @throws IllegalArgumentException
1684 * <li>if <code>schemaNode</code> is null</li>
1685 * <li>if <code>packageName</code> is null</li>
1686 * <li>if QName of schema node is null</li>
1687 * <li>if schemaNode name is null</li>
1690 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1691 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1692 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1693 final String schemaNodeName = schemaNode.getQName().getLocalName();
1694 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1696 // FIXME: Validation of name conflict
1697 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1698 final Module module = findParentModule(schemaContext, schemaNode);
1699 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1700 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1702 addCodegenInformation(newType, module, schemaNode);
1703 newType.setSchemaPath(schemaNode.getPath());
1704 newType.setModuleName(module.getName());
1706 final String packageName = identifier.packageName();
1707 final String simpleName = identifier.simpleName();
1708 if (!genTypeBuilders.containsKey(packageName)) {
1709 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1710 builders.put(simpleName, newType);
1711 genTypeBuilders.put(packageName, builders);
1713 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1714 if (!builders.containsKey(simpleName)) {
1715 builders.put(simpleName, newType);
1722 * Creates the name of the getter method name from <code>localName</code>.
1724 * @param localName string with the name of the getter method
1725 * @param returnType return type
1726 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1728 public static String getterMethodName(final String localName, final Type returnType) {
1729 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1733 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1734 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1735 * and <code>returnType</code> information are added to the builder.
1737 * @param interfaceBuilder generated type builder for which the getter method should be created
1738 * @param returnType type which represents the return type of the getter method
1739 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1740 * @param comment string with comment for the getter method
1741 * @param status status from yang file, for deprecated annotation
1742 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1744 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1745 final SchemaNode node) {
1746 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1747 getterMethodName(node.getQName().getLocalName(), returnType));
1748 getMethod.setReturnType(returnType);
1750 annotateDeprecatedIfNecessary(node, getMethod);
1751 addComment(getMethod, node);
1756 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1757 final ListSchemaNode node) {
1758 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1759 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1760 getMethod.setReturnType(returnType).setDefault(true);
1761 annotateDeprecatedIfNecessary(node, getMethod);
1765 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1768 * @param basePackageName string contains the module package name
1769 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1770 * or as a property to <code>genTOBuilder</code> if is part of the list key
1771 * @param typeBuilder generated type builder for the list schema node
1772 * @param genTOBuilder generated TO builder for the list keys
1773 * @param listKeys list of string which contains names of the list keys
1774 * @param module current module
1775 * @throws IllegalArgumentException
1777 * <li>if <code>schemaNode</code> equals null</li>
1778 * <li>if <code>typeBuilder</code> equals null</li>
1781 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1782 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1783 final List<String> listKeys, final boolean inGrouping) {
1784 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1785 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1787 if (schemaNode instanceof LeafSchemaNode) {
1788 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1789 final String leafName = leaf.getQName().getLocalName();
1790 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1791 if (listKeys.contains(leafName)) {
1793 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1795 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1798 } else if (!schemaNode.isAddedByUses()) {
1799 if (schemaNode instanceof LeafListSchemaNode) {
1800 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1801 } else if (schemaNode instanceof ContainerSchemaNode) {
1802 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1803 (ContainerSchemaNode) schemaNode, inGrouping);
1804 } else if (schemaNode instanceof ChoiceSchemaNode) {
1805 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1806 } else if (schemaNode instanceof ListSchemaNode) {
1807 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1808 } else if (schemaNode instanceof AnyXmlSchemaNode || schemaNode instanceof AnyDataSchemaNode) {
1809 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1814 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1815 final GeneratedTOBuilder genTOBuilder) {
1816 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1818 if (genTOBuilder != null) {
1819 final GeneratedTransferObject genTO = genTOBuilder.build();
1820 // Add Identifiable.getKey() for items
1821 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1822 .addAnnotation(OVERRIDE_ANNOTATION);
1823 context.addGeneratedTOBuilder(genTOBuilder);
1828 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1830 * @param list of string with names of the list keys
1831 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1832 * an empty list is returned.
1834 private static List<String> listKeys(final ListSchemaNode list) {
1835 final List<QName> keyDefinition = list.getKeyDefinition();
1836 switch (keyDefinition.size()) {
1838 return Collections.emptyList();
1840 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1842 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1843 for (final QName keyDef : keyDefinition) {
1844 listKeys.add(keyDef.getLocalName());
1851 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1852 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1853 * enclosing transfer objects.
1855 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1856 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1857 * @param leaf string with name for generated TO builder
1858 * @param parentModule parent module
1859 * @return generated TO builder for <code>typeDef</code>
1861 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1862 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1863 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1864 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1866 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1867 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1868 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1869 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1870 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1872 for (GeneratedTOBuilder builder : types) {
1873 if (builder.isUnion()) {
1874 final GeneratedTransferObject type = builder.build();
1875 createUnionBuilder(builder, typeBuilder, type, parentModule);
1879 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1883 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1884 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1885 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1888 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1889 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1890 * @param leaf string with name for generated TO builder
1891 * @param parentModule parent module
1892 * @return generated TO builder for <code>typeDef</code>
1894 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1895 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1896 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1897 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1898 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1899 return genTOBuilder;
1903 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1904 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1905 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1906 * to <code>builder</code>
1908 * @param dataNodeContainer element which contains the list of used YANG groupings
1909 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1910 * @return generated type builder with all implemented types
1912 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1913 final GeneratedTypeBuilder builder) {
1914 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1915 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1916 if (genType == null) {
1917 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1918 + builder.getName());
1921 builder.addImplementsType(genType.build());
1926 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1927 for (final ModuleContext ctx : genCtx.values()) {
1928 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1929 if (result != null) {
1936 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1937 for (final ModuleContext ctx : genCtx.values()) {
1938 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1939 if (result != null) {
1946 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1947 for (final ModuleContext ctx : genCtx.values()) {
1948 final GeneratedTypeBuilder result = ctx.getCase(path);
1949 if (result != null) {
1956 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1957 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1958 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1961 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1962 switch (node.getStatus()) {
1965 // FIXME: we really want to use a pre-made annotation
1966 builder.addAnnotation(DEPRECATED_ANNOTATION);
1972 throw new IllegalStateException("Unhandled status in " + node);
1976 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1977 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1980 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1981 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1985 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1986 final Type classType) {
1987 final MethodSignatureBuilder ret = typeBuilder
1988 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1989 .setAccessModifier(AccessModifier.PUBLIC)
1990 .setReturnType(classType(classType));
1991 ret.addAnnotation(OVERRIDE_ANNOTATION);