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.STRING;
36 import static org.opendaylight.mdsal.binding.model.util.Types.augmentationTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
38 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
39 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
40 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
41 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
42 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
43 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
44 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
45 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
47 import com.google.common.base.Splitter;
48 import com.google.common.collect.Iterables;
49 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
50 import java.util.AbstractMap.SimpleImmutableEntry;
51 import java.util.ArrayList;
52 import java.util.Collection;
53 import java.util.Comparator;
54 import java.util.HashMap;
55 import java.util.HashSet;
56 import java.util.Iterator;
57 import java.util.List;
59 import java.util.Optional;
61 import org.eclipse.jdt.annotation.Nullable;
62 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
63 import org.opendaylight.mdsal.binding.model.api.Constant;
64 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
65 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
66 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
67 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
68 import org.opendaylight.mdsal.binding.model.api.Restrictions;
69 import org.opendaylight.mdsal.binding.model.api.Type;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
79 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
80 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
81 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
82 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
83 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
84 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
85 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
86 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
87 import org.opendaylight.yangtools.yang.common.QName;
88 import org.opendaylight.yangtools.yang.common.QNameModule;
89 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
90 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
99 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
100 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.Module;
105 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
106 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
107 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
111 import org.opendaylight.yangtools.yang.model.api.Status;
112 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
113 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.UsesNode;
115 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
116 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
117 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
118 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
119 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
120 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
121 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
122 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
123 import org.slf4j.Logger;
124 import org.slf4j.LoggerFactory;
126 abstract class AbstractTypeGenerator {
127 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
128 private static final Splitter COLON_SPLITTER = Splitter.on(':');
129 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
130 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
131 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
134 * Comparator based on augment target path.
136 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
137 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
138 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
140 while (thisIt.hasNext()) {
141 if (!otherIt.hasNext()) {
145 final int comp = thisIt.next().compareTo(otherIt.next());
151 return otherIt.hasNext() ? -1 : 0;
155 * Constant with the concrete name of identifier.
157 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
160 * Constant with the concrete name of namespace.
162 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
164 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
167 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
168 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
169 * for schema node specified in key part.
171 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
174 * Provide methods for converting YANG types to JAVA types.
176 private final AbstractTypeProvider typeProvider;
179 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
181 private final SchemaContext schemaContext;
184 * Holds renamed elements.
186 private final Map<SchemaNode, JavaTypeName> renames;
188 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
189 final Map<SchemaNode, JavaTypeName> renames) {
190 this.schemaContext = requireNonNull(context);
191 this.typeProvider = requireNonNull(typeProvider);
192 this.renames = requireNonNull(renames);
194 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
195 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
196 for (final Module contextModule : contextModules) {
197 contexts.add(moduleToGenTypes(contextModule));
200 contexts.forEach(this::allAugmentsToGenTypes);
203 final Collection<ModuleContext> moduleContexts() {
204 return genCtx.values();
207 final ModuleContext moduleContext(final QNameModule module) {
208 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
211 final AbstractTypeProvider typeProvider() {
215 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
217 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
219 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
220 Set<? extends SchemaNode> nodes);
222 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
224 private ModuleContext moduleToGenTypes(final Module module) {
225 final ModuleContext context = new ModuleContext(module);
226 genCtx.put(module.getQNameModule(), context);
227 allTypeDefinitionsToGenTypes(context);
228 groupingsToGenTypes(context, module.getGroupings());
229 rpcMethodsToGenType(context);
230 allIdentitiesToGenTypes(context);
231 notificationsToGenType(context);
233 if (!module.getChildNodes().isEmpty()) {
234 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
235 context.addModuleNode(moduleType);
236 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
242 * Converts all extended type definitions of module to the list of
243 * <code>Type</code> objects.
246 * module from which is obtained set of type definitions
247 * @throws IllegalArgumentException
249 * <li>if module is null</li>
250 * <li>if name of module is null</li>
252 * @throws IllegalStateException
253 * if set of type definitions from module is null
255 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
256 final Module module = context.module();
257 checkArgument(module.getName() != null, "Module name cannot be NULL.");
258 final DataNodeIterator it = new DataNodeIterator(module);
259 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
260 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
262 for (final TypeDefinition<?> typedef : typeDefinitions) {
263 if (typedef != null) {
264 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
266 context.addTypedefType(typedef, type);
267 context.addTypeToSchema(type,typedef);
273 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
274 final DataSchemaNode node) {
275 if (node.isAugmenting() || node.isAddedByUses()) {
278 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
279 defaultImplementedInterace(genType);
280 annotateDeprecatedIfNecessary(node.getStatus(), genType);
282 final Module module = context.module();
283 genType.setModuleName(module.getName());
284 addCodegenInformation(genType, module, node);
285 genType.setSchemaPath(node.getPath());
286 if (node instanceof DataNodeContainer) {
287 context.addChildNodeType(node, genType);
288 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
289 processUsesAugments((DataNodeContainer) node, context);
294 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
295 final Type baseInterface, final ContainerSchemaNode node) {
296 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
297 if (genType != null) {
298 constructGetter(parent, genType, node);
299 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
300 actionsToGenType(context, genType, node, null);
304 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
305 final Type baseInterface, final ListSchemaNode node) {
306 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
307 if (genType != null) {
308 final ParameterizedType listType = listTypeFor(genType);
309 constructGetter(parent, listType, node);
310 constructNonnull(parent, listType, node);
312 final List<String> listKeys = listKeys(node);
313 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
314 if (genTOBuilder != null) {
315 final Type identifierMarker = identifier(genType);
316 final Type identifiableMarker = identifiable(genTOBuilder);
317 genTOBuilder.addImplementsType(identifierMarker);
318 genType.addImplementsType(identifiableMarker);
321 actionsToGenType(context, genType, node, genTOBuilder);
323 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
324 if (!schemaNode.isAugmenting()) {
325 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
330 if (genTOBuilder != null) {
331 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
332 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
333 genTOBuilder.setSUID(prop);
336 typeBuildersToGenTypes(context, genType, genTOBuilder);
340 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
341 for (final UsesNode usesNode : node.getUses()) {
342 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
343 usesAugmentationToGenTypes(context, augment, usesNode, node);
344 processUsesAugments(augment, context);
350 * Converts all <b>augmentation</b> of the module to the list
351 * <code>Type</code> objects.
354 * module from which is obtained list of all augmentation objects
355 * to iterate over them
356 * @throws IllegalArgumentException
358 * <li>if the module is null</li>
359 * <li>if the name of module is null</li>
361 * @throws IllegalStateException
362 * if set of augmentations from module is null
364 private void allAugmentsToGenTypes(final ModuleContext context) {
365 final Module module = context.module();
366 checkArgument(module != null, "Module reference cannot be NULL.");
367 checkArgument(module.getName() != null, "Module name cannot be NULL.");
368 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
370 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
371 augmentationToGenTypes(context, augment);
376 * Returns list of <code>AugmentationSchema</code> objects. The objects are
377 * sorted according to the length of their target path from the shortest to
381 * module from which is obtained list of all augmentation objects
382 * @return list of sorted <code>AugmentationSchema</code> objects obtained
383 * from <code>module</code>
384 * @throws IllegalArgumentException
386 * @throws IllegalStateException
387 * if set of module augmentations is null
389 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
390 checkArgument(module != null, "Module reference cannot be NULL.");
391 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
393 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
394 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
395 sortedAugmentations.sort(AUGMENT_COMP);
397 return sortedAugmentations;
401 * Create GeneratedTypeBuilder object from module argument.
404 * Module object from which builder will be created
405 * @return <code>GeneratedTypeBuilder</code> which is internal
406 * representation of the module
407 * @throws IllegalArgumentException
410 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
411 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
412 final Module module = context.module();
413 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
414 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
416 addCodegenInformation(moduleDataTypeBuilder, module);
417 return moduleDataTypeBuilder;
420 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
421 final Type parent, final T parentSchema, final Type keyType) {
422 for (final ActionDefinition action : parentSchema.getActions()) {
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());
431 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
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) {
471 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
472 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
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);
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 defaultImplementedInterace(outType);
537 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
538 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
539 context.addChildNodeType(schema, outType);
540 return outType.build();
544 * Converts all <b>notifications</b> of the module to the list of
545 * <code>Type</code> objects. In addition are to this list added containers
546 * and lists which are part of this notification.
549 * module from which is obtained set of all notification objects
550 * to iterate over them
551 * @throws IllegalArgumentException
553 * <li>if the module equals null</li>
554 * <li>if the name of module equals null</li>
556 * @throws IllegalStateException
557 * if set of notifications from module is null
559 private void notificationsToGenType(final ModuleContext context) {
560 final Module module = context.module();
561 checkArgument(module.getName() != null, "Module name cannot be NULL.");
562 final Set<NotificationDefinition> notifications = module.getNotifications();
563 if (notifications.isEmpty()) {
567 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
568 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
570 for (final NotificationDefinition notification : notifications) {
571 if (notification != null) {
572 processUsesAugments(notification, context);
574 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
575 context.modulePackageName(), notification, DATA_OBJECT, context);
576 defaultImplementedInterace(notificationInterface);
577 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
578 notificationInterface.addImplementsType(NOTIFICATION);
579 context.addChildNodeType(notification, notificationInterface);
581 // Notification object
582 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
583 notification.getChildNodes());
585 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
586 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
587 .setReturnType(primitiveVoidType()), notification);
591 addCodegenInformation(listenerInterface, module, "notifications", notifications);
592 context.addTopLevelNodeType(listenerInterface);
596 * Converts all <b>identities</b> of the module to the list of
597 * <code>Type</code> objects.
600 * module from which is obtained set of all identity objects to
602 * @param schemaContext
603 * schema context only used as input parameter for method
604 * {@link BindingGeneratorImpl#identityToGenType}
607 private void allIdentitiesToGenTypes(final ModuleContext context) {
608 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
610 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
611 for (final IdentitySchemaNode identity : schemaIdentities) {
612 identityToGenType(context, identity);
618 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
619 * created transport object builder. If identity contains base identity then
620 * reference to base identity is added to superior identity as its extend.
621 * If identity doesn't contain base identity then only reference to abstract
622 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
623 * BaseIdentity} is added
627 * @param basePackageName
628 * string contains the module package name
630 * IdentitySchemaNode which contains data about identity
632 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
633 if (identity == null) {
637 JavaTypeName name = renames.get(identity);
639 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
640 BindingMapping.getClassName(identity.getQName()));
643 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
644 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
645 if (!baseIdentities.isEmpty()) {
646 for (IdentitySchemaNode baseIdentity : baseIdentities) {
647 JavaTypeName base = renames.get(baseIdentity);
649 final QName qname = baseIdentity.getQName();
650 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
651 BindingMapping.getClassName(qname));
654 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
655 newType.addImplementsType(gto);
658 newType.addImplementsType(BASE_IDENTITY);
661 final Module module = context.module();
662 addCodegenInformation(newType, module, identity);
663 newType.setModuleName(module.getName());
664 newType.setSchemaPath(identity.getPath());
666 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
667 identity.getQName().getLocalName());
669 context.addIdentityType(identity, newType);
672 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
673 final JavaTypeName yangModuleInfo, final String localName) {
674 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
675 new SimpleImmutableEntry<>(yangModuleInfo, localName));
679 * Converts all <b>groupings</b> of the module to the list of
680 * <code>Type</code> objects. Firstly are groupings sorted according mutual
681 * dependencies. At least dependent (independent) groupings are in the list
682 * saved at first positions. For every grouping the record is added to map
683 * {@link ModuleContext#groupings allGroupings}
688 * collection of groupings from which types will be generated
691 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
692 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
693 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
694 // node of grouping is resolved to the method.
695 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
696 narrowImplementedInterface(genType);
697 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
698 context.addGroupingType(grouping, genType);
699 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
700 groupingsToGenTypes(context, grouping.getGroupings());
701 processUsesAugments(grouping, context);
702 actionsToGenType(context, genType, grouping, null);
707 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
708 * <code>enumTypeDef</code> item is added to builder with its name and value.
710 * @param enumTypeDef EnumTypeDefinition contains enum data
711 * @param enumName string contains name which will be assigned to enumeration builder
712 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
713 * @param module Module in which type should be generated
714 * @return enumeration builder which contains data from <code>enumTypeDef</code>
716 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
717 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
718 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
719 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
720 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
721 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
722 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
729 * Generates type builder for <code>module</code>.
731 * @param module Module which is source of package name for generated type builder
732 * @param postfix string which is added to the module class name representation as suffix
733 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
734 * @throws IllegalArgumentException if <code>module</code> is null
736 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
737 final Module module = context.module();
738 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
739 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
740 JavaTypeName.create(context.modulePackageName(), moduleName));
742 moduleBuilder.setModuleName(moduleName);
743 addCodegenInformation(moduleBuilder, module);
744 return moduleBuilder;
748 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
749 * In addition there are also generated types for all containers, list and choices which are child of
750 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
752 * @param augmentPackageName string with the name of the package to which the augmentation belongs
753 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
754 * @param module current module
755 * @throws IllegalArgumentException
757 * <li>if <code>augmentPackageName</code> equals null</li>
758 * <li>if <code>augSchema</code> equals null</li>
760 * @throws IllegalStateException
761 * if augment target path is null
763 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
764 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
765 checkState(augSchema.getTargetPath() != null,
766 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
768 processUsesAugments(augSchema, context);
769 final SchemaPath targetPath = augSchema.getTargetPath();
770 SchemaNode targetSchemaNode = null;
772 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
773 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
774 if (targetSchemaNode instanceof DerivableSchemaNode) {
775 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
777 if (targetSchemaNode == null) {
778 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
779 + " in module " + context.module().getName());
782 if (targetSchemaNode == null) {
783 throw new IllegalArgumentException("augment target not found: " + targetPath);
786 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
787 if (targetTypeBuilder == null) {
788 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
790 if (targetTypeBuilder == null) {
791 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
794 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
795 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
796 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
799 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
800 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
804 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
805 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
806 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
807 checkState(augSchema.getTargetPath() != null,
808 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
810 processUsesAugments(augSchema, context);
811 final SchemaPath targetPath = augSchema.getTargetPath();
812 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
813 if (targetSchemaNode == null) {
814 throw new IllegalArgumentException("augment target not found: " + targetPath);
817 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
818 if (targetTypeBuilder == null) {
819 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
821 if (targetTypeBuilder == null) {
822 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
825 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
826 if (usesNodeParent instanceof SchemaNode) {
827 addRawAugmentGenTypeDefinition(context,
828 packageNameForAugmentedGeneratedType(context.modulePackageName(),
829 ((SchemaNode) usesNodeParent).getPath()),
830 targetTypeBuilder.build(), augSchema);
832 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
835 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
836 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
840 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
841 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
843 if (targetGrouping instanceof GroupingDefinition) {
844 return (GroupingDefinition) targetGrouping;
847 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
851 * Convenient method to find node added by uses statement.
853 * @param targetPath node path
854 * @param parentUsesNode parent of uses node
855 * @return node from its original location in grouping
857 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
858 SchemaNode result = findUsedGrouping(parentUsesNode);
859 for (final QName node : targetPath.getPathFromRoot()) {
860 if (result instanceof DataNodeContainer) {
861 final QName resultNode = node.withModule(result.getQName().getModule());
862 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
863 } else if (result instanceof ChoiceSchemaNode) {
864 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
867 if (result == null) {
871 if (result instanceof DerivableSchemaNode) {
872 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
873 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
874 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
875 result = originalNode.get();
879 if (result instanceof DataSchemaNode) {
880 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
881 if (resultDataSchemaNode.isAddedByUses()) {
882 // The original node is required, but we have only the copy of
883 // the original node.
884 // Maybe this indicates a bug in Yang parser.
885 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
888 return resultDataSchemaNode;
891 throw new IllegalStateException(
892 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
897 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
898 * of augmented node with serial number as suffix.
900 * @param context current module
901 * @param augmentPackageName string with contains the package name to which the augment belongs
902 * @param basePackageName string with the package name to which the augmented node belongs
903 * @param targetTypeRef target type
904 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
905 * @return generated type builder for augment
907 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
908 final String augmentPackageName, final Type targetTypeRef,
909 final AugmentationSchemaNode augSchema) {
910 Map<String, GeneratedTypeBuilder> augmentBuilders =
911 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
912 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
915 if (augIdentifier != null) {
916 augTypeName = BindingMapping.getClassName(augIdentifier);
918 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
921 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
922 JavaTypeName.create(augmentPackageName, augTypeName));
924 augTypeBuilder.addImplementsType(DATA_OBJECT);
925 defaultImplementedInterace(augTypeBuilder);
927 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
928 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
929 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
931 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
932 augmentBuilders.put(augTypeName, augTypeBuilder);
934 if (!augSchema.getChildNodes().isEmpty()) {
935 context.addTypeToAugmentation(augTypeBuilder, augSchema);
938 context.addAugmentType(augTypeBuilder);
939 return augTypeBuilder;
942 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
943 final AugmentationSchemaNode augSchema) {
944 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
947 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
948 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
949 final QName nodeType = unknownSchemaNode.getNodeType();
950 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
951 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
952 return unknownSchemaNode.getNodeParameter();
959 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
960 * consists from name of augmented node and serial number of its augmentation.
962 * @param builders map of builders which were created in the package to which the augmentation belongs
963 * @param genTypeName string with name of augmented node
964 * @return string with unique name for augmentation builder
966 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
968 if (builders != null) {
969 while (builders.containsKey(genTypeName + index)) {
973 return genTypeName + index;
977 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
978 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
979 * already part of them).
981 * @param module current module
982 * @param parent generated type builder which represents any node. The subnodes of this node are added
983 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
985 * @param childOf parent type
986 * @param schemaNodes set of data schema nodes which are the children of the node for which
987 * <code>typeBuilder</code> was created
988 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
989 * child nodes) could be added to it.
991 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
992 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
993 if (schemaNodes != null && parent != null) {
994 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
995 for (final DataSchemaNode schemaNode : schemaNodes) {
996 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
997 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1005 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1008 * @param module current module
1009 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1010 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1011 * container, choice.
1012 * @param childOf parent type
1013 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1015 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1016 * The getter method could be added to it.
1018 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1019 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1020 if (schemaNodes != null && typeBuilder != null) {
1021 final Type baseInterface = childOf(typeBuilder);
1022 for (final DataSchemaNode schemaNode : schemaNodes) {
1023 if (!schemaNode.isAugmenting()) {
1024 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1032 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1034 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1035 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1036 * @param childOf parent type
1037 * @param module current module
1039 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1040 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1041 if (node != null && typeBuilder != null) {
1042 if (node instanceof LeafSchemaNode) {
1043 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1044 } else if (node instanceof LeafListSchemaNode) {
1045 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1046 } else if (node instanceof ContainerSchemaNode) {
1047 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1048 } else if (node instanceof ListSchemaNode) {
1049 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1050 } else if (node instanceof ChoiceSchemaNode) {
1051 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1053 // TODO: anyxml not yet supported
1054 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1055 typeBuilder.getFullyQualifiedName());
1061 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1062 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1063 * and names of all parents node.
1065 * @param context current module
1066 * @param basePackageName string with the module package name
1067 * @param parent parent type
1068 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1070 * @throws IllegalArgumentException
1072 * <li>if <code>basePackageName</code> is null</li>
1073 * <li>if <code>choiceNode</code> is null</li>
1076 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1077 final ChoiceSchemaNode choiceNode) {
1078 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1080 if (!choiceNode.isAddedByUses()) {
1081 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1082 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1083 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1084 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1085 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1086 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1088 final GeneratedType choiceType = choiceTypeBuilder.build();
1089 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1091 constructGetter(parent, choiceType, choiceNode);
1096 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1097 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1098 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1099 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1101 * @param context current module context
1102 * @param refChoiceType type which represents superior <i>case</i>
1103 * @param choiceNode choice case node which is mapped to generated type
1104 * @throws IllegalArgumentException
1106 * <li>if <code>refChoiceType</code> equals null</li>
1107 * <li>if <code>caseNodes</code> equals null</li>
1110 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1111 final ChoiceSchemaNode choiceNode) {
1112 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1113 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1115 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1116 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1117 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1118 caseTypeBuilder.addImplementsType(refChoiceType);
1119 defaultImplementedInterace(caseTypeBuilder);
1120 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1121 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1122 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1123 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1124 if (caseChildNodes != null) {
1125 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1127 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1128 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1130 if (parent instanceof AugmentationSchemaNode) {
1131 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1132 final SchemaPath targetPath = augSchema.getTargetPath();
1133 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1134 if (targetSchemaNode instanceof DataSchemaNode
1135 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1136 if (targetSchemaNode instanceof DerivableSchemaNode) {
1137 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1140 if (targetSchemaNode == null) {
1141 throw new IllegalStateException(
1142 "Failed to find target node from grouping for augmentation " + augSchema
1143 + " in module " + context.module().getName());
1146 parent = targetSchemaNode;
1149 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1150 Type childOfType = findChildNodeByPath(parent.getPath());
1151 if (childOfType == null) {
1152 childOfType = findGroupingByPath(parent.getPath());
1154 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1156 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1160 processUsesAugments(caseNode, context);
1165 * Generates list of generated types for all the cases of a choice which are added to the choice through
1168 * @param module current module
1169 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1170 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1171 * of the augmenting choice will belong to pcg2.
1172 * @param targetType Type which represents target choice
1173 * @param targetNode node which represents target choice
1174 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1176 * @throws IllegalArgumentException
1178 * <li>if <code>basePackageName</code> is null</li>
1179 * <li>if <code>targetType</code> is null</li>
1180 * <li>if <code>augmentedNodes</code> is null</li>
1183 // FIXME: nullness rules need to untangled in this method
1184 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1185 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1186 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1187 final DataNodeContainer usesNodeParent) {
1188 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1189 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1191 for (final DataSchemaNode caseNode : augmentedNodes) {
1192 if (caseNode != null) {
1193 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1194 caseTypeBuilder.addImplementsType(targetType);
1195 defaultImplementedInterace(caseTypeBuilder);
1197 CaseSchemaNode node = null;
1198 final String caseLocalName = caseNode.getQName().getLocalName();
1199 if (caseNode instanceof CaseSchemaNode) {
1200 node = (CaseSchemaNode) caseNode;
1201 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1202 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1203 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1204 if (dataSchemaNode instanceof ChoiceSchemaNode
1205 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1206 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1211 node = findNamedCase(targetNode, caseLocalName);
1213 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1214 if (childNodes != null) {
1215 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1217 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1218 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1223 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1224 final SchemaPath nodePath = targetNode.getPath();
1225 final SchemaPath parentSp = nodePath.getParent();
1226 if (parentSp.getParent() == null) {
1227 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1230 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1231 GeneratedTypeBuilder childOfType = null;
1232 if (parent instanceof CaseSchemaNode) {
1233 childOfType = findCaseByPath(parent.getPath());
1234 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1235 childOfType = findChildNodeByPath(parent.getPath());
1236 } else if (parent instanceof GroupingDefinition) {
1237 childOfType = findGroupingByPath(parent.getPath());
1240 if (childOfType == null) {
1241 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1247 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1248 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1249 return cases.isEmpty() ? null : cases.get(0);
1252 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1253 // New parser with encapsulated type
1254 if (leaf.getPath().equals(type.getPath())) {
1258 // Embedded type definition with new parser. Also takes care of the old parser with bits
1259 if (leaf.getPath().equals(type.getPath().getParent())) {
1266 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1267 final List<PatternConstraint> patternConstraints) {
1268 if (!patternConstraints.isEmpty()) {
1269 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1270 .append(BindingMapping.getPropertyName(leafName));
1271 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1272 typeProvider.resolveRegExpressions(patternConstraints));
1277 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1279 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1280 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1281 * @param module Module in which type was defined
1282 * @return boolean value
1284 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1286 * <li>true - in other cases</li>
1289 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1290 final ModuleContext context) {
1291 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1295 final Module parentModule = findParentModule(schemaContext, leaf);
1296 Type returnType = null;
1298 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1299 if (isInnerType(leaf, typeDef)) {
1300 if (typeDef instanceof EnumTypeDefinition) {
1301 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1302 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1303 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1304 typeBuilder, context);
1305 if (enumBuilder != null) {
1306 returnType = enumBuilder.toInstance(typeBuilder);
1308 typeProvider.putReferencedType(leaf.getPath(), returnType);
1309 } else if (typeDef instanceof UnionTypeDefinition) {
1310 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1311 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1312 // Store the inner type within the union so that we can find the reference for it
1313 context.addInnerTypedefType(typeDef.getPath(), returnType);
1314 } else if (typeDef instanceof BitsTypeDefinition) {
1315 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1317 if (genTOBuilder != null) {
1318 returnType = genTOBuilder.build();
1321 // It is constrained version of already declared type (inner declared type exists,
1322 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1323 // In order to get proper class we need to look up closest derived type
1324 // and apply restrictions from leaf type
1325 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1326 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1328 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1331 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1332 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1333 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1336 if (returnType == null) {
1340 if (typeDef instanceof EnumTypeDefinition) {
1341 typeProvider.putReferencedType(leaf.getPath(), returnType);
1344 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1345 processContextRefExtension(leaf, getter, parentModule);
1349 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1350 // Returns DerivedType in case of new parser.
1351 final TypeDefinition<?> baseType = typeDef.getBaseType();
1352 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1355 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1356 final Module module) {
1357 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1358 final QName nodeType = node.getNodeType();
1359 if ("context-reference".equals(nodeType.getLocalName())) {
1360 final String nodeParam = node.getNodeParameter();
1361 IdentitySchemaNode identity = null;
1362 String basePackageName = null;
1363 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1364 final Iterator<String> iterator = splittedElement.iterator();
1365 final int length = Iterables.size(splittedElement);
1367 identity = findIdentityByName(module.getIdentities(), iterator.next());
1368 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1369 } else if (length == 2) {
1370 final String prefix = iterator.next();
1371 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1372 if (dependentModule == null) {
1373 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1376 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1377 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1379 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1382 if (identity == null) {
1383 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1387 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1388 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1389 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1390 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1395 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1396 for (final IdentitySchemaNode id : identities) {
1397 if (id.getQName().getLocalName().equals(name)) {
1404 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1405 for (final ModuleImport imp : imports) {
1406 if (imp.getPrefix().equals(prefix)) {
1407 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1413 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1414 final boolean isReadOnly) {
1415 if (leaf != null && toBuilder != null) {
1417 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1418 if (typeDef instanceof UnionTypeDefinition) {
1419 // GeneratedType for this type definition should have be already created
1420 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1421 returnType = mc.getTypedefs().get(typeDef.getPath());
1422 if (returnType == null) {
1423 // This may still be an inner type, try to find it
1424 returnType = mc.getInnerType(typeDef.getPath());
1426 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1427 // Annonymous enumeration (already generated, since it is inherited via uses).
1428 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1429 QName qname = originalLeaf.getQName();
1430 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1432 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1434 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1440 * Converts <code>leaf</code> schema node to property of generated TO builder.
1442 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1443 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1444 * @param returnType property type
1445 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1446 * @return boolean value
1448 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1449 * name equals null or if leaf is added by <i>uses</i>.</li>
1450 * <li>true - other cases</li>
1453 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1454 final Type returnType, final boolean isReadOnly) {
1455 if (returnType == null) {
1458 final String leafName = leaf.getQName().getLocalName();
1459 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1460 propBuilder.setReadOnly(isReadOnly);
1461 propBuilder.setReturnType(returnType);
1462 addComment(propBuilder, leaf);
1464 toBuilder.addEqualsIdentity(propBuilder);
1465 toBuilder.addHashIdentity(propBuilder);
1466 toBuilder.addToStringProperty(propBuilder);
1471 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1473 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1474 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1475 * @param module module
1476 * @return boolean value
1478 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1479 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1480 * <li>false - other cases</li>
1483 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1484 final ModuleContext context) {
1485 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1489 final QName nodeName = node.getQName();
1491 final TypeDefinition<?> typeDef = node.getType();
1492 final Module parentModule = findParentModule(schemaContext, node);
1494 Type returnType = null;
1495 if (typeDef.getBaseType() == null) {
1496 if (typeDef instanceof EnumTypeDefinition) {
1497 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1498 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1499 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1500 typeBuilder, context);
1501 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1502 typeProvider.putReferencedType(node.getPath(), returnType);
1503 } else if (typeDef instanceof UnionTypeDefinition) {
1504 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1505 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1506 } else if (typeDef instanceof BitsTypeDefinition) {
1507 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1508 node, parentModule);
1509 returnType = genTOBuilder.build();
1511 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1512 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1513 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1516 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1517 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1518 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1521 constructGetter(typeBuilder, listTypeFor(returnType), node);
1525 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1526 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1527 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1528 returnTypeBuilder.setIsUnion(true);
1529 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1530 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1531 returnTypeBuilder.setModuleName(parentModule.getName());
1532 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1534 genTOBuilder.setTypedef(true);
1535 genTOBuilder.setIsUnion(true);
1536 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1538 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1542 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1543 final GeneratedTransferObject returnType, final Module parentModule) {
1544 // Append enclosing path hierarchy without dots
1545 final StringBuilder sb = new StringBuilder();
1546 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1547 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1548 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1549 unionBuilder.setIsUnionBuilder(true);
1551 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1552 method.setReturnType(returnType);
1553 method.addParameter(STRING, "defaultValue");
1554 method.setAccessModifier(AccessModifier.PUBLIC);
1555 method.setStatic(true);
1557 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1558 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1561 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1562 final SchemaNode schemaNode) {
1563 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1566 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1567 final SchemaNode schemaNode, final Type baseInterface) {
1568 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1569 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1573 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1574 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1575 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1576 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1577 * If <code>schemaNode</code> is instance of
1578 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1579 * which are specified in <i>uses</i>.
1581 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1582 * @param schemaNode schema node for which is created generated type builder
1583 * @param parent parent type (can be null)
1584 * @return generated type builder <code>schemaNode</code>
1586 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1587 final Type baseInterface, final ModuleContext context) {
1588 JavaTypeName name = renames.get(schemaNode);
1590 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1593 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1594 it.addImplementsType(baseInterface);
1595 if (!(schemaNode instanceof GroupingDefinition)) {
1596 it.addImplementsType(augmentable(it));
1598 if (schemaNode instanceof DataNodeContainer) {
1599 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1600 groupingsToGenTypes(context, containerSchema.getGroupings());
1601 addImplementedInterfaceFromUses(containerSchema, it);
1608 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1609 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1610 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1612 * @param packageName string with the package name to which returning generated type builder belongs
1613 * @param schemaNode schema node which provide data about the schema node name
1614 * @param prefix return type name prefix
1615 * @return generated type builder for <code>schemaNode</code>
1616 * @throws IllegalArgumentException
1618 * <li>if <code>schemaNode</code> is null</li>
1619 * <li>if <code>packageName</code> is null</li>
1620 * <li>if QName of schema node is null</li>
1621 * <li>if schemaNode name is null</li>
1624 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1625 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1626 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1627 final String schemaNodeName = schemaNode.getQName().getLocalName();
1628 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1630 // FIXME: Validation of name conflict
1631 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1632 final Module module = findParentModule(schemaContext, schemaNode);
1633 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1634 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1636 addCodegenInformation(newType, module, schemaNode);
1637 newType.setSchemaPath(schemaNode.getPath());
1638 newType.setModuleName(module.getName());
1640 final String packageName = identifier.packageName();
1641 final String simpleName = identifier.simpleName();
1642 if (!genTypeBuilders.containsKey(packageName)) {
1643 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1644 builders.put(simpleName, newType);
1645 genTypeBuilders.put(packageName, builders);
1647 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1648 if (!builders.containsKey(simpleName)) {
1649 builders.put(simpleName, newType);
1656 * Creates the name of the getter method name from <code>localName</code>.
1658 * @param localName string with the name of the getter method
1659 * @param returnType return type
1660 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1662 public static String getterMethodName(final String localName, final Type returnType) {
1663 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1667 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1668 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1669 * and <code>returnType</code> information are added to the builder.
1671 * @param interfaceBuilder generated type builder for which the getter method should be created
1672 * @param returnType type which represents the return type of the getter method
1673 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1674 * @param comment string with comment for the getter method
1675 * @param status status from yang file, for deprecated annotation
1676 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1678 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1679 final SchemaNode node) {
1680 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1681 getterMethodName(node.getQName().getLocalName(), returnType));
1682 getMethod.setReturnType(returnType);
1684 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1685 addComment(getMethod, node);
1690 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1691 final ListSchemaNode node) {
1692 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1693 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1694 getMethod.setReturnType(returnType).setDefault(true);
1695 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1699 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1702 * @param basePackageName string contains the module package name
1703 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1704 * or as a property to <code>genTOBuilder</code> if is part of the list key
1705 * @param typeBuilder generated type builder for the list schema node
1706 * @param genTOBuilder generated TO builder for the list keys
1707 * @param listKeys list of string which contains names of the list keys
1708 * @param module current module
1709 * @throws IllegalArgumentException
1711 * <li>if <code>schemaNode</code> equals null</li>
1712 * <li>if <code>typeBuilder</code> equals null</li>
1715 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1716 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1717 final List<String> listKeys) {
1718 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1719 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1721 if (schemaNode instanceof LeafSchemaNode) {
1722 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1723 final String leafName = leaf.getQName().getLocalName();
1724 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1725 if (listKeys.contains(leafName)) {
1727 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1729 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1732 } else if (!schemaNode.isAddedByUses()) {
1733 if (schemaNode instanceof LeafListSchemaNode) {
1734 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1735 } else if (schemaNode instanceof ContainerSchemaNode) {
1736 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1737 (ContainerSchemaNode) schemaNode);
1738 } else if (schemaNode instanceof ChoiceSchemaNode) {
1739 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1740 } else if (schemaNode instanceof ListSchemaNode) {
1741 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1746 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1747 final GeneratedTOBuilder genTOBuilder) {
1748 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1750 if (genTOBuilder != null) {
1751 final GeneratedTransferObject genTO = genTOBuilder.build();
1752 // Add Identifiable.getKey() for items
1753 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1754 .addAnnotation(OVERRIDE_ANNOTATION);
1755 context.addGeneratedTOBuilder(genTOBuilder);
1760 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1762 * @param list of string with names of the list keys
1763 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1764 * an empty list is returned.
1766 private static List<String> listKeys(final ListSchemaNode list) {
1767 final List<String> listKeys = new ArrayList<>();
1769 final List<QName> keyDefinition = list.getKeyDefinition();
1770 if (keyDefinition != null) {
1771 for (final QName keyDef : keyDefinition) {
1772 listKeys.add(keyDef.getLocalName());
1779 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1781 * @param packageName string with package name to which the list belongs
1782 * @param list list schema node which is source of data about the list name
1783 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1784 * null or list of key definitions is null or empty.
1786 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1787 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1788 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1789 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1790 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1796 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1797 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1798 * enclosing transfer objects.
1800 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1801 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1802 * @param leaf string with name for generated TO builder
1803 * @param parentModule parent module
1804 * @return generated TO builder for <code>typeDef</code>
1806 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1807 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1808 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1809 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1812 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1813 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1814 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1815 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1816 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1818 for (GeneratedTOBuilder builder : types) {
1819 if (builder.isUnion()) {
1820 final GeneratedTransferObject type = builder.build();
1821 createUnionBuilder(builder, typeBuilder, type, parentModule);
1825 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1829 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1830 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1831 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1834 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1835 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1836 * @param leaf string with name for generated TO builder
1837 * @param parentModule parent module
1838 * @return generated TO builder for <code>typeDef</code>
1840 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1841 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1842 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1843 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1844 typeDef, parentModule.getName());
1845 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1846 return genTOBuilder;
1851 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1852 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1853 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1854 * to <code>builder</code>
1856 * @param dataNodeContainer element which contains the list of used YANG groupings
1857 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1858 * @return generated type builder with all implemented types
1860 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1861 final GeneratedTypeBuilder builder) {
1862 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1863 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1864 if (genType == null) {
1865 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1866 + builder.getName());
1869 builder.addImplementsType(genType);
1874 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1875 for (final ModuleContext ctx : genCtx.values()) {
1876 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1877 if (result != null) {
1884 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1885 for (final ModuleContext ctx : genCtx.values()) {
1886 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1887 if (result != null) {
1894 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1895 for (final ModuleContext ctx : genCtx.values()) {
1896 final GeneratedTypeBuilder result = ctx.getCase(path);
1897 if (result != null) {
1904 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1905 if (status == Status.DEPRECATED) {
1906 builder.addAnnotation(DEPRECATED_ANNOTATION);
1910 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1911 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1914 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1915 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1919 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1920 final Type classType) {
1921 final MethodSignatureBuilder ret = typeBuilder
1922 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1923 .setAccessModifier(AccessModifier.PUBLIC)
1924 .setReturnType(classType(classType));
1925 ret.addAnnotation(OVERRIDE_ANNOTATION);