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.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
34 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
35 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
36 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
38 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
39 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
40 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
42 import com.google.common.base.Splitter;
43 import com.google.common.collect.Iterables;
44 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
45 import java.util.AbstractMap.SimpleImmutableEntry;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.List;
54 import java.util.Optional;
56 import org.eclipse.jdt.annotation.Nullable;
57 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
58 import org.opendaylight.mdsal.binding.model.api.Constant;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
60 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
61 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
62 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
63 import org.opendaylight.mdsal.binding.model.api.Restrictions;
64 import org.opendaylight.mdsal.binding.model.api.Type;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
74 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
75 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
76 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
77 import org.opendaylight.mdsal.binding.model.util.Types;
78 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
79 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
80 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
81 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
82 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
83 import org.opendaylight.yangtools.yang.common.QName;
84 import org.opendaylight.yangtools.yang.common.QNameModule;
85 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
86 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
87 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
92 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
95 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
96 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.Module;
101 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
102 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
103 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
104 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
105 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
107 import org.opendaylight.yangtools.yang.model.api.Status;
108 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
109 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.UsesNode;
111 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
113 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
114 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
115 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
116 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
117 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
118 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
119 import org.slf4j.Logger;
120 import org.slf4j.LoggerFactory;
122 abstract class AbstractTypeGenerator {
123 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
124 private static final Splitter COLON_SPLITTER = Splitter.on(':');
125 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
126 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
127 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
130 * Comparator based on augment target path.
132 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
133 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
134 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
136 while (thisIt.hasNext()) {
137 if (!otherIt.hasNext()) {
141 final int comp = thisIt.next().compareTo(otherIt.next());
147 return otherIt.hasNext() ? -1 : 0;
151 * Constant with the concrete name of identifier.
153 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
156 * Constant with the concrete name of namespace.
158 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
160 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
163 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
164 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
165 * for schema node specified in key part.
167 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
170 * Provide methods for converting YANG types to JAVA types.
172 private final AbstractTypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
177 private final SchemaContext schemaContext;
180 * Holds renamed elements.
182 private final Map<SchemaNode, JavaTypeName> renames;
184 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
185 final Map<SchemaNode, JavaTypeName> renames) {
186 this.schemaContext = requireNonNull(context);
187 this.typeProvider = requireNonNull(typeProvider);
188 this.renames = requireNonNull(renames);
190 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
191 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
192 for (final Module contextModule : contextModules) {
193 contexts.add(moduleToGenTypes(contextModule));
196 contexts.forEach(this::allAugmentsToGenTypes);
199 final Collection<ModuleContext> moduleContexts() {
200 return genCtx.values();
203 final ModuleContext moduleContext(final QNameModule module) {
204 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
207 final AbstractTypeProvider typeProvider() {
211 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
213 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
215 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
216 Set<? extends SchemaNode> nodes);
218 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
220 private ModuleContext moduleToGenTypes(final Module module) {
221 final ModuleContext context = new ModuleContext(module);
222 genCtx.put(module.getQNameModule(), context);
223 allTypeDefinitionsToGenTypes(context);
224 groupingsToGenTypes(context, module.getGroupings());
225 rpcMethodsToGenType(context);
226 allIdentitiesToGenTypes(context);
227 notificationsToGenType(context);
229 if (!module.getChildNodes().isEmpty()) {
230 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
231 context.addModuleNode(moduleType);
232 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
238 * Converts all extended type definitions of module to the list of
239 * <code>Type</code> objects.
242 * module from which is obtained set of type definitions
243 * @throws IllegalArgumentException
245 * <li>if module is null</li>
246 * <li>if name of module is null</li>
248 * @throws IllegalStateException
249 * if set of type definitions from module is null
251 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
252 final Module module = context.module();
253 checkArgument(module.getName() != null, "Module name cannot be NULL.");
254 final DataNodeIterator it = new DataNodeIterator(module);
255 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
256 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
258 for (final TypeDefinition<?> typedef : typeDefinitions) {
259 if (typedef != null) {
260 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
262 context.addTypedefType(typedef, type);
263 context.addTypeToSchema(type,typedef);
269 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
270 final DataSchemaNode node, final boolean inGrouping) {
271 if (node.isAugmenting() || node.isAddedByUses()) {
274 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
275 annotateDeprecatedIfNecessary(node.getStatus(), genType);
277 final Module module = context.module();
278 genType.setModuleName(module.getName());
279 addCodegenInformation(genType, module, node);
280 genType.setSchemaPath(node.getPath());
281 if (node instanceof DataNodeContainer) {
282 context.addChildNodeType(node, genType);
283 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
284 processUsesAugments((DataNodeContainer) node, context, inGrouping);
289 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
290 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
291 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
292 if (genType != null) {
293 constructGetter(parent, genType, node);
294 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
295 actionsToGenType(context, genType, node, null, inGrouping);
299 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
300 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
301 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
302 if (genType != null) {
303 final ParameterizedType listType = listTypeFor(genType);
304 constructGetter(parent, listType, node);
305 constructNonnull(parent, listType, node);
307 final List<String> listKeys = listKeys(node);
308 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
309 if (genTOBuilder != null) {
310 final Type identifierMarker = identifier(genType);
311 final Type identifiableMarker = identifiable(genTOBuilder);
312 genTOBuilder.addImplementsType(identifierMarker);
313 genType.addImplementsType(identifiableMarker);
316 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
318 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
319 if (!schemaNode.isAugmenting()) {
320 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
325 if (genTOBuilder != null) {
326 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
327 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
328 genTOBuilder.setSUID(prop);
331 typeBuildersToGenTypes(context, genType, genTOBuilder);
335 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
336 final boolean inGrouping) {
337 for (final UsesNode usesNode : node.getUses()) {
338 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
339 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
340 processUsesAugments(augment, context, inGrouping);
346 * Converts all <b>augmentation</b> of the module to the list
347 * <code>Type</code> objects.
350 * module from which is obtained list of all augmentation objects
351 * to iterate over them
352 * @throws IllegalArgumentException
354 * <li>if the module is null</li>
355 * <li>if the name of module is null</li>
357 * @throws IllegalStateException
358 * if set of augmentations from module is null
360 private void allAugmentsToGenTypes(final ModuleContext context) {
361 final Module module = context.module();
362 checkArgument(module != null, "Module reference cannot be NULL.");
363 checkArgument(module.getName() != null, "Module name cannot be NULL.");
364 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
366 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
367 augmentationToGenTypes(context, augment);
372 * Returns list of <code>AugmentationSchema</code> objects. The objects are
373 * sorted according to the length of their target path from the shortest to
377 * module from which is obtained list of all augmentation objects
378 * @return list of sorted <code>AugmentationSchema</code> objects obtained
379 * from <code>module</code>
380 * @throws IllegalArgumentException
382 * @throws IllegalStateException
383 * if set of module augmentations is null
385 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
386 checkArgument(module != null, "Module reference cannot be NULL.");
387 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
389 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
390 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
391 sortedAugmentations.sort(AUGMENT_COMP);
393 return sortedAugmentations;
397 * Create GeneratedTypeBuilder object from module argument.
400 * Module object from which builder will be created
401 * @return <code>GeneratedTypeBuilder</code> which is internal
402 * representation of the module
403 * @throws IllegalArgumentException
406 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
407 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
408 final Module module = context.module();
409 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
410 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
412 addCodegenInformation(moduleDataTypeBuilder, module);
413 return moduleDataTypeBuilder;
416 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
417 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
418 for (final ActionDefinition action : parentSchema.getActions()) {
419 if (action.isAugmenting()) {
423 final GeneratedType input;
424 final GeneratedType output;
425 if (action.isAddedByUses()) {
426 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
427 input = context.getChildNode(orig.getInput().getPath()).build();
428 output = context.getChildNode(orig.getOutput().getPath()).build();
430 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
431 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
434 if (!(parentSchema instanceof GroupingDefinition)) {
435 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
436 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
437 // and do not capture an actual instantiation.
438 final QName qname = action.getQName();
439 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
440 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
441 BindingMapping.getClassName(qname)));
442 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
443 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
445 annotateDeprecatedIfNecessary(action.getStatus(), builder);
446 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
447 : action(parent, input, output));
449 addCodegenInformation(builder, context.module(), action);
450 context.addChildNodeType(action, builder);
455 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
456 for (UsesNode uses : parent.getUses()) {
457 final GroupingDefinition grp = findUsedGrouping(uses);
458 final Optional<ActionDefinition> found = grp.getActions().stream()
459 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
460 if (found.isPresent()) {
461 final ActionDefinition result = found.get();
462 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
466 return Optional.empty();
469 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
470 final ContainerSchemaNode schema, final boolean inGrouping) {
471 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
472 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
473 return genType.build();
477 * Converts all <b>RPCs</b> input and output substatements of the module
478 * to the list of <code>Type</code> objects. In addition are to containers
479 * and lists which belong to input or output also part of returning list.
482 * module from which is obtained set of all rpc objects to
484 * @throws IllegalArgumentException
486 * <li>if the module is null</li>
487 * <li>if the name of module is null</li>
489 * @throws IllegalStateException
490 * if set of rpcs from module is null
492 private void rpcMethodsToGenType(final ModuleContext context) {
493 final Module module = context.module();
494 checkArgument(module.getName() != null, "Module name cannot be NULL.");
495 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
496 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
497 if (rpcDefinitions.isEmpty()) {
501 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
502 interfaceBuilder.addImplementsType(RPC_SERVICE);
504 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
506 for (final RpcDefinition rpc : rpcDefinitions) {
508 final String rpcName = BindingMapping.getClassName(rpc.getQName());
509 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
510 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
512 // Do not refer to annotation class, as it may not be available at runtime
513 // FIXME: migrate this to some other annotation type and re-enable
515 // method.addAnnotation("javax.annotation", "CheckReturnValue");
516 addComment(method, rpc);
518 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
519 method.setReturnType(listenableFutureTypeFor(
520 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
524 context.addTopLevelNodeType(interfaceBuilder);
527 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
528 final ContainerSchemaNode schema, final Type type) {
529 processUsesAugments(schema, context, false);
530 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
531 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
533 addImplementedInterfaceFromUses(schema, outType);
534 outType.addImplementsType(type);
535 outType.addImplementsType(augmentable(outType));
536 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
537 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
538 context.addChildNodeType(schema, outType);
539 return outType.build();
543 * Converts all <b>notifications</b> of the module to the list of
544 * <code>Type</code> objects. In addition are to this list added containers
545 * and lists which are part of this notification.
548 * module from which is obtained set of all notification objects
549 * to iterate over them
550 * @throws IllegalArgumentException
552 * <li>if the module equals null</li>
553 * <li>if the name of module equals null</li>
555 * @throws IllegalStateException
556 * if set of notifications from module is null
558 private void notificationsToGenType(final ModuleContext context) {
559 final Module module = context.module();
560 checkArgument(module.getName() != null, "Module name cannot be NULL.");
561 final Set<NotificationDefinition> notifications = module.getNotifications();
562 if (notifications.isEmpty()) {
566 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
567 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
569 for (final NotificationDefinition notification : notifications) {
570 if (notification != null) {
571 processUsesAugments(notification, context, false);
573 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
574 context.modulePackageName(), notification, DATA_OBJECT, context);
575 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
576 notificationInterface.addImplementsType(NOTIFICATION);
577 context.addChildNodeType(notification, notificationInterface);
579 // Notification object
580 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
581 notification.getChildNodes(), false);
583 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
584 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
585 .setReturnType(Types.primitiveVoidType()), notification);
589 addCodegenInformation(listenerInterface, module, "notifications", notifications);
590 context.addTopLevelNodeType(listenerInterface);
594 * Converts all <b>identities</b> of the module to the list of
595 * <code>Type</code> objects.
598 * module from which is obtained set of all identity objects to
600 * @param schemaContext
601 * schema context only used as input parameter for method
602 * {@link BindingGeneratorImpl#identityToGenType}
605 private void allIdentitiesToGenTypes(final ModuleContext context) {
606 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
608 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
609 for (final IdentitySchemaNode identity : schemaIdentities) {
610 identityToGenType(context, identity);
616 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
617 * created transport object builder. If identity contains base identity then
618 * reference to base identity is added to superior identity as its extend.
619 * If identity doesn't contain base identity then only reference to abstract
620 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
621 * BaseIdentity} is added
625 * @param basePackageName
626 * string contains the module package name
628 * IdentitySchemaNode which contains data about identity
630 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
631 if (identity == null) {
635 JavaTypeName name = renames.get(identity);
637 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
638 BindingMapping.getClassName(identity.getQName()));
641 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
642 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
643 if (!baseIdentities.isEmpty()) {
644 for (IdentitySchemaNode baseIdentity : baseIdentities) {
645 JavaTypeName base = renames.get(baseIdentity);
647 final QName qname = baseIdentity.getQName();
648 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
649 BindingMapping.getClassName(qname));
652 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
653 newType.addImplementsType(gto);
656 newType.addImplementsType(BASE_IDENTITY);
659 final Module module = context.module();
660 addCodegenInformation(newType, module, identity);
661 newType.setModuleName(module.getName());
662 newType.setSchemaPath(identity.getPath());
664 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
665 identity.getQName().getLocalName());
667 context.addIdentityType(identity, newType);
670 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
671 final JavaTypeName yangModuleInfo, final String localName) {
672 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
673 new SimpleImmutableEntry<>(yangModuleInfo, localName));
677 * Converts all <b>groupings</b> of the module to the list of
678 * <code>Type</code> objects. Firstly are groupings sorted according mutual
679 * dependencies. At least dependent (independent) groupings are in the list
680 * saved at first positions. For every grouping the record is added to map
681 * {@link ModuleContext#groupings allGroupings}
686 * collection of groupings from which types will be generated
689 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
690 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
691 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
692 // node of grouping is resolved to the method.
693 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
694 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
695 context.addGroupingType(grouping, genType);
696 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
697 groupingsToGenTypes(context, grouping.getGroupings());
698 processUsesAugments(grouping, context, true);
699 actionsToGenType(context, genType, grouping, null, true);
704 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
705 * <code>enumTypeDef</code> item is added to builder with its name and value.
707 * @param enumTypeDef EnumTypeDefinition contains enum data
708 * @param enumName string contains name which will be assigned to enumeration builder
709 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
710 * @param module Module in which type should be generated
711 * @return enumeration builder which contains data from <code>enumTypeDef</code>
713 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
714 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
715 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
716 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
717 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
718 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
719 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
726 * Generates type builder for <code>module</code>.
728 * @param module Module which is source of package name for generated type builder
729 * @param postfix string which is added to the module class name representation as suffix
730 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
731 * @throws IllegalArgumentException if <code>module</code> is null
733 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
734 final Module module = context.module();
735 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
736 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
737 JavaTypeName.create(context.modulePackageName(), moduleName));
739 moduleBuilder.setModuleName(moduleName);
740 addCodegenInformation(moduleBuilder, module);
741 return moduleBuilder;
745 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
746 * In addition there are also generated types for all containers, list and choices which are child of
747 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
749 * @param augmentPackageName string with the name of the package to which the augmentation belongs
750 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
751 * @param module current module
752 * @throws IllegalArgumentException
754 * <li>if <code>augmentPackageName</code> equals null</li>
755 * <li>if <code>augSchema</code> equals null</li>
757 * @throws IllegalStateException
758 * if augment target path is null
760 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
761 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
762 checkState(augSchema.getTargetPath() != null,
763 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
765 processUsesAugments(augSchema, context, false);
766 final SchemaPath targetPath = augSchema.getTargetPath();
767 SchemaNode targetSchemaNode = null;
769 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
770 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
771 if (targetSchemaNode instanceof DerivableSchemaNode) {
772 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
774 if (targetSchemaNode == null) {
775 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
776 + " in module " + context.module().getName());
779 if (targetSchemaNode == null) {
780 throw new IllegalArgumentException("augment target not found: " + targetPath);
783 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
784 if (targetTypeBuilder == null) {
785 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
787 if (targetTypeBuilder == null) {
788 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
791 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
792 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
793 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
796 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
797 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
801 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
802 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
803 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
804 checkState(augSchema.getTargetPath() != null,
805 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
807 processUsesAugments(augSchema, context, inGrouping);
808 final SchemaPath targetPath = augSchema.getTargetPath();
809 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
810 if (targetSchemaNode == null) {
811 throw new IllegalArgumentException("augment target not found: " + targetPath);
814 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
815 if (targetTypeBuilder == null) {
816 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
818 if (targetTypeBuilder == null) {
819 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
822 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
823 if (usesNodeParent instanceof SchemaNode) {
824 addRawAugmentGenTypeDefinition(context,
825 packageNameForAugmentedGeneratedType(context.modulePackageName(),
826 ((SchemaNode) usesNodeParent).getPath()),
827 targetTypeBuilder.build(), augSchema, inGrouping);
829 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
832 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
833 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
837 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
838 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
840 if (targetGrouping instanceof GroupingDefinition) {
841 return (GroupingDefinition) targetGrouping;
844 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
848 * Convenient method to find node added by uses statement.
850 * @param targetPath node path
851 * @param parentUsesNode parent of uses node
852 * @return node from its original location in grouping
854 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
855 SchemaNode result = findUsedGrouping(parentUsesNode);
856 for (final QName node : targetPath.getPathFromRoot()) {
857 if (result instanceof DataNodeContainer) {
858 final QName resultNode = node.withModule(result.getQName().getModule());
859 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
860 } else if (result instanceof ChoiceSchemaNode) {
861 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
864 if (result == null) {
868 if (result instanceof DerivableSchemaNode) {
869 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
870 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
871 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
872 result = originalNode.get();
876 if (result instanceof DataSchemaNode) {
877 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
878 if (resultDataSchemaNode.isAddedByUses()) {
879 // The original node is required, but we have only the copy of
880 // the original node.
881 // Maybe this indicates a bug in Yang parser.
882 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
885 return resultDataSchemaNode;
888 throw new IllegalStateException(
889 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
894 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
895 * of augmented node with serial number as suffix.
897 * @param context current module
898 * @param augmentPackageName string with contains the package name to which the augment belongs
899 * @param basePackageName string with the package name to which the augmented node belongs
900 * @param targetTypeRef target type
901 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
902 * @return generated type builder for augment
904 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
905 final String augmentPackageName, final Type targetTypeRef,
906 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
907 Map<String, GeneratedTypeBuilder> augmentBuilders =
908 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
909 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
912 if (augIdentifier != null) {
913 augTypeName = BindingMapping.getClassName(augIdentifier);
915 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
918 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
919 JavaTypeName.create(augmentPackageName, augTypeName));
921 augTypeBuilder.addImplementsType(DATA_OBJECT);
922 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
923 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
924 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
926 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
927 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
928 augmentBuilders.put(augTypeName, augTypeBuilder);
930 if (!augSchema.getChildNodes().isEmpty()) {
931 context.addTypeToAugmentation(augTypeBuilder, augSchema);
934 context.addAugmentType(augTypeBuilder);
935 return augTypeBuilder;
938 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
939 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
940 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
944 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
945 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
946 final QName nodeType = unknownSchemaNode.getNodeType();
947 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
948 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
949 return unknownSchemaNode.getNodeParameter();
956 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
957 * consists from name of augmented node and serial number of its augmentation.
959 * @param builders map of builders which were created in the package to which the augmentation belongs
960 * @param genTypeName string with name of augmented node
961 * @return string with unique name for augmentation builder
963 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
965 if (builders != null) {
966 while (builders.containsKey(genTypeName + index)) {
970 return genTypeName + index;
974 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
975 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
976 * already part of them).
978 * @param module current module
979 * @param parent generated type builder which represents any node. The subnodes of this node are added
980 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
982 * @param childOf parent type
983 * @param schemaNodes set of data schema nodes which are the children of the node for which
984 * <code>typeBuilder</code> was created
985 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
986 * child nodes) could be added to it.
988 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
989 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
990 if (schemaNodes != null && parent != null) {
991 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
992 for (final DataSchemaNode schemaNode : schemaNodes) {
993 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
994 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1002 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1005 * @param module current module
1006 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1007 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1008 * container, choice.
1009 * @param childOf parent type
1010 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1012 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1013 * The getter method could be added to it.
1015 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1016 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1017 final boolean inGrouping) {
1018 if (schemaNodes != null && typeBuilder != null) {
1019 final Type baseInterface = childOf(typeBuilder);
1020 for (final DataSchemaNode schemaNode : schemaNodes) {
1021 if (!schemaNode.isAugmenting()) {
1022 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1030 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1032 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1033 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1034 * @param childOf parent type
1035 * @param module current module
1037 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1038 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1039 if (node != null && typeBuilder != null) {
1040 if (node instanceof LeafSchemaNode) {
1041 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1042 } else if (node instanceof LeafListSchemaNode) {
1043 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1044 } else if (node instanceof ContainerSchemaNode) {
1045 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1046 } else if (node instanceof ListSchemaNode) {
1047 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1048 } else if (node instanceof ChoiceSchemaNode) {
1049 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1051 // TODO: anyxml not yet supported
1052 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1053 typeBuilder.getFullyQualifiedName());
1059 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1060 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1061 * and names of all parents node.
1063 * @param context current module
1064 * @param basePackageName string with the module package name
1065 * @param parent parent type
1066 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1068 * @throws IllegalArgumentException
1070 * <li>if <code>basePackageName</code> is null</li>
1071 * <li>if <code>choiceNode</code> is null</li>
1074 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1075 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1076 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1078 if (!choiceNode.isAddedByUses()) {
1079 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1080 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1081 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1082 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1083 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1084 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1086 final GeneratedType choiceType = choiceTypeBuilder.build();
1087 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1089 constructGetter(parent, choiceType, choiceNode);
1094 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1095 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1096 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1097 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1099 * @param context current module context
1100 * @param refChoiceType type which represents superior <i>case</i>
1101 * @param choiceNode choice case node which is mapped to generated type
1102 * @throws IllegalArgumentException
1104 * <li>if <code>refChoiceType</code> equals null</li>
1105 * <li>if <code>caseNodes</code> equals null</li>
1108 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1109 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1110 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1111 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1113 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1114 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1115 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1116 caseTypeBuilder.addImplementsType(refChoiceType);
1117 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1118 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1119 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1120 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1121 if (caseChildNodes != null) {
1122 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1124 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1125 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1127 if (parent instanceof AugmentationSchemaNode) {
1128 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1129 final SchemaPath targetPath = augSchema.getTargetPath();
1130 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1131 if (targetSchemaNode instanceof DataSchemaNode
1132 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1133 if (targetSchemaNode instanceof DerivableSchemaNode) {
1134 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1137 if (targetSchemaNode == null) {
1138 throw new IllegalStateException(
1139 "Failed to find target node from grouping for augmentation " + augSchema
1140 + " in module " + context.module().getName());
1143 parent = targetSchemaNode;
1146 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1147 Type childOfType = findChildNodeByPath(parent.getPath());
1148 if (childOfType == null) {
1149 childOfType = findGroupingByPath(parent.getPath());
1151 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1153 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1158 processUsesAugments(caseNode, context, inGrouping);
1163 * Generates list of generated types for all the cases of a choice which are added to the choice through
1166 * @param module current module
1167 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1168 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1169 * of the augmenting choice will belong to pcg2.
1170 * @param targetType Type which represents target choice
1171 * @param targetNode node which represents target choice
1172 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1174 * @throws IllegalArgumentException
1176 * <li>if <code>basePackageName</code> is null</li>
1177 * <li>if <code>targetType</code> is null</li>
1178 * <li>if <code>augmentedNodes</code> is null</li>
1181 // FIXME: nullness rules need to untangled in this method
1182 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1183 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1184 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1185 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1186 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1187 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1189 for (final DataSchemaNode caseNode : augmentedNodes) {
1190 if (caseNode != null) {
1191 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1192 caseTypeBuilder.addImplementsType(targetType);
1194 CaseSchemaNode node = null;
1195 final String caseLocalName = caseNode.getQName().getLocalName();
1196 if (caseNode instanceof CaseSchemaNode) {
1197 node = (CaseSchemaNode) caseNode;
1198 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1199 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1200 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1201 if (dataSchemaNode instanceof ChoiceSchemaNode
1202 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1203 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1208 node = findNamedCase(targetNode, caseLocalName);
1210 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1211 if (childNodes != null) {
1212 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1215 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1216 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1221 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1222 final SchemaPath nodePath = targetNode.getPath();
1223 final SchemaPath parentSp = nodePath.getParent();
1224 if (parentSp.getParent() == null) {
1225 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1228 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1229 GeneratedTypeBuilder childOfType = null;
1230 if (parent instanceof CaseSchemaNode) {
1231 childOfType = findCaseByPath(parent.getPath());
1232 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1233 childOfType = findChildNodeByPath(parent.getPath());
1234 } else if (parent instanceof GroupingDefinition) {
1235 childOfType = findGroupingByPath(parent.getPath());
1238 if (childOfType == null) {
1239 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1245 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1246 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1247 return cases.isEmpty() ? null : cases.get(0);
1250 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1251 // New parser with encapsulated type
1252 if (leaf.getPath().equals(type.getPath())) {
1256 // Embedded type definition with new parser. Also takes care of the old parser with bits
1257 if (leaf.getPath().equals(type.getPath().getParent())) {
1264 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1265 final List<PatternConstraint> patternConstraints) {
1266 if (!patternConstraints.isEmpty()) {
1267 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1268 .append(BindingMapping.getPropertyName(leafName));
1269 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1270 typeProvider.resolveRegExpressions(patternConstraints));
1275 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1277 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1278 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1279 * @param module Module in which type was defined
1280 * @return boolean value
1282 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1284 * <li>true - in other cases</li>
1287 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1288 final ModuleContext context, final boolean inGrouping) {
1289 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1293 final Module parentModule = findParentModule(schemaContext, leaf);
1294 Type returnType = null;
1296 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1297 if (isInnerType(leaf, typeDef)) {
1298 if (typeDef instanceof EnumTypeDefinition) {
1299 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1300 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1301 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1302 typeBuilder, context);
1303 if (enumBuilder != null) {
1304 returnType = enumBuilder.toInstance(typeBuilder);
1306 typeProvider.putReferencedType(leaf.getPath(), returnType);
1307 } else if (typeDef instanceof UnionTypeDefinition) {
1308 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1309 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1310 // Store the inner type within the union so that we can find the reference for it
1311 context.addInnerTypedefType(typeDef.getPath(), returnType);
1312 } else if (typeDef instanceof BitsTypeDefinition) {
1313 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1315 if (genTOBuilder != null) {
1316 returnType = genTOBuilder.build();
1319 // It is constrained version of already declared type (inner declared type exists,
1320 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1321 // In order to get proper class we need to look up closest derived type
1322 // and apply restrictions from leaf type
1323 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1324 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1325 restrictions, inGrouping);
1326 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1329 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1330 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1331 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1334 if (returnType == null) {
1338 if (typeDef instanceof EnumTypeDefinition) {
1339 typeProvider.putReferencedType(leaf.getPath(), returnType);
1342 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1343 processContextRefExtension(leaf, getter, parentModule);
1347 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1348 // Returns DerivedType in case of new parser.
1349 final TypeDefinition<?> baseType = typeDef.getBaseType();
1350 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1353 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1354 final Module module) {
1355 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1356 final QName nodeType = node.getNodeType();
1357 if ("context-reference".equals(nodeType.getLocalName())) {
1358 final String nodeParam = node.getNodeParameter();
1359 IdentitySchemaNode identity = null;
1360 String basePackageName = null;
1361 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1362 final Iterator<String> iterator = splittedElement.iterator();
1363 final int length = Iterables.size(splittedElement);
1365 identity = findIdentityByName(module.getIdentities(), iterator.next());
1366 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1367 } else if (length == 2) {
1368 final String prefix = iterator.next();
1369 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1370 if (dependentModule == null) {
1371 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1374 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1375 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1377 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1380 if (identity == null) {
1381 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1385 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1386 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1387 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1388 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1393 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1394 for (final IdentitySchemaNode id : identities) {
1395 if (id.getQName().getLocalName().equals(name)) {
1402 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1403 for (final ModuleImport imp : imports) {
1404 if (imp.getPrefix().equals(prefix)) {
1405 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1411 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1412 final boolean isReadOnly) {
1413 if (leaf != null && toBuilder != null) {
1415 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1416 if (typeDef instanceof UnionTypeDefinition) {
1417 // GeneratedType for this type definition should have be already created
1418 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1419 returnType = mc.getTypedefs().get(typeDef.getPath());
1420 if (returnType == null) {
1421 // This may still be an inner type, try to find it
1422 returnType = mc.getInnerType(typeDef.getPath());
1424 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1425 // Annonymous enumeration (already generated, since it is inherited via uses).
1426 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1427 QName qname = originalLeaf.getQName();
1428 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1430 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1432 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1438 * Converts <code>leaf</code> schema node to property of generated TO builder.
1440 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1441 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1442 * @param returnType property type
1443 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1444 * @return boolean value
1446 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1447 * name equals null or if leaf is added by <i>uses</i>.</li>
1448 * <li>true - other cases</li>
1451 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1452 final Type returnType, final boolean isReadOnly) {
1453 if (returnType == null) {
1456 final String leafName = leaf.getQName().getLocalName();
1457 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1458 propBuilder.setReadOnly(isReadOnly);
1459 propBuilder.setReturnType(returnType);
1460 addComment(propBuilder, leaf);
1462 toBuilder.addEqualsIdentity(propBuilder);
1463 toBuilder.addHashIdentity(propBuilder);
1464 toBuilder.addToStringProperty(propBuilder);
1469 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1471 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1472 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1473 * @param module module
1474 * @return boolean value
1476 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1477 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1478 * <li>false - other cases</li>
1481 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1482 final ModuleContext context, final boolean inGrouping) {
1483 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1487 final QName nodeName = node.getQName();
1489 final TypeDefinition<?> typeDef = node.getType();
1490 final Module parentModule = findParentModule(schemaContext, node);
1492 Type returnType = null;
1493 if (typeDef.getBaseType() == null) {
1494 if (typeDef instanceof EnumTypeDefinition) {
1495 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1496 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1497 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1498 typeBuilder, context);
1499 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1500 typeProvider.putReferencedType(node.getPath(), returnType);
1501 } else if (typeDef instanceof UnionTypeDefinition) {
1502 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1503 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1504 } else if (typeDef instanceof BitsTypeDefinition) {
1505 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1506 node, parentModule);
1507 returnType = genTOBuilder.build();
1509 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1510 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1511 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1514 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1515 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1516 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1519 constructGetter(typeBuilder, listTypeFor(returnType), node);
1523 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1524 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1525 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1526 returnTypeBuilder.setIsUnion(true);
1527 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1528 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1529 returnTypeBuilder.setModuleName(parentModule.getName());
1530 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1532 genTOBuilder.setTypedef(true);
1533 genTOBuilder.setIsUnion(true);
1534 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1536 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1540 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1541 final GeneratedTransferObject returnType, final Module parentModule) {
1542 // Append enclosing path hierarchy without dots
1543 final StringBuilder sb = new StringBuilder();
1544 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1545 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1546 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1547 unionBuilder.setIsUnionBuilder(true);
1549 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1550 method.setReturnType(returnType);
1551 method.addParameter(Types.STRING, "defaultValue");
1552 method.setAccessModifier(AccessModifier.PUBLIC);
1553 method.setStatic(true);
1555 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1556 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1559 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1560 final SchemaNode schemaNode) {
1561 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1564 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1565 final SchemaNode schemaNode, final Type baseInterface) {
1566 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1567 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1571 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1572 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1573 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1574 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1575 * If <code>schemaNode</code> is instance of
1576 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1577 * which are specified in <i>uses</i>.
1579 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1580 * @param schemaNode schema node for which is created generated type builder
1581 * @param parent parent type (can be null)
1582 * @return generated type builder <code>schemaNode</code>
1584 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1585 final Type baseInterface, final ModuleContext context) {
1586 JavaTypeName name = renames.get(schemaNode);
1588 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1591 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1593 it.addImplementsType(baseInterface);
1594 if (!(schemaNode instanceof GroupingDefinition)) {
1595 it.addImplementsType(augmentable(it));
1597 if (schemaNode instanceof DataNodeContainer) {
1598 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1599 groupingsToGenTypes(context, containerSchema.getGroupings());
1600 addImplementedInterfaceFromUses(containerSchema, it);
1607 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1608 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1609 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1611 * @param packageName string with the package name to which returning generated type builder belongs
1612 * @param schemaNode schema node which provide data about the schema node name
1613 * @param prefix return type name prefix
1614 * @return generated type builder for <code>schemaNode</code>
1615 * @throws IllegalArgumentException
1617 * <li>if <code>schemaNode</code> is null</li>
1618 * <li>if <code>packageName</code> is null</li>
1619 * <li>if QName of schema node is null</li>
1620 * <li>if schemaNode name is null</li>
1623 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1624 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1625 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1626 final String schemaNodeName = schemaNode.getQName().getLocalName();
1627 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1629 // FIXME: Validation of name conflict
1630 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1631 final Module module = findParentModule(schemaContext, schemaNode);
1632 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1633 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1635 addCodegenInformation(newType, module, schemaNode);
1636 newType.setSchemaPath(schemaNode.getPath());
1637 newType.setModuleName(module.getName());
1639 final String packageName = identifier.packageName();
1640 final String simpleName = identifier.simpleName();
1641 if (!genTypeBuilders.containsKey(packageName)) {
1642 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1643 builders.put(simpleName, newType);
1644 genTypeBuilders.put(packageName, builders);
1646 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1647 if (!builders.containsKey(simpleName)) {
1648 builders.put(simpleName, newType);
1655 * Creates the name of the getter method name from <code>localName</code>.
1657 * @param localName string with the name of the getter method
1658 * @param returnType return type
1659 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1661 public static String getterMethodName(final String localName, final Type returnType) {
1662 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1666 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1667 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1668 * and <code>returnType</code> information are added to the builder.
1670 * @param interfaceBuilder generated type builder for which the getter method should be created
1671 * @param returnType type which represents the return type of the getter method
1672 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1673 * @param comment string with comment for the getter method
1674 * @param status status from yang file, for deprecated annotation
1675 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1677 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1678 final SchemaNode node) {
1679 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1680 getterMethodName(node.getQName().getLocalName(), returnType));
1681 getMethod.setReturnType(returnType);
1683 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1684 addComment(getMethod, node);
1689 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1690 final ListSchemaNode node) {
1691 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1692 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1693 getMethod.setReturnType(returnType).setDefault(true);
1694 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1698 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1701 * @param basePackageName string contains the module package name
1702 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1703 * or as a property to <code>genTOBuilder</code> if is part of the list key
1704 * @param typeBuilder generated type builder for the list schema node
1705 * @param genTOBuilder generated TO builder for the list keys
1706 * @param listKeys list of string which contains names of the list keys
1707 * @param module current module
1708 * @throws IllegalArgumentException
1710 * <li>if <code>schemaNode</code> equals null</li>
1711 * <li>if <code>typeBuilder</code> equals null</li>
1714 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1715 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1716 final List<String> listKeys, final boolean inGrouping) {
1717 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1718 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1720 if (schemaNode instanceof LeafSchemaNode) {
1721 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1722 final String leafName = leaf.getQName().getLocalName();
1723 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1724 if (listKeys.contains(leafName)) {
1726 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1728 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1731 } else if (!schemaNode.isAddedByUses()) {
1732 if (schemaNode instanceof LeafListSchemaNode) {
1733 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1734 } else if (schemaNode instanceof ContainerSchemaNode) {
1735 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1736 (ContainerSchemaNode) schemaNode, inGrouping);
1737 } else if (schemaNode instanceof ChoiceSchemaNode) {
1738 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1739 } else if (schemaNode instanceof ListSchemaNode) {
1740 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1745 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1746 final GeneratedTOBuilder genTOBuilder) {
1747 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1749 if (genTOBuilder != null) {
1750 final GeneratedTransferObject genTO = genTOBuilder.build();
1751 // Add Identifiable.getKey() for items
1752 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1753 .addAnnotation(OVERRIDE_ANNOTATION);
1754 context.addGeneratedTOBuilder(genTOBuilder);
1759 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1761 * @param list of string with names of the list keys
1762 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1763 * an empty list is returned.
1765 private static List<String> listKeys(final ListSchemaNode list) {
1766 final List<String> listKeys = new ArrayList<>();
1768 final List<QName> keyDefinition = list.getKeyDefinition();
1769 if (keyDefinition != null) {
1770 for (final QName keyDef : keyDefinition) {
1771 listKeys.add(keyDef.getLocalName());
1778 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1780 * @param packageName string with package name to which the list belongs
1781 * @param list list schema node which is source of data about the list name
1782 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1783 * null or list of key definitions is null or empty.
1785 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1786 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1787 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1788 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1789 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1795 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1796 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1797 * enclosing transfer objects.
1799 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1800 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1801 * @param leaf string with name for generated TO builder
1802 * @param parentModule parent module
1803 * @return generated TO builder for <code>typeDef</code>
1805 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1806 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1807 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1808 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1810 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1811 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1812 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1813 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1814 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1816 for (GeneratedTOBuilder builder : types) {
1817 if (builder.isUnion()) {
1818 final GeneratedTransferObject type = builder.build();
1819 createUnionBuilder(builder, typeBuilder, type, parentModule);
1823 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1827 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1828 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1829 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1832 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1833 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1834 * @param leaf string with name for generated TO builder
1835 * @param parentModule parent module
1836 * @return generated TO builder for <code>typeDef</code>
1838 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1839 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1840 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1841 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1842 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1843 return genTOBuilder;
1847 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1848 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1849 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1850 * to <code>builder</code>
1852 * @param dataNodeContainer element which contains the list of used YANG groupings
1853 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1854 * @return generated type builder with all implemented types
1856 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1857 final GeneratedTypeBuilder builder) {
1858 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1859 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1860 if (genType == null) {
1861 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1862 + builder.getName());
1865 builder.addImplementsType(genType.build());
1870 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1871 for (final ModuleContext ctx : genCtx.values()) {
1872 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1873 if (result != null) {
1880 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1881 for (final ModuleContext ctx : genCtx.values()) {
1882 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1883 if (result != null) {
1890 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1891 for (final ModuleContext ctx : genCtx.values()) {
1892 final GeneratedTypeBuilder result = ctx.getCase(path);
1893 if (result != null) {
1900 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1901 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1902 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1905 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1906 if (status == Status.DEPRECATED) {
1907 builder.addAnnotation(DEPRECATED_ANNOTATION);