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 // FIXME: migrate this to some other annotation type
507 method.addAnnotation("javax.annotation", "CheckReturnValue");
508 addComment(method, rpc);
510 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
511 method.setReturnType(listenableFutureTypeFor(
512 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
516 context.addTopLevelNodeType(interfaceBuilder);
519 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
520 final ContainerSchemaNode schema, final Type type) {
521 processUsesAugments(schema, context);
522 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
523 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
525 addImplementedInterfaceFromUses(schema, outType);
526 outType.addImplementsType(type);
527 outType.addImplementsType(augmentable(outType));
528 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
529 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
530 context.addChildNodeType(schema, outType);
531 return outType.build();
535 * Converts all <b>notifications</b> of the module to the list of
536 * <code>Type</code> objects. In addition are to this list added containers
537 * and lists which are part of this notification.
540 * module from which is obtained set of all notification objects
541 * to iterate over them
542 * @throws IllegalArgumentException
544 * <li>if the module equals null</li>
545 * <li>if the name of module equals null</li>
547 * @throws IllegalStateException
548 * if set of notifications from module is null
550 private void notificationsToGenType(final ModuleContext context) {
551 final Module module = context.module();
552 checkArgument(module.getName() != null, "Module name cannot be NULL.");
553 final Set<NotificationDefinition> notifications = module.getNotifications();
554 if (notifications.isEmpty()) {
558 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
559 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
561 for (final NotificationDefinition notification : notifications) {
562 if (notification != null) {
563 processUsesAugments(notification, context);
565 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
566 context.modulePackageName(), notification, DATA_OBJECT, context);
567 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
568 notificationInterface.addImplementsType(NOTIFICATION);
569 context.addChildNodeType(notification, notificationInterface);
571 // Notification object
572 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
573 notification.getChildNodes());
575 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
576 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
577 .setReturnType(Types.primitiveVoidType()), notification);
581 addCodegenInformation(listenerInterface, module, "notifications", notifications);
582 context.addTopLevelNodeType(listenerInterface);
586 * Converts all <b>identities</b> of the module to the list of
587 * <code>Type</code> objects.
590 * module from which is obtained set of all identity objects to
592 * @param schemaContext
593 * schema context only used as input parameter for method
594 * {@link BindingGeneratorImpl#identityToGenType}
597 private void allIdentitiesToGenTypes(final ModuleContext context) {
598 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
600 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
601 for (final IdentitySchemaNode identity : schemaIdentities) {
602 identityToGenType(context, identity);
608 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
609 * created transport object builder. If identity contains base identity then
610 * reference to base identity is added to superior identity as its extend.
611 * If identity doesn't contain base identity then only reference to abstract
612 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
613 * BaseIdentity} is added
617 * @param basePackageName
618 * string contains the module package name
620 * IdentitySchemaNode which contains data about identity
622 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
623 if (identity == null) {
627 JavaTypeName name = renames.get(identity);
629 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
630 BindingMapping.getClassName(identity.getQName()));
633 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
634 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
635 if (!baseIdentities.isEmpty()) {
636 for (IdentitySchemaNode baseIdentity : baseIdentities) {
637 JavaTypeName base = renames.get(baseIdentity);
639 final QName qname = baseIdentity.getQName();
640 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
641 BindingMapping.getClassName(qname));
644 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
645 newType.addImplementsType(gto);
648 newType.addImplementsType(BASE_IDENTITY);
651 final Module module = context.module();
652 addCodegenInformation(newType, module, identity);
653 newType.setModuleName(module.getName());
654 newType.setSchemaPath(identity.getPath());
656 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
657 identity.getQName().getLocalName());
659 context.addIdentityType(identity, newType);
662 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
663 final JavaTypeName yangModuleInfo, final String localName) {
664 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
665 new SimpleImmutableEntry<>(yangModuleInfo, localName));
669 * Converts all <b>groupings</b> of the module to the list of
670 * <code>Type</code> objects. Firstly are groupings sorted according mutual
671 * dependencies. At least dependent (independent) groupings are in the list
672 * saved at first positions. For every grouping the record is added to map
673 * {@link ModuleContext#groupings allGroupings}
678 * collection of groupings from which types will be generated
681 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
682 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
683 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
684 // node of grouping is resolved to the method.
685 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
686 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
687 context.addGroupingType(grouping, genType);
688 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
689 groupingsToGenTypes(context, grouping.getGroupings());
690 processUsesAugments(grouping, context);
691 actionsToGenType(context, genType, grouping, null);
696 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
697 * <code>enumTypeDef</code> item is added to builder with its name and value.
699 * @param enumTypeDef EnumTypeDefinition contains enum data
700 * @param enumName string contains name which will be assigned to enumeration builder
701 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
702 * @param module Module in which type should be generated
703 * @return enumeration builder which contains data from <code>enumTypeDef</code>
705 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
706 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
707 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
708 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
709 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
710 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
711 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
718 * Generates type builder for <code>module</code>.
720 * @param module Module which is source of package name for generated type builder
721 * @param postfix string which is added to the module class name representation as suffix
722 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
723 * @throws IllegalArgumentException if <code>module</code> is null
725 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
726 final Module module = context.module();
727 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
728 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
729 JavaTypeName.create(context.modulePackageName(), moduleName));
731 moduleBuilder.setModuleName(moduleName);
732 addCodegenInformation(moduleBuilder, module);
733 return moduleBuilder;
737 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
738 * In addition there are also generated types for all containers, list and choices which are child of
739 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
741 * @param augmentPackageName string with the name of the package to which the augmentation belongs
742 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
743 * @param module current module
744 * @throws IllegalArgumentException
746 * <li>if <code>augmentPackageName</code> equals null</li>
747 * <li>if <code>augSchema</code> equals null</li>
749 * @throws IllegalStateException
750 * if augment target path is null
752 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
753 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
754 checkState(augSchema.getTargetPath() != null,
755 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
757 processUsesAugments(augSchema, context);
758 final SchemaPath targetPath = augSchema.getTargetPath();
759 SchemaNode targetSchemaNode = null;
761 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
762 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
763 if (targetSchemaNode instanceof DerivableSchemaNode) {
764 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
766 if (targetSchemaNode == null) {
767 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
768 + " in module " + context.module().getName());
771 if (targetSchemaNode == null) {
772 throw new IllegalArgumentException("augment target not found: " + targetPath);
775 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
776 if (targetTypeBuilder == null) {
777 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
779 if (targetTypeBuilder == null) {
780 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
783 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
784 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
785 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
788 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
789 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
793 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
794 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
795 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
796 checkState(augSchema.getTargetPath() != null,
797 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
799 processUsesAugments(augSchema, context);
800 final SchemaPath targetPath = augSchema.getTargetPath();
801 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
802 if (targetSchemaNode == null) {
803 throw new IllegalArgumentException("augment target not found: " + targetPath);
806 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
807 if (targetTypeBuilder == null) {
808 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
810 if (targetTypeBuilder == null) {
811 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
814 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
815 if (usesNodeParent instanceof SchemaNode) {
816 addRawAugmentGenTypeDefinition(context,
817 packageNameForAugmentedGeneratedType(context.modulePackageName(),
818 ((SchemaNode) usesNodeParent).getPath()),
819 targetTypeBuilder.build(), augSchema);
821 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
824 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
825 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
829 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
830 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
832 if (targetGrouping instanceof GroupingDefinition) {
833 return (GroupingDefinition) targetGrouping;
836 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
840 * Convenient method to find node added by uses statement.
842 * @param targetPath node path
843 * @param parentUsesNode parent of uses node
844 * @return node from its original location in grouping
846 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
847 SchemaNode result = findUsedGrouping(parentUsesNode);
848 for (final QName node : targetPath.getPathFromRoot()) {
849 if (result instanceof DataNodeContainer) {
850 final QName resultNode = node.withModule(result.getQName().getModule());
851 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
852 } else if (result instanceof ChoiceSchemaNode) {
853 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
856 if (result == null) {
860 if (result instanceof DerivableSchemaNode) {
861 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
862 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
863 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
864 result = originalNode.get();
868 if (result instanceof DataSchemaNode) {
869 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
870 if (resultDataSchemaNode.isAddedByUses()) {
871 // The original node is required, but we have only the copy of
872 // the original node.
873 // Maybe this indicates a bug in Yang parser.
874 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
877 return resultDataSchemaNode;
880 throw new IllegalStateException(
881 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
886 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
887 * of augmented node with serial number as suffix.
889 * @param context current module
890 * @param augmentPackageName string with contains the package name to which the augment belongs
891 * @param basePackageName string with the package name to which the augmented node belongs
892 * @param targetTypeRef target type
893 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
894 * @return generated type builder for augment
896 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
897 final String augmentPackageName, final Type targetTypeRef,
898 final AugmentationSchemaNode augSchema) {
899 Map<String, GeneratedTypeBuilder> augmentBuilders =
900 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
901 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
904 if (augIdentifier != null) {
905 augTypeName = BindingMapping.getClassName(augIdentifier);
907 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
910 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
911 JavaTypeName.create(augmentPackageName, augTypeName));
913 augTypeBuilder.addImplementsType(DATA_OBJECT);
914 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
915 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
916 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
918 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
919 augmentBuilders.put(augTypeName, augTypeBuilder);
921 if (!augSchema.getChildNodes().isEmpty()) {
922 context.addTypeToAugmentation(augTypeBuilder, augSchema);
925 context.addAugmentType(augTypeBuilder);
926 return augTypeBuilder;
929 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
930 final AugmentationSchemaNode augSchema) {
931 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
934 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
935 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
936 final QName nodeType = unknownSchemaNode.getNodeType();
937 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
938 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
939 return unknownSchemaNode.getNodeParameter();
946 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
947 * consists from name of augmented node and serial number of its augmentation.
949 * @param builders map of builders which were created in the package to which the augmentation belongs
950 * @param genTypeName string with name of augmented node
951 * @return string with unique name for augmentation builder
953 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
955 if (builders != null) {
956 while (builders.containsKey(genTypeName + index)) {
960 return genTypeName + index;
964 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
965 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
966 * already part of them).
968 * @param module current module
969 * @param parent generated type builder which represents any node. The subnodes of this node are added
970 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
972 * @param childOf parent type
973 * @param schemaNodes set of data schema nodes which are the children of the node for which
974 * <code>typeBuilder</code> was created
975 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
976 * child nodes) could be added to it.
978 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
979 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
980 if (schemaNodes != null && parent != null) {
981 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
982 for (final DataSchemaNode schemaNode : schemaNodes) {
983 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
984 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
992 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
995 * @param module current module
996 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
997 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
999 * @param childOf parent type
1000 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1002 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1003 * The getter method could be added to it.
1005 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1006 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1007 if (schemaNodes != null && typeBuilder != null) {
1008 final Type baseInterface = childOf(typeBuilder);
1009 for (final DataSchemaNode schemaNode : schemaNodes) {
1010 if (!schemaNode.isAugmenting()) {
1011 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1019 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1021 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1022 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1023 * @param childOf parent type
1024 * @param module current module
1026 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1027 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1028 if (node != null && typeBuilder != null) {
1029 if (node instanceof LeafSchemaNode) {
1030 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1031 } else if (node instanceof LeafListSchemaNode) {
1032 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1033 } else if (node instanceof ContainerSchemaNode) {
1034 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1035 } else if (node instanceof ListSchemaNode) {
1036 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1037 } else if (node instanceof ChoiceSchemaNode) {
1038 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1040 // TODO: anyxml not yet supported
1041 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1042 typeBuilder.getFullyQualifiedName());
1048 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1049 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1050 * and names of all parents node.
1052 * @param context current module
1053 * @param basePackageName string with the module package name
1054 * @param parent parent type
1055 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1057 * @throws IllegalArgumentException
1059 * <li>if <code>basePackageName</code> is null</li>
1060 * <li>if <code>choiceNode</code> is null</li>
1063 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1064 final ChoiceSchemaNode choiceNode) {
1065 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1067 if (!choiceNode.isAddedByUses()) {
1068 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1069 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1070 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1071 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1072 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1073 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1075 final GeneratedType choiceType = choiceTypeBuilder.build();
1076 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1078 constructGetter(parent, choiceType, choiceNode);
1083 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1084 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1085 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1086 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1088 * @param context current module context
1089 * @param refChoiceType type which represents superior <i>case</i>
1090 * @param choiceNode choice case node which is mapped to generated type
1091 * @throws IllegalArgumentException
1093 * <li>if <code>refChoiceType</code> equals null</li>
1094 * <li>if <code>caseNodes</code> equals null</li>
1097 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1098 final ChoiceSchemaNode choiceNode) {
1099 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1100 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1102 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1103 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1104 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1105 caseTypeBuilder.addImplementsType(refChoiceType);
1106 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1107 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1108 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1109 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1110 if (caseChildNodes != null) {
1111 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1113 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1114 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1116 if (parent instanceof AugmentationSchemaNode) {
1117 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1118 final SchemaPath targetPath = augSchema.getTargetPath();
1119 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1120 if (targetSchemaNode instanceof DataSchemaNode
1121 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1122 if (targetSchemaNode instanceof DerivableSchemaNode) {
1123 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1126 if (targetSchemaNode == null) {
1127 throw new IllegalStateException(
1128 "Failed to find target node from grouping for augmentation " + augSchema
1129 + " in module " + context.module().getName());
1132 parent = targetSchemaNode;
1135 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1136 Type childOfType = findChildNodeByPath(parent.getPath());
1137 if (childOfType == null) {
1138 childOfType = findGroupingByPath(parent.getPath());
1140 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1142 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1146 processUsesAugments(caseNode, context);
1151 * Generates list of generated types for all the cases of a choice which are added to the choice through
1154 * @param module current module
1155 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1156 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1157 * of the augmenting choice will belong to pcg2.
1158 * @param targetType Type which represents target choice
1159 * @param targetNode node which represents target choice
1160 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1162 * @throws IllegalArgumentException
1164 * <li>if <code>basePackageName</code> is null</li>
1165 * <li>if <code>targetType</code> is null</li>
1166 * <li>if <code>augmentedNodes</code> is null</li>
1169 // FIXME: nullness rules need to untangled in this method
1170 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1171 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1172 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1173 final DataNodeContainer usesNodeParent) {
1174 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1175 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1177 for (final DataSchemaNode caseNode : augmentedNodes) {
1178 if (caseNode != null) {
1179 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1180 caseTypeBuilder.addImplementsType(targetType);
1182 CaseSchemaNode node = null;
1183 final String caseLocalName = caseNode.getQName().getLocalName();
1184 if (caseNode instanceof CaseSchemaNode) {
1185 node = (CaseSchemaNode) caseNode;
1186 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1187 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1188 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1189 if (dataSchemaNode instanceof ChoiceSchemaNode
1190 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1191 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1196 node = findNamedCase(targetNode, caseLocalName);
1198 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1199 if (childNodes != null) {
1200 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1202 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1203 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1208 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1209 final SchemaPath nodePath = targetNode.getPath();
1210 final SchemaPath parentSp = nodePath.getParent();
1211 if (parentSp.getParent() == null) {
1212 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1215 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1216 GeneratedTypeBuilder childOfType = null;
1217 if (parent instanceof CaseSchemaNode) {
1218 childOfType = findCaseByPath(parent.getPath());
1219 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1220 childOfType = findChildNodeByPath(parent.getPath());
1221 } else if (parent instanceof GroupingDefinition) {
1222 childOfType = findGroupingByPath(parent.getPath());
1225 if (childOfType == null) {
1226 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1232 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1233 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1234 return cases.isEmpty() ? null : cases.get(0);
1237 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1238 // New parser with encapsulated type
1239 if (leaf.getPath().equals(type.getPath())) {
1243 // Embedded type definition with new parser. Also takes care of the old parser with bits
1244 if (leaf.getPath().equals(type.getPath().getParent())) {
1251 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1252 final List<PatternConstraint> patternConstraints) {
1253 if (!patternConstraints.isEmpty()) {
1254 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1255 .append(BindingMapping.getPropertyName(leafName));
1256 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1257 typeProvider.resolveRegExpressions(patternConstraints));
1262 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1264 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1265 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1266 * @param module Module in which type was defined
1267 * @return boolean value
1269 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1271 * <li>true - in other cases</li>
1274 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1275 final ModuleContext context) {
1276 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1280 final Module parentModule = findParentModule(schemaContext, leaf);
1281 Type returnType = null;
1283 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1284 if (isInnerType(leaf, typeDef)) {
1285 if (typeDef instanceof EnumTypeDefinition) {
1286 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1287 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1288 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1289 typeBuilder, context);
1290 if (enumBuilder != null) {
1291 returnType = enumBuilder.toInstance(typeBuilder);
1293 typeProvider.putReferencedType(leaf.getPath(), returnType);
1294 } else if (typeDef instanceof UnionTypeDefinition) {
1295 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1296 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1297 // Store the inner type within the union so that we can find the reference for it
1298 context.addInnerTypedefType(typeDef.getPath(), returnType);
1299 } else if (typeDef instanceof BitsTypeDefinition) {
1300 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1302 if (genTOBuilder != null) {
1303 returnType = genTOBuilder.build();
1306 // It is constrained version of already declared type (inner declared type exists,
1307 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1308 // In order to get proper class we need to look up closest derived type
1309 // and apply restrictions from leaf type
1310 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1311 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1313 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1316 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1317 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1318 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1321 if (returnType == null) {
1325 if (typeDef instanceof EnumTypeDefinition) {
1326 typeProvider.putReferencedType(leaf.getPath(), returnType);
1329 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1330 processContextRefExtension(leaf, getter, parentModule);
1334 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1335 // Returns DerivedType in case of new parser.
1336 final TypeDefinition<?> baseType = typeDef.getBaseType();
1337 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1340 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1341 final Module module) {
1342 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1343 final QName nodeType = node.getNodeType();
1344 if ("context-reference".equals(nodeType.getLocalName())) {
1345 final String nodeParam = node.getNodeParameter();
1346 IdentitySchemaNode identity = null;
1347 String basePackageName = null;
1348 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1349 final Iterator<String> iterator = splittedElement.iterator();
1350 final int length = Iterables.size(splittedElement);
1352 identity = findIdentityByName(module.getIdentities(), iterator.next());
1353 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1354 } else if (length == 2) {
1355 final String prefix = iterator.next();
1356 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1357 if (dependentModule == null) {
1358 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1361 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1362 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1364 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1367 if (identity == null) {
1368 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1372 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1373 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1374 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1375 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1380 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1381 for (final IdentitySchemaNode id : identities) {
1382 if (id.getQName().getLocalName().equals(name)) {
1389 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1390 for (final ModuleImport imp : imports) {
1391 if (imp.getPrefix().equals(prefix)) {
1392 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1398 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1399 final boolean isReadOnly) {
1400 if (leaf != null && toBuilder != null) {
1402 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1403 if (typeDef instanceof UnionTypeDefinition) {
1404 // GeneratedType for this type definition should have be already created
1405 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1406 returnType = mc.getTypedefs().get(typeDef.getPath());
1407 if (returnType == null) {
1408 // This may still be an inner type, try to find it
1409 returnType = mc.getInnerType(typeDef.getPath());
1411 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1412 // Annonymous enumeration (already generated, since it is inherited via uses).
1413 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1414 QName qname = originalLeaf.getQName();
1415 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1417 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1419 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1425 * Converts <code>leaf</code> schema node to property of generated TO builder.
1427 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1428 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1429 * @param returnType property type
1430 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1431 * @return boolean value
1433 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1434 * name equals null or if leaf is added by <i>uses</i>.</li>
1435 * <li>true - other cases</li>
1438 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1439 final Type returnType, final boolean isReadOnly) {
1440 if (returnType == null) {
1443 final String leafName = leaf.getQName().getLocalName();
1444 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1445 propBuilder.setReadOnly(isReadOnly);
1446 propBuilder.setReturnType(returnType);
1447 addComment(propBuilder, leaf);
1449 toBuilder.addEqualsIdentity(propBuilder);
1450 toBuilder.addHashIdentity(propBuilder);
1451 toBuilder.addToStringProperty(propBuilder);
1456 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1458 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1459 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1460 * @param module module
1461 * @return boolean value
1463 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1464 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1465 * <li>false - other cases</li>
1468 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1469 final ModuleContext context) {
1470 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1474 final QName nodeName = node.getQName();
1476 final TypeDefinition<?> typeDef = node.getType();
1477 final Module parentModule = findParentModule(schemaContext, node);
1479 Type returnType = null;
1480 if (typeDef.getBaseType() == null) {
1481 if (typeDef instanceof EnumTypeDefinition) {
1482 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1483 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1484 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1485 typeBuilder, context);
1486 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1487 typeProvider.putReferencedType(node.getPath(), returnType);
1488 } else if (typeDef instanceof UnionTypeDefinition) {
1489 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1490 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1491 } else if (typeDef instanceof BitsTypeDefinition) {
1492 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1493 node, parentModule);
1494 returnType = genTOBuilder.build();
1496 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1497 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1498 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1501 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1502 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1503 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1506 final ParameterizedType listType = listTypeFor(returnType);
1507 constructGetter(typeBuilder, listType, node);
1511 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1512 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1513 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1514 returnTypeBuilder.setIsUnion(true);
1515 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1516 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1517 returnTypeBuilder.setModuleName(parentModule.getName());
1518 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1520 genTOBuilder.setTypedef(true);
1521 genTOBuilder.setIsUnion(true);
1522 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1524 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1528 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1529 final GeneratedTransferObject returnType, final Module parentModule) {
1530 // Append enclosing path hierarchy without dots
1531 final StringBuilder sb = new StringBuilder();
1532 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1533 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1534 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1535 unionBuilder.setIsUnionBuilder(true);
1537 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1538 method.setReturnType(returnType);
1539 method.addParameter(Types.STRING, "defaultValue");
1540 method.setAccessModifier(AccessModifier.PUBLIC);
1541 method.setStatic(true);
1543 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1544 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1545 if (types == null) {
1546 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1548 types.add(unionBuilderType);
1552 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1553 final SchemaNode schemaNode) {
1554 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1557 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1558 final SchemaNode schemaNode, final Type baseInterface) {
1559 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1560 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1564 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1565 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1566 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1567 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1568 * If <code>schemaNode</code> is instance of
1569 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1570 * which are specified in <i>uses</i>.
1572 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1573 * @param schemaNode schema node for which is created generated type builder
1574 * @param parent parent type (can be null)
1575 * @return generated type builder <code>schemaNode</code>
1577 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1578 final Type baseInterface, final ModuleContext context) {
1579 JavaTypeName name = renames.get(schemaNode);
1581 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1584 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1586 it.addImplementsType(baseInterface);
1587 if (!(schemaNode instanceof GroupingDefinition)) {
1588 it.addImplementsType(augmentable(it));
1590 if (schemaNode instanceof DataNodeContainer) {
1591 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1592 groupingsToGenTypes(context, containerSchema.getGroupings());
1593 addImplementedInterfaceFromUses(containerSchema, it);
1600 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1601 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1602 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1604 * @param packageName string with the package name to which returning generated type builder belongs
1605 * @param schemaNode schema node which provide data about the schema node name
1606 * @param prefix return type name prefix
1607 * @return generated type builder for <code>schemaNode</code>
1608 * @throws IllegalArgumentException
1610 * <li>if <code>schemaNode</code> is null</li>
1611 * <li>if <code>packageName</code> is null</li>
1612 * <li>if QName of schema node is null</li>
1613 * <li>if schemaNode name is null</li>
1616 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1617 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1618 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1619 final String schemaNodeName = schemaNode.getQName().getLocalName();
1620 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1622 // FIXME: Validation of name conflict
1623 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1624 final Module module = findParentModule(schemaContext, schemaNode);
1625 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1626 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1628 addCodegenInformation(newType, module, schemaNode);
1629 newType.setSchemaPath(schemaNode.getPath());
1630 newType.setModuleName(module.getName());
1632 final String packageName = identifier.packageName();
1633 final String simpleName = identifier.simpleName();
1634 if (!genTypeBuilders.containsKey(packageName)) {
1635 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1636 builders.put(simpleName, newType);
1637 genTypeBuilders.put(packageName, builders);
1639 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1640 if (!builders.containsKey(simpleName)) {
1641 builders.put(simpleName, newType);
1648 * Creates the name of the getter method name from <code>localName</code>.
1650 * @param localName string with the name of the getter method
1651 * @param returnType return type
1652 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1654 public static String getterMethodName(final String localName, final Type returnType) {
1655 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1659 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1660 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1661 * and <code>returnType</code> information are added to the builder.
1663 * @param interfaceBuilder generated type builder for which the getter method should be created
1664 * @param returnType type which represents the return type of the getter method
1665 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1666 * @param comment string with comment for the getter method
1667 * @param status status from yang file, for deprecated annotation
1668 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1670 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1671 final SchemaNode node) {
1672 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1673 getterMethodName(node.getQName().getLocalName(), returnType));
1674 getMethod.setReturnType(returnType);
1676 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1677 addComment(getMethod, node);
1683 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1686 * @param basePackageName string contains the module package name
1687 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1688 * or as a property to <code>genTOBuilder</code> if is part of the list key
1689 * @param typeBuilder generated type builder for the list schema node
1690 * @param genTOBuilder generated TO builder for the list keys
1691 * @param listKeys list of string which contains names of the list keys
1692 * @param module current module
1693 * @throws IllegalArgumentException
1695 * <li>if <code>schemaNode</code> equals null</li>
1696 * <li>if <code>typeBuilder</code> equals null</li>
1699 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1700 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1701 final List<String> listKeys) {
1702 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1703 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1705 if (schemaNode instanceof LeafSchemaNode) {
1706 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1707 final String leafName = leaf.getQName().getLocalName();
1708 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1709 if (listKeys.contains(leafName)) {
1711 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1713 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1716 } else if (!schemaNode.isAddedByUses()) {
1717 if (schemaNode instanceof LeafListSchemaNode) {
1718 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1719 } else if (schemaNode instanceof ContainerSchemaNode) {
1720 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1721 (ContainerSchemaNode) schemaNode);
1722 } else if (schemaNode instanceof ChoiceSchemaNode) {
1723 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1724 } else if (schemaNode instanceof ListSchemaNode) {
1725 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1730 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1731 final GeneratedTOBuilder genTOBuilder) {
1732 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1734 if (genTOBuilder != null) {
1735 final GeneratedTransferObject genTO = genTOBuilder.build();
1736 // Add Identifiable.getKey() for items
1737 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1738 .addAnnotation(OVERRIDE_ANNOTATION);
1739 context.addGeneratedTOBuilder(genTOBuilder);
1744 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1746 * @param list of string with names of the list keys
1747 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1748 * an empty list is returned.
1750 private static List<String> listKeys(final ListSchemaNode list) {
1751 final List<String> listKeys = new ArrayList<>();
1753 final List<QName> keyDefinition = list.getKeyDefinition();
1754 if (keyDefinition != null) {
1755 for (final QName keyDef : keyDefinition) {
1756 listKeys.add(keyDef.getLocalName());
1763 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1765 * @param packageName string with package name to which the list belongs
1766 * @param list list schema node which is source of data about the list name
1767 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1768 * null or list of key definitions is null or empty.
1770 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1771 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1772 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1773 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1774 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1780 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1781 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1782 * enclosing transfer objects.
1784 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1785 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1786 * @param leaf string with name for generated TO builder
1787 * @param parentModule parent module
1788 * @return generated TO builder for <code>typeDef</code>
1790 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1791 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1792 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1793 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1796 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1797 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1798 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1799 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1800 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1802 for (GeneratedTOBuilder builder : types) {
1803 if (builder.isUnion()) {
1804 final GeneratedTransferObject type = builder.build();
1805 createUnionBuilder(builder, typeBuilder, type, parentModule);
1809 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1813 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1814 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1815 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1818 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1819 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1820 * @param leaf string with name for generated TO builder
1821 * @param parentModule parent module
1822 * @return generated TO builder for <code>typeDef</code>
1824 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1825 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1826 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1827 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1828 typeDef, parentModule.getName());
1829 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1830 return genTOBuilder;
1835 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1836 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1837 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1838 * to <code>builder</code>
1840 * @param dataNodeContainer element which contains the list of used YANG groupings
1841 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1842 * @return generated type builder with all implemented types
1844 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1845 final GeneratedTypeBuilder builder) {
1846 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1847 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1848 if (genType == null) {
1849 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1850 + builder.getName());
1853 builder.addImplementsType(genType);
1858 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1859 for (final ModuleContext ctx : genCtx.values()) {
1860 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1861 if (result != null) {
1868 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1869 for (final ModuleContext ctx : genCtx.values()) {
1870 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1871 if (result != null) {
1878 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1879 for (final ModuleContext ctx : genCtx.values()) {
1880 final GeneratedTypeBuilder result = ctx.getCase(path);
1881 if (result != null) {
1888 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1889 if (status == Status.DEPRECATED) {
1890 builder.addAnnotation(DEPRECATED_ANNOTATION);