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 com.google.common.collect.Sets;
45 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
46 import java.util.AbstractMap.SimpleImmutableEntry;
47 import java.util.ArrayList;
48 import java.util.Collection;
49 import java.util.Comparator;
50 import java.util.HashMap;
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());
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) {
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);
289 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
290 final Type baseInterface, final ContainerSchemaNode node) {
291 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
292 if (genType != null) {
293 constructGetter(parent, genType, node);
294 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
295 actionsToGenType(context, genType, node, null);
299 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
300 final Type baseInterface, final ListSchemaNode node) {
301 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
302 if (genType != null) {
303 constructGetter(parent, listTypeFor(genType), node);
305 final List<String> listKeys = listKeys(node);
306 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
307 if (genTOBuilder != null) {
308 final Type identifierMarker = identifier(genType);
309 final Type identifiableMarker = identifiable(genTOBuilder);
310 genTOBuilder.addImplementsType(identifierMarker);
311 genType.addImplementsType(identifiableMarker);
314 actionsToGenType(context, genType, node, genTOBuilder);
316 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
317 if (!schemaNode.isAugmenting()) {
318 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
323 if (genTOBuilder != null) {
324 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
325 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
326 genTOBuilder.setSUID(prop);
329 typeBuildersToGenTypes(context, genType, genTOBuilder);
333 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
334 for (final UsesNode usesNode : node.getUses()) {
335 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
336 usesAugmentationToGenTypes(context, augment, usesNode, node);
337 processUsesAugments(augment, context);
343 * Converts all <b>augmentation</b> of the module to the list
344 * <code>Type</code> objects.
347 * module from which is obtained list of all augmentation objects
348 * to iterate over them
349 * @throws IllegalArgumentException
351 * <li>if the module is null</li>
352 * <li>if the name of module is null</li>
354 * @throws IllegalStateException
355 * if set of augmentations from module is null
357 private void allAugmentsToGenTypes(final ModuleContext context) {
358 final Module module = context.module();
359 checkArgument(module != null, "Module reference cannot be NULL.");
360 checkArgument(module.getName() != null, "Module name cannot be NULL.");
361 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
363 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
364 augmentationToGenTypes(context, augment);
369 * Returns list of <code>AugmentationSchema</code> objects. The objects are
370 * sorted according to the length of their target path from the shortest to
374 * module from which is obtained list of all augmentation objects
375 * @return list of sorted <code>AugmentationSchema</code> objects obtained
376 * from <code>module</code>
377 * @throws IllegalArgumentException
379 * @throws IllegalStateException
380 * if set of module augmentations is null
382 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
383 checkArgument(module != null, "Module reference cannot be NULL.");
384 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
386 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
387 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
388 sortedAugmentations.sort(AUGMENT_COMP);
390 return sortedAugmentations;
394 * Create GeneratedTypeBuilder object from module argument.
397 * Module object from which builder will be created
398 * @return <code>GeneratedTypeBuilder</code> which is internal
399 * representation of the module
400 * @throws IllegalArgumentException
403 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
404 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
405 final Module module = context.module();
406 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
407 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
409 addCodegenInformation(moduleDataTypeBuilder, module);
410 return moduleDataTypeBuilder;
413 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
414 final Type parent, final T parentSchema, final Type keyType) {
415 for (final ActionDefinition action : parentSchema.getActions()) {
416 final GeneratedType input;
417 final GeneratedType output;
418 if (action.isAddedByUses()) {
419 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
420 input = context.getChildNode(orig.getInput().getPath()).build();
421 output = context.getChildNode(orig.getOutput().getPath()).build();
423 input = actionContainer(context, RPC_INPUT, action.getInput());
424 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
427 if (!(parentSchema instanceof GroupingDefinition)) {
428 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
429 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
430 // and do not capture an actual instantiation.
431 final QName qname = action.getQName();
432 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
433 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
434 BindingMapping.getClassName(qname)));
435 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
436 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
438 annotateDeprecatedIfNecessary(action.getStatus(), builder);
439 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
440 : action(parent, input, output));
442 addCodegenInformation(builder, context.module(), action);
443 context.addChildNodeType(action, builder);
448 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
449 for (UsesNode uses : parent.getUses()) {
450 final GroupingDefinition grp = findUsedGrouping(uses);
451 final Optional<ActionDefinition> found = grp.getActions().stream()
452 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
453 if (found.isPresent()) {
454 final ActionDefinition result = found.get();
455 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
459 return Optional.empty();
462 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
463 final ContainerSchemaNode schema) {
464 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
465 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
466 return genType.build();
470 * Converts all <b>RPCs</b> input and output substatements of the module
471 * to the list of <code>Type</code> objects. In addition are to containers
472 * and lists which belong to input or output also part of returning list.
475 * module from which is obtained set of all rpc objects to
477 * @throws IllegalArgumentException
479 * <li>if the module is null</li>
480 * <li>if the name of module is null</li>
482 * @throws IllegalStateException
483 * if set of rpcs from module is null
485 private void rpcMethodsToGenType(final ModuleContext context) {
486 final Module module = context.module();
487 checkArgument(module.getName() != null, "Module name cannot be NULL.");
488 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
489 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
490 if (rpcDefinitions.isEmpty()) {
494 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
495 interfaceBuilder.addImplementsType(RPC_SERVICE);
497 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
499 for (final RpcDefinition rpc : rpcDefinitions) {
501 final String rpcName = BindingMapping.getClassName(rpc.getQName());
502 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
503 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
505 // Do not refer to annotation class, as it may not be available at runtime
506 method.addAnnotation("javax.annotation", "CheckReturnValue");
507 addComment(method, rpc);
509 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
510 method.setReturnType(listenableFutureTypeFor(
511 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
515 context.addTopLevelNodeType(interfaceBuilder);
518 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
519 final ContainerSchemaNode schema, final Type type) {
520 processUsesAugments(schema, context);
521 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
522 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
524 addImplementedInterfaceFromUses(schema, outType);
525 outType.addImplementsType(type);
526 outType.addImplementsType(augmentable(outType));
527 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
528 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
529 context.addChildNodeType(schema, outType);
530 return outType.build();
534 * Converts all <b>notifications</b> of the module to the list of
535 * <code>Type</code> objects. In addition are to this list added containers
536 * and lists which are part of this notification.
539 * module from which is obtained set of all notification objects
540 * to iterate over them
541 * @throws IllegalArgumentException
543 * <li>if the module equals null</li>
544 * <li>if the name of module equals null</li>
546 * @throws IllegalStateException
547 * if set of notifications from module is null
549 private void notificationsToGenType(final ModuleContext context) {
550 final Module module = context.module();
551 checkArgument(module.getName() != null, "Module name cannot be NULL.");
552 final Set<NotificationDefinition> notifications = module.getNotifications();
553 if (notifications.isEmpty()) {
557 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
558 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
560 for (final NotificationDefinition notification : notifications) {
561 if (notification != null) {
562 processUsesAugments(notification, context);
564 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
565 context.modulePackageName(), notification, DATA_OBJECT, context);
566 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
567 notificationInterface.addImplementsType(NOTIFICATION);
568 context.addChildNodeType(notification, notificationInterface);
570 // Notification object
571 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
572 notification.getChildNodes());
574 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
575 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
576 .setReturnType(Types.primitiveVoidType()), notification);
580 addCodegenInformation(listenerInterface, module, "notifications", notifications);
581 context.addTopLevelNodeType(listenerInterface);
585 * Converts all <b>identities</b> of the module to the list of
586 * <code>Type</code> objects.
589 * module from which is obtained set of all identity objects to
591 * @param schemaContext
592 * schema context only used as input parameter for method
593 * {@link BindingGeneratorImpl#identityToGenType}
596 private void allIdentitiesToGenTypes(final ModuleContext context) {
597 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
599 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
600 for (final IdentitySchemaNode identity : schemaIdentities) {
601 identityToGenType(context, identity);
607 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
608 * created transport object builder. If identity contains base identity then
609 * reference to base identity is added to superior identity as its extend.
610 * If identity doesn't contain base identity then only reference to abstract
611 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
612 * BaseIdentity} is added
616 * @param basePackageName
617 * string contains the module package name
619 * IdentitySchemaNode which contains data about identity
621 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
622 if (identity == null) {
626 JavaTypeName name = renames.get(identity);
628 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
629 BindingMapping.getClassName(identity.getQName()));
632 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
633 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
634 if (!baseIdentities.isEmpty()) {
635 for (IdentitySchemaNode baseIdentity : baseIdentities) {
636 JavaTypeName base = renames.get(baseIdentity);
638 final QName qname = baseIdentity.getQName();
639 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
640 BindingMapping.getClassName(qname));
643 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
644 newType.addImplementsType(gto);
647 newType.addImplementsType(BASE_IDENTITY);
650 final Module module = context.module();
651 addCodegenInformation(newType, module, identity);
652 newType.setModuleName(module.getName());
653 newType.setSchemaPath(identity.getPath());
655 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
656 identity.getQName().getLocalName());
658 context.addIdentityType(identity, newType);
661 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
662 final JavaTypeName yangModuleInfo, final String localName) {
663 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
664 new SimpleImmutableEntry<>(yangModuleInfo, localName));
668 * Converts all <b>groupings</b> of the module to the list of
669 * <code>Type</code> objects. Firstly are groupings sorted according mutual
670 * dependencies. At least dependent (independent) groupings are in the list
671 * saved at first positions. For every grouping the record is added to map
672 * {@link ModuleContext#groupings allGroupings}
677 * collection of groupings from which types will be generated
680 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
681 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
682 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
683 // node of grouping is resolved to the method.
684 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
685 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
686 context.addGroupingType(grouping, genType);
687 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
688 groupingsToGenTypes(context, grouping.getGroupings());
689 processUsesAugments(grouping, context);
690 actionsToGenType(context, genType, grouping, null);
695 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
696 * <code>enumTypeDef</code> item is added to builder with its name and value.
698 * @param enumTypeDef EnumTypeDefinition contains enum data
699 * @param enumName string contains name which will be assigned to enumeration builder
700 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
701 * @param module Module in which type should be generated
702 * @return enumeration builder which contains data from <code>enumTypeDef</code>
704 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
705 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
706 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
707 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
708 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
709 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
710 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
717 * Generates type builder for <code>module</code>.
719 * @param module Module which is source of package name for generated type builder
720 * @param postfix string which is added to the module class name representation as suffix
721 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
722 * @throws IllegalArgumentException if <code>module</code> is null
724 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
725 final Module module = context.module();
726 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
727 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
728 JavaTypeName.create(context.modulePackageName(), moduleName));
730 moduleBuilder.setModuleName(moduleName);
731 addCodegenInformation(moduleBuilder, module);
732 return moduleBuilder;
736 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
737 * In addition there are also generated types for all containers, list and choices which are child of
738 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
740 * @param augmentPackageName string with the name of the package to which the augmentation belongs
741 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
742 * @param module current module
743 * @throws IllegalArgumentException
745 * <li>if <code>augmentPackageName</code> equals null</li>
746 * <li>if <code>augSchema</code> equals null</li>
748 * @throws IllegalStateException
749 * if augment target path is null
751 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
752 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
753 checkState(augSchema.getTargetPath() != null,
754 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
756 processUsesAugments(augSchema, context);
757 final SchemaPath targetPath = augSchema.getTargetPath();
758 SchemaNode targetSchemaNode = null;
760 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
761 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
762 if (targetSchemaNode instanceof DerivableSchemaNode) {
763 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
765 if (targetSchemaNode == null) {
766 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
767 + " in module " + context.module().getName());
770 if (targetSchemaNode == null) {
771 throw new IllegalArgumentException("augment target not found: " + targetPath);
774 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
775 if (targetTypeBuilder == null) {
776 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
778 if (targetTypeBuilder == null) {
779 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
782 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
783 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
784 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
787 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
788 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
792 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
793 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
794 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
795 checkState(augSchema.getTargetPath() != null,
796 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
798 processUsesAugments(augSchema, context);
799 final SchemaPath targetPath = augSchema.getTargetPath();
800 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
801 if (targetSchemaNode == null) {
802 throw new IllegalArgumentException("augment target not found: " + targetPath);
805 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
806 if (targetTypeBuilder == null) {
807 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
809 if (targetTypeBuilder == null) {
810 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
813 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
814 if (usesNodeParent instanceof SchemaNode) {
815 addRawAugmentGenTypeDefinition(context,
816 packageNameForAugmentedGeneratedType(context.modulePackageName(),
817 ((SchemaNode) usesNodeParent).getPath()),
818 targetTypeBuilder.build(), augSchema);
820 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
823 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
824 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
828 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
829 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
831 if (targetGrouping instanceof GroupingDefinition) {
832 return (GroupingDefinition) targetGrouping;
835 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
839 * Convenient method to find node added by uses statement.
841 * @param targetPath node path
842 * @param parentUsesNode parent of uses node
843 * @return node from its original location in grouping
845 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
846 SchemaNode result = findUsedGrouping(parentUsesNode);
847 for (final QName node : targetPath.getPathFromRoot()) {
848 if (result instanceof DataNodeContainer) {
849 final QName resultNode = node.withModule(result.getQName().getModule());
850 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
851 } else if (result instanceof ChoiceSchemaNode) {
852 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
855 if (result == null) {
859 if (result instanceof DerivableSchemaNode) {
860 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
861 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
862 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
863 result = originalNode.get();
867 if (result instanceof DataSchemaNode) {
868 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
869 if (resultDataSchemaNode.isAddedByUses()) {
870 // The original node is required, but we have only the copy of
871 // the original node.
872 // Maybe this indicates a bug in Yang parser.
873 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
876 return resultDataSchemaNode;
879 throw new IllegalStateException(
880 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
885 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
886 * of augmented node with serial number as suffix.
888 * @param context current module
889 * @param augmentPackageName string with contains the package name to which the augment belongs
890 * @param basePackageName string with the package name to which the augmented node belongs
891 * @param targetTypeRef target type
892 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
893 * @return generated type builder for augment
895 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
896 final String augmentPackageName, final Type targetTypeRef,
897 final AugmentationSchemaNode augSchema) {
898 Map<String, GeneratedTypeBuilder> augmentBuilders =
899 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
900 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
903 if (augIdentifier != null) {
904 augTypeName = BindingMapping.getClassName(augIdentifier);
906 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
909 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
910 JavaTypeName.create(augmentPackageName, augTypeName));
912 augTypeBuilder.addImplementsType(DATA_OBJECT);
913 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
914 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
915 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
917 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
918 augmentBuilders.put(augTypeName, augTypeBuilder);
920 if (!augSchema.getChildNodes().isEmpty()) {
921 context.addTypeToAugmentation(augTypeBuilder, augSchema);
924 context.addAugmentType(augTypeBuilder);
925 return augTypeBuilder;
928 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
929 final AugmentationSchemaNode augSchema) {
930 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
933 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
934 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
935 final QName nodeType = unknownSchemaNode.getNodeType();
936 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
937 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
938 return unknownSchemaNode.getNodeParameter();
945 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
946 * consists from name of augmented node and serial number of its augmentation.
948 * @param builders map of builders which were created in the package to which the augmentation belongs
949 * @param genTypeName string with name of augmented node
950 * @return string with unique name for augmentation builder
952 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
954 if (builders != null) {
955 while (builders.containsKey(genTypeName + index)) {
959 return genTypeName + index;
963 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
964 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
965 * already part of them).
967 * @param module current module
968 * @param parent generated type builder which represents any node. The subnodes of this node are added
969 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
971 * @param childOf parent type
972 * @param schemaNodes set of data schema nodes which are the children of the node for which
973 * <code>typeBuilder</code> was created
974 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
975 * child nodes) could be added to it.
977 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
978 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
979 if (schemaNodes != null && parent != null) {
980 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
981 for (final DataSchemaNode schemaNode : schemaNodes) {
982 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
983 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
991 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
994 * @param module current module
995 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
996 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
998 * @param childOf parent type
999 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1001 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1002 * The getter method could be added to it.
1004 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1005 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1006 if (schemaNodes != null && typeBuilder != null) {
1007 final Type baseInterface = childOf(typeBuilder);
1008 for (final DataSchemaNode schemaNode : schemaNodes) {
1009 if (!schemaNode.isAugmenting()) {
1010 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1018 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1020 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1021 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1022 * @param childOf parent type
1023 * @param module current module
1025 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1026 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1027 if (node != null && typeBuilder != null) {
1028 if (node instanceof LeafSchemaNode) {
1029 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1030 } else if (node instanceof LeafListSchemaNode) {
1031 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1032 } else if (node instanceof ContainerSchemaNode) {
1033 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1034 } else if (node instanceof ListSchemaNode) {
1035 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1036 } else if (node instanceof ChoiceSchemaNode) {
1037 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1039 // TODO: anyxml not yet supported
1040 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1041 typeBuilder.getFullyQualifiedName());
1047 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1048 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1049 * and names of all parents node.
1051 * @param context current module
1052 * @param basePackageName string with the module package name
1053 * @param parent parent type
1054 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1056 * @throws IllegalArgumentException
1058 * <li>if <code>basePackageName</code> is null</li>
1059 * <li>if <code>choiceNode</code> is null</li>
1062 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1063 final ChoiceSchemaNode choiceNode) {
1064 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1066 if (!choiceNode.isAddedByUses()) {
1067 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1068 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1069 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1070 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1071 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1072 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1074 final GeneratedType choiceType = choiceTypeBuilder.build();
1075 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1077 constructGetter(parent, choiceType, choiceNode);
1082 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1083 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1084 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1085 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1087 * @param context current module context
1088 * @param refChoiceType type which represents superior <i>case</i>
1089 * @param choiceNode choice case node which is mapped to generated type
1090 * @throws IllegalArgumentException
1092 * <li>if <code>refChoiceType</code> equals null</li>
1093 * <li>if <code>caseNodes</code> equals null</li>
1096 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1097 final ChoiceSchemaNode choiceNode) {
1098 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1099 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1101 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1102 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1103 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1104 caseTypeBuilder.addImplementsType(refChoiceType);
1105 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1106 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1107 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1108 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1109 if (caseChildNodes != null) {
1110 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1112 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1113 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1115 if (parent instanceof AugmentationSchemaNode) {
1116 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1117 final SchemaPath targetPath = augSchema.getTargetPath();
1118 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1119 if (targetSchemaNode instanceof DataSchemaNode
1120 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1121 if (targetSchemaNode instanceof DerivableSchemaNode) {
1122 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1125 if (targetSchemaNode == null) {
1126 throw new IllegalStateException(
1127 "Failed to find target node from grouping for augmentation " + augSchema
1128 + " in module " + context.module().getName());
1131 parent = targetSchemaNode;
1134 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1135 Type childOfType = findChildNodeByPath(parent.getPath());
1136 if (childOfType == null) {
1137 childOfType = findGroupingByPath(parent.getPath());
1139 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1141 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1145 processUsesAugments(caseNode, context);
1150 * Generates list of generated types for all the cases of a choice which are added to the choice through
1153 * @param module current module
1154 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1155 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1156 * of the augmenting choice will belong to pcg2.
1157 * @param targetType Type which represents target choice
1158 * @param targetNode node which represents target choice
1159 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1161 * @throws IllegalArgumentException
1163 * <li>if <code>basePackageName</code> is null</li>
1164 * <li>if <code>targetType</code> is null</li>
1165 * <li>if <code>augmentedNodes</code> is null</li>
1168 // FIXME: nullness rules need to untangled in this method
1169 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1170 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1171 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1172 final DataNodeContainer usesNodeParent) {
1173 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1174 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1176 for (final DataSchemaNode caseNode : augmentedNodes) {
1177 if (caseNode != null) {
1178 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1179 caseTypeBuilder.addImplementsType(targetType);
1181 CaseSchemaNode node = null;
1182 final String caseLocalName = caseNode.getQName().getLocalName();
1183 if (caseNode instanceof CaseSchemaNode) {
1184 node = (CaseSchemaNode) caseNode;
1185 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1186 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1187 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1188 if (dataSchemaNode instanceof ChoiceSchemaNode
1189 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1190 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1195 node = findNamedCase(targetNode, caseLocalName);
1197 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1198 if (childNodes != null) {
1199 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1201 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1202 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1207 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1208 final SchemaPath nodePath = targetNode.getPath();
1209 final SchemaPath parentSp = nodePath.getParent();
1210 if (parentSp.getParent() == null) {
1211 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1214 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1215 GeneratedTypeBuilder childOfType = null;
1216 if (parent instanceof CaseSchemaNode) {
1217 childOfType = findCaseByPath(parent.getPath());
1218 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1219 childOfType = findChildNodeByPath(parent.getPath());
1220 } else if (parent instanceof GroupingDefinition) {
1221 childOfType = findGroupingByPath(parent.getPath());
1224 if (childOfType == null) {
1225 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1231 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1232 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1233 return cases.isEmpty() ? null : cases.get(0);
1236 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1237 // New parser with encapsulated type
1238 if (leaf.getPath().equals(type.getPath())) {
1242 // Embedded type definition with new parser. Also takes care of the old parser with bits
1243 if (leaf.getPath().equals(type.getPath().getParent())) {
1250 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1251 final List<PatternConstraint> patternConstraints) {
1252 if (!patternConstraints.isEmpty()) {
1253 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1254 .append(BindingMapping.getPropertyName(leafName));
1255 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1256 typeProvider.resolveRegExpressions(patternConstraints));
1261 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1263 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1264 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1265 * @param module Module in which type was defined
1266 * @return boolean value
1268 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1270 * <li>true - in other cases</li>
1273 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1274 final ModuleContext context) {
1275 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1279 final Module parentModule = findParentModule(schemaContext, leaf);
1280 Type returnType = null;
1282 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1283 if (isInnerType(leaf, typeDef)) {
1284 if (typeDef instanceof EnumTypeDefinition) {
1285 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1286 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1287 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1288 typeBuilder, context);
1289 if (enumBuilder != null) {
1290 returnType = enumBuilder.toInstance(typeBuilder);
1292 typeProvider.putReferencedType(leaf.getPath(), returnType);
1293 } else if (typeDef instanceof UnionTypeDefinition) {
1294 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1295 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1296 // Store the inner type within the union so that we can find the reference for it
1297 context.addInnerTypedefType(typeDef.getPath(), returnType);
1298 } else if (typeDef instanceof BitsTypeDefinition) {
1299 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1301 if (genTOBuilder != null) {
1302 returnType = genTOBuilder.build();
1305 // It is constrained version of already declared type (inner declared type exists,
1306 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1307 // In order to get proper class we need to look up closest derived type
1308 // and apply restrictions from leaf type
1309 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1310 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1312 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1315 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1316 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1317 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1320 if (returnType == null) {
1324 if (typeDef instanceof EnumTypeDefinition) {
1325 typeProvider.putReferencedType(leaf.getPath(), returnType);
1328 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1329 processContextRefExtension(leaf, getter, parentModule);
1333 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1334 // Returns DerivedType in case of new parser.
1335 final TypeDefinition<?> baseType = typeDef.getBaseType();
1336 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1339 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1340 final Module module) {
1341 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1342 final QName nodeType = node.getNodeType();
1343 if ("context-reference".equals(nodeType.getLocalName())) {
1344 final String nodeParam = node.getNodeParameter();
1345 IdentitySchemaNode identity = null;
1346 String basePackageName = null;
1347 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1348 final Iterator<String> iterator = splittedElement.iterator();
1349 final int length = Iterables.size(splittedElement);
1351 identity = findIdentityByName(module.getIdentities(), iterator.next());
1352 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1353 } else if (length == 2) {
1354 final String prefix = iterator.next();
1355 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1356 if (dependentModule == null) {
1357 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1360 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1361 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1363 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1366 if (identity == null) {
1367 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1371 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1372 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1373 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1374 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1379 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1380 for (final IdentitySchemaNode id : identities) {
1381 if (id.getQName().getLocalName().equals(name)) {
1388 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1389 for (final ModuleImport imp : imports) {
1390 if (imp.getPrefix().equals(prefix)) {
1391 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1397 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1398 final boolean isReadOnly) {
1399 if (leaf != null && toBuilder != null) {
1401 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1402 if (typeDef instanceof UnionTypeDefinition) {
1403 // GeneratedType for this type definition should have be already created
1404 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1405 returnType = mc.getTypedefs().get(typeDef.getPath());
1406 if (returnType == null) {
1407 // This may still be an inner type, try to find it
1408 returnType = mc.getInnerType(typeDef.getPath());
1410 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1411 // Annonymous enumeration (already generated, since it is inherited via uses).
1412 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1413 QName qname = originalLeaf.getQName();
1414 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1416 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1418 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1424 * Converts <code>leaf</code> schema node to property of generated TO builder.
1426 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1427 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1428 * @param returnType property type
1429 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1430 * @return boolean value
1432 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1433 * name equals null or if leaf is added by <i>uses</i>.</li>
1434 * <li>true - other cases</li>
1437 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1438 final Type returnType, final boolean isReadOnly) {
1439 if (returnType == null) {
1442 final String leafName = leaf.getQName().getLocalName();
1443 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1444 propBuilder.setReadOnly(isReadOnly);
1445 propBuilder.setReturnType(returnType);
1446 addComment(propBuilder, leaf);
1448 toBuilder.addEqualsIdentity(propBuilder);
1449 toBuilder.addHashIdentity(propBuilder);
1450 toBuilder.addToStringProperty(propBuilder);
1455 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1457 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1458 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1459 * @param module module
1460 * @return boolean value
1462 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1463 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1464 * <li>false - other cases</li>
1467 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1468 final ModuleContext context) {
1469 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1473 final QName nodeName = node.getQName();
1475 final TypeDefinition<?> typeDef = node.getType();
1476 final Module parentModule = findParentModule(schemaContext, node);
1478 Type returnType = null;
1479 if (typeDef.getBaseType() == null) {
1480 if (typeDef instanceof EnumTypeDefinition) {
1481 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1482 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1483 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1484 typeBuilder, context);
1485 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1486 typeProvider.putReferencedType(node.getPath(), returnType);
1487 } else if (typeDef instanceof UnionTypeDefinition) {
1488 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1489 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1490 } else if (typeDef instanceof BitsTypeDefinition) {
1491 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1492 node, parentModule);
1493 returnType = genTOBuilder.build();
1495 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1496 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1497 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1500 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1501 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1502 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1505 final ParameterizedType listType = listTypeFor(returnType);
1506 constructGetter(typeBuilder, listType, node);
1510 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1511 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1512 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1513 returnTypeBuilder.setIsUnion(true);
1514 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1515 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1516 returnTypeBuilder.setModuleName(parentModule.getName());
1517 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1519 genTOBuilder.setTypedef(true);
1520 genTOBuilder.setIsUnion(true);
1521 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1523 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1527 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1528 final GeneratedTransferObject returnType, final Module parentModule) {
1529 // Append enclosing path hierarchy without dots
1530 final StringBuilder sb = new StringBuilder();
1531 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1532 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1533 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1534 unionBuilder.setIsUnionBuilder(true);
1536 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1537 method.setReturnType(returnType);
1538 method.addParameter(Types.STRING, "defaultValue");
1539 method.setAccessModifier(AccessModifier.PUBLIC);
1540 method.setStatic(true);
1542 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1543 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1544 if (types == null) {
1545 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1547 types.add(unionBuilderType);
1551 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1552 final SchemaNode schemaNode) {
1553 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1556 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1557 final SchemaNode schemaNode, final Type baseInterface) {
1558 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1559 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1563 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1564 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1565 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1566 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1567 * If <code>schemaNode</code> is instance of
1568 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1569 * which are specified in <i>uses</i>.
1571 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1572 * @param schemaNode schema node for which is created generated type builder
1573 * @param parent parent type (can be null)
1574 * @return generated type builder <code>schemaNode</code>
1576 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1577 final Type baseInterface, final ModuleContext context) {
1578 JavaTypeName name = renames.get(schemaNode);
1580 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1583 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1585 it.addImplementsType(baseInterface);
1586 if (!(schemaNode instanceof GroupingDefinition)) {
1587 it.addImplementsType(augmentable(it));
1589 if (schemaNode instanceof DataNodeContainer) {
1590 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1591 groupingsToGenTypes(context, containerSchema.getGroupings());
1592 addImplementedInterfaceFromUses(containerSchema, it);
1599 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1600 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1601 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1603 * @param packageName string with the package name to which returning generated type builder belongs
1604 * @param schemaNode schema node which provide data about the schema node name
1605 * @param prefix return type name prefix
1606 * @return generated type builder for <code>schemaNode</code>
1607 * @throws IllegalArgumentException
1609 * <li>if <code>schemaNode</code> is null</li>
1610 * <li>if <code>packageName</code> is null</li>
1611 * <li>if QName of schema node is null</li>
1612 * <li>if schemaNode name is null</li>
1615 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1616 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1617 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1618 final String schemaNodeName = schemaNode.getQName().getLocalName();
1619 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1621 // FIXME: Validation of name conflict
1622 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1623 final Module module = findParentModule(schemaContext, schemaNode);
1624 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1625 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1627 addCodegenInformation(newType, module, schemaNode);
1628 newType.setSchemaPath(schemaNode.getPath());
1629 newType.setModuleName(module.getName());
1631 final String packageName = identifier.packageName();
1632 final String simpleName = identifier.simpleName();
1633 if (!genTypeBuilders.containsKey(packageName)) {
1634 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1635 builders.put(simpleName, newType);
1636 genTypeBuilders.put(packageName, builders);
1638 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1639 if (!builders.containsKey(simpleName)) {
1640 builders.put(simpleName, newType);
1647 * Creates the name of the getter method name from <code>localName</code>.
1649 * @param localName string with the name of the getter method
1650 * @param returnType return type
1651 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1653 public static String getterMethodName(final String localName, final Type returnType) {
1654 final StringBuilder method = new StringBuilder();
1655 if (BOOLEAN.equals(returnType)) {
1656 method.append("is");
1658 method.append("get");
1660 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1661 method.append(name);
1662 return method.toString();
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 if (!returnType.getPackageName().isEmpty()) {
1685 // The return type has a package, so it's not a primitive type
1686 getMethod.addAnnotation("javax.annotation", "Nullable");
1688 addComment(getMethod, node);
1694 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1697 * @param basePackageName string contains the module package name
1698 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1699 * or as a property to <code>genTOBuilder</code> if is part of the list key
1700 * @param typeBuilder generated type builder for the list schema node
1701 * @param genTOBuilder generated TO builder for the list keys
1702 * @param listKeys list of string which contains names of the list keys
1703 * @param module current module
1704 * @throws IllegalArgumentException
1706 * <li>if <code>schemaNode</code> equals null</li>
1707 * <li>if <code>typeBuilder</code> equals null</li>
1710 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1711 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1712 final List<String> listKeys) {
1713 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1714 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1716 if (schemaNode instanceof LeafSchemaNode) {
1717 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1718 final String leafName = leaf.getQName().getLocalName();
1719 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1720 if (listKeys.contains(leafName)) {
1722 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1724 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1727 } else if (!schemaNode.isAddedByUses()) {
1728 if (schemaNode instanceof LeafListSchemaNode) {
1729 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1730 } else if (schemaNode instanceof ContainerSchemaNode) {
1731 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1732 (ContainerSchemaNode) schemaNode);
1733 } else if (schemaNode instanceof ChoiceSchemaNode) {
1734 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1735 } else if (schemaNode instanceof ListSchemaNode) {
1736 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1741 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1742 final GeneratedTOBuilder genTOBuilder) {
1743 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1745 if (genTOBuilder != null) {
1746 final GeneratedTransferObject genTO = genTOBuilder.build();
1747 // Add Identifiable.getKey() for items
1748 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1749 .addAnnotation(OVERRIDE_ANNOTATION);
1750 context.addGeneratedTOBuilder(genTOBuilder);
1755 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1757 * @param list of string with names of the list keys
1758 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1759 * an empty list is returned.
1761 private static List<String> listKeys(final ListSchemaNode list) {
1762 final List<String> listKeys = new ArrayList<>();
1764 final List<QName> keyDefinition = list.getKeyDefinition();
1765 if (keyDefinition != null) {
1766 for (final QName keyDef : keyDefinition) {
1767 listKeys.add(keyDef.getLocalName());
1774 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1776 * @param packageName string with package name to which the list belongs
1777 * @param list list schema node which is source of data about the list name
1778 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1779 * null or list of key definitions is null or empty.
1781 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1782 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1783 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1784 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1785 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1791 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1792 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1793 * enclosing transfer objects.
1795 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1796 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1797 * @param leaf string with name for generated TO builder
1798 * @param parentModule parent module
1799 * @return generated TO builder for <code>typeDef</code>
1801 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1802 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1803 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1804 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1807 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1808 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1809 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1810 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1811 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1813 for (GeneratedTOBuilder builder : types) {
1814 if (builder.isUnion()) {
1815 final GeneratedTransferObject type = builder.build();
1816 createUnionBuilder(builder, typeBuilder, type, parentModule);
1820 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1824 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1825 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1826 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1829 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1830 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1831 * @param leaf string with name for generated TO builder
1832 * @param parentModule parent module
1833 * @return generated TO builder for <code>typeDef</code>
1835 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1836 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1837 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1838 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1839 typeDef, parentModule.getName());
1840 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1841 return genTOBuilder;
1846 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1847 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1848 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1849 * to <code>builder</code>
1851 * @param dataNodeContainer element which contains the list of used YANG groupings
1852 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1853 * @return generated type builder with all implemented types
1855 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1856 final GeneratedTypeBuilder builder) {
1857 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1858 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1859 if (genType == null) {
1860 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1861 + builder.getName());
1864 builder.addImplementsType(genType);
1869 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1870 for (final ModuleContext ctx : genCtx.values()) {
1871 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1872 if (result != null) {
1879 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1880 for (final ModuleContext ctx : genCtx.values()) {
1881 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1882 if (result != null) {
1889 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1890 for (final ModuleContext ctx : genCtx.values()) {
1891 final GeneratedTypeBuilder result = ctx.getCase(path);
1892 if (result != null) {
1899 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1900 if (status == Status.DEPRECATED) {
1901 builder.addAnnotation(DEPRECATED_ANNOTATION);