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 final ParameterizedType listType = listTypeFor(genType);
304 constructGetter(parent, listType, node);
305 constructNonnull(parent, listType, node);
307 final List<String> listKeys = listKeys(node);
308 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
309 if (genTOBuilder != null) {
310 final Type identifierMarker = identifier(genType);
311 final Type identifiableMarker = identifiable(genTOBuilder);
312 genTOBuilder.addImplementsType(identifierMarker);
313 genType.addImplementsType(identifiableMarker);
316 actionsToGenType(context, genType, node, genTOBuilder);
318 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
319 if (!schemaNode.isAugmenting()) {
320 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
325 if (genTOBuilder != null) {
326 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
327 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
328 genTOBuilder.setSUID(prop);
331 typeBuildersToGenTypes(context, genType, genTOBuilder);
335 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
336 for (final UsesNode usesNode : node.getUses()) {
337 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
338 usesAugmentationToGenTypes(context, augment, usesNode, node);
339 processUsesAugments(augment, context);
345 * Converts all <b>augmentation</b> of the module to the list
346 * <code>Type</code> objects.
349 * module from which is obtained list of all augmentation objects
350 * to iterate over them
351 * @throws IllegalArgumentException
353 * <li>if the module is null</li>
354 * <li>if the name of module is null</li>
356 * @throws IllegalStateException
357 * if set of augmentations from module is null
359 private void allAugmentsToGenTypes(final ModuleContext context) {
360 final Module module = context.module();
361 checkArgument(module != null, "Module reference cannot be NULL.");
362 checkArgument(module.getName() != null, "Module name cannot be NULL.");
363 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
365 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
366 augmentationToGenTypes(context, augment);
371 * Returns list of <code>AugmentationSchema</code> objects. The objects are
372 * sorted according to the length of their target path from the shortest to
376 * module from which is obtained list of all augmentation objects
377 * @return list of sorted <code>AugmentationSchema</code> objects obtained
378 * from <code>module</code>
379 * @throws IllegalArgumentException
381 * @throws IllegalStateException
382 * if set of module augmentations is null
384 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
385 checkArgument(module != null, "Module reference cannot be NULL.");
386 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
388 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
389 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
390 sortedAugmentations.sort(AUGMENT_COMP);
392 return sortedAugmentations;
396 * Create GeneratedTypeBuilder object from module argument.
399 * Module object from which builder will be created
400 * @return <code>GeneratedTypeBuilder</code> which is internal
401 * representation of the module
402 * @throws IllegalArgumentException
405 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
406 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
407 final Module module = context.module();
408 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
409 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
411 addCodegenInformation(moduleDataTypeBuilder, module);
412 return moduleDataTypeBuilder;
415 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
416 final Type parent, final T parentSchema, final Type keyType) {
417 for (final ActionDefinition action : parentSchema.getActions()) {
418 final GeneratedType input;
419 final GeneratedType output;
420 if (action.isAddedByUses()) {
421 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
422 input = context.getChildNode(orig.getInput().getPath()).build();
423 output = context.getChildNode(orig.getOutput().getPath()).build();
425 input = actionContainer(context, RPC_INPUT, action.getInput());
426 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
429 if (!(parentSchema instanceof GroupingDefinition)) {
430 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
431 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
432 // and do not capture an actual instantiation.
433 final QName qname = action.getQName();
434 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
435 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
436 BindingMapping.getClassName(qname)));
437 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
438 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
440 annotateDeprecatedIfNecessary(action.getStatus(), builder);
441 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
442 : action(parent, input, output));
444 addCodegenInformation(builder, context.module(), action);
445 context.addChildNodeType(action, builder);
450 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
451 for (UsesNode uses : parent.getUses()) {
452 final GroupingDefinition grp = findUsedGrouping(uses);
453 final Optional<ActionDefinition> found = grp.getActions().stream()
454 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
455 if (found.isPresent()) {
456 final ActionDefinition result = found.get();
457 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
461 return Optional.empty();
464 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
465 final ContainerSchemaNode schema) {
466 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
467 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
468 return genType.build();
472 * Converts all <b>RPCs</b> input and output substatements of the module
473 * to the list of <code>Type</code> objects. In addition are to containers
474 * and lists which belong to input or output also part of returning list.
477 * module from which is obtained set of all rpc objects to
479 * @throws IllegalArgumentException
481 * <li>if the module is null</li>
482 * <li>if the name of module is null</li>
484 * @throws IllegalStateException
485 * if set of rpcs from module is null
487 private void rpcMethodsToGenType(final ModuleContext context) {
488 final Module module = context.module();
489 checkArgument(module.getName() != null, "Module name cannot be NULL.");
490 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
491 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
492 if (rpcDefinitions.isEmpty()) {
496 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
497 interfaceBuilder.addImplementsType(RPC_SERVICE);
499 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
501 for (final RpcDefinition rpc : rpcDefinitions) {
503 final String rpcName = BindingMapping.getClassName(rpc.getQName());
504 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
505 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
507 // Do not refer to annotation class, as it may not be available at runtime
508 // FIXME: migrate this to some other annotation type and re-enable
510 // method.addAnnotation("javax.annotation", "CheckReturnValue");
511 addComment(method, rpc);
513 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
514 method.setReturnType(listenableFutureTypeFor(
515 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
519 context.addTopLevelNodeType(interfaceBuilder);
522 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
523 final ContainerSchemaNode schema, final Type type) {
524 processUsesAugments(schema, context);
525 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
526 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
528 addImplementedInterfaceFromUses(schema, outType);
529 outType.addImplementsType(type);
530 outType.addImplementsType(augmentable(outType));
531 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
532 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
533 context.addChildNodeType(schema, outType);
534 return outType.build();
538 * Converts all <b>notifications</b> of the module to the list of
539 * <code>Type</code> objects. In addition are to this list added containers
540 * and lists which are part of this notification.
543 * module from which is obtained set of all notification objects
544 * to iterate over them
545 * @throws IllegalArgumentException
547 * <li>if the module equals null</li>
548 * <li>if the name of module equals null</li>
550 * @throws IllegalStateException
551 * if set of notifications from module is null
553 private void notificationsToGenType(final ModuleContext context) {
554 final Module module = context.module();
555 checkArgument(module.getName() != null, "Module name cannot be NULL.");
556 final Set<NotificationDefinition> notifications = module.getNotifications();
557 if (notifications.isEmpty()) {
561 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
562 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
564 for (final NotificationDefinition notification : notifications) {
565 if (notification != null) {
566 processUsesAugments(notification, context);
568 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
569 context.modulePackageName(), notification, DATA_OBJECT, context);
570 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
571 notificationInterface.addImplementsType(NOTIFICATION);
572 context.addChildNodeType(notification, notificationInterface);
574 // Notification object
575 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
576 notification.getChildNodes());
578 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
579 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
580 .setReturnType(Types.primitiveVoidType()), notification);
584 addCodegenInformation(listenerInterface, module, "notifications", notifications);
585 context.addTopLevelNodeType(listenerInterface);
589 * Converts all <b>identities</b> of the module to the list of
590 * <code>Type</code> objects.
593 * module from which is obtained set of all identity objects to
595 * @param schemaContext
596 * schema context only used as input parameter for method
597 * {@link BindingGeneratorImpl#identityToGenType}
600 private void allIdentitiesToGenTypes(final ModuleContext context) {
601 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
603 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
604 for (final IdentitySchemaNode identity : schemaIdentities) {
605 identityToGenType(context, identity);
611 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
612 * created transport object builder. If identity contains base identity then
613 * reference to base identity is added to superior identity as its extend.
614 * If identity doesn't contain base identity then only reference to abstract
615 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
616 * BaseIdentity} is added
620 * @param basePackageName
621 * string contains the module package name
623 * IdentitySchemaNode which contains data about identity
625 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
626 if (identity == null) {
630 JavaTypeName name = renames.get(identity);
632 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
633 BindingMapping.getClassName(identity.getQName()));
636 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
637 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
638 if (!baseIdentities.isEmpty()) {
639 for (IdentitySchemaNode baseIdentity : baseIdentities) {
640 JavaTypeName base = renames.get(baseIdentity);
642 final QName qname = baseIdentity.getQName();
643 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
644 BindingMapping.getClassName(qname));
647 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
648 newType.addImplementsType(gto);
651 newType.addImplementsType(BASE_IDENTITY);
654 final Module module = context.module();
655 addCodegenInformation(newType, module, identity);
656 newType.setModuleName(module.getName());
657 newType.setSchemaPath(identity.getPath());
659 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
660 identity.getQName().getLocalName());
662 context.addIdentityType(identity, newType);
665 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
666 final JavaTypeName yangModuleInfo, final String localName) {
667 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
668 new SimpleImmutableEntry<>(yangModuleInfo, localName));
672 * Converts all <b>groupings</b> of the module to the list of
673 * <code>Type</code> objects. Firstly are groupings sorted according mutual
674 * dependencies. At least dependent (independent) groupings are in the list
675 * saved at first positions. For every grouping the record is added to map
676 * {@link ModuleContext#groupings allGroupings}
681 * collection of groupings from which types will be generated
684 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
685 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
686 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
687 // node of grouping is resolved to the method.
688 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
689 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
690 context.addGroupingType(grouping, genType);
691 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
692 groupingsToGenTypes(context, grouping.getGroupings());
693 processUsesAugments(grouping, context);
694 actionsToGenType(context, genType, grouping, null);
699 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
700 * <code>enumTypeDef</code> item is added to builder with its name and value.
702 * @param enumTypeDef EnumTypeDefinition contains enum data
703 * @param enumName string contains name which will be assigned to enumeration builder
704 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
705 * @param module Module in which type should be generated
706 * @return enumeration builder which contains data from <code>enumTypeDef</code>
708 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
709 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
710 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
711 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
712 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
713 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
714 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
721 * Generates type builder for <code>module</code>.
723 * @param module Module which is source of package name for generated type builder
724 * @param postfix string which is added to the module class name representation as suffix
725 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
726 * @throws IllegalArgumentException if <code>module</code> is null
728 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
729 final Module module = context.module();
730 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
731 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
732 JavaTypeName.create(context.modulePackageName(), moduleName));
734 moduleBuilder.setModuleName(moduleName);
735 addCodegenInformation(moduleBuilder, module);
736 return moduleBuilder;
740 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
741 * In addition there are also generated types for all containers, list and choices which are child of
742 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
744 * @param augmentPackageName string with the name of the package to which the augmentation belongs
745 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
746 * @param module current module
747 * @throws IllegalArgumentException
749 * <li>if <code>augmentPackageName</code> equals null</li>
750 * <li>if <code>augSchema</code> equals null</li>
752 * @throws IllegalStateException
753 * if augment target path is null
755 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
756 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
757 checkState(augSchema.getTargetPath() != null,
758 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
760 processUsesAugments(augSchema, context);
761 final SchemaPath targetPath = augSchema.getTargetPath();
762 SchemaNode targetSchemaNode = null;
764 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
765 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
766 if (targetSchemaNode instanceof DerivableSchemaNode) {
767 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
769 if (targetSchemaNode == null) {
770 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
771 + " in module " + context.module().getName());
774 if (targetSchemaNode == null) {
775 throw new IllegalArgumentException("augment target not found: " + targetPath);
778 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
779 if (targetTypeBuilder == null) {
780 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
782 if (targetTypeBuilder == null) {
783 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
786 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
787 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
788 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
791 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
792 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
796 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
797 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
798 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
799 checkState(augSchema.getTargetPath() != null,
800 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
802 processUsesAugments(augSchema, context);
803 final SchemaPath targetPath = augSchema.getTargetPath();
804 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
805 if (targetSchemaNode == null) {
806 throw new IllegalArgumentException("augment target not found: " + targetPath);
809 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
810 if (targetTypeBuilder == null) {
811 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
813 if (targetTypeBuilder == null) {
814 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
817 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
818 if (usesNodeParent instanceof SchemaNode) {
819 addRawAugmentGenTypeDefinition(context,
820 packageNameForAugmentedGeneratedType(context.modulePackageName(),
821 ((SchemaNode) usesNodeParent).getPath()),
822 targetTypeBuilder.build(), augSchema);
824 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
827 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
828 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
832 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
833 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
835 if (targetGrouping instanceof GroupingDefinition) {
836 return (GroupingDefinition) targetGrouping;
839 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
843 * Convenient method to find node added by uses statement.
845 * @param targetPath node path
846 * @param parentUsesNode parent of uses node
847 * @return node from its original location in grouping
849 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
850 SchemaNode result = findUsedGrouping(parentUsesNode);
851 for (final QName node : targetPath.getPathFromRoot()) {
852 if (result instanceof DataNodeContainer) {
853 final QName resultNode = node.withModule(result.getQName().getModule());
854 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
855 } else if (result instanceof ChoiceSchemaNode) {
856 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
859 if (result == null) {
863 if (result instanceof DerivableSchemaNode) {
864 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
865 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
866 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
867 result = originalNode.get();
871 if (result instanceof DataSchemaNode) {
872 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
873 if (resultDataSchemaNode.isAddedByUses()) {
874 // The original node is required, but we have only the copy of
875 // the original node.
876 // Maybe this indicates a bug in Yang parser.
877 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
880 return resultDataSchemaNode;
883 throw new IllegalStateException(
884 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
889 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
890 * of augmented node with serial number as suffix.
892 * @param context current module
893 * @param augmentPackageName string with contains the package name to which the augment belongs
894 * @param basePackageName string with the package name to which the augmented node belongs
895 * @param targetTypeRef target type
896 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
897 * @return generated type builder for augment
899 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
900 final String augmentPackageName, final Type targetTypeRef,
901 final AugmentationSchemaNode augSchema) {
902 Map<String, GeneratedTypeBuilder> augmentBuilders =
903 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
904 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
907 if (augIdentifier != null) {
908 augTypeName = BindingMapping.getClassName(augIdentifier);
910 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
913 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
914 JavaTypeName.create(augmentPackageName, augTypeName));
916 augTypeBuilder.addImplementsType(DATA_OBJECT);
917 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
918 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
919 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
921 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
922 augmentBuilders.put(augTypeName, augTypeBuilder);
924 if (!augSchema.getChildNodes().isEmpty()) {
925 context.addTypeToAugmentation(augTypeBuilder, augSchema);
928 context.addAugmentType(augTypeBuilder);
929 return augTypeBuilder;
932 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
933 final AugmentationSchemaNode augSchema) {
934 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
937 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
938 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
939 final QName nodeType = unknownSchemaNode.getNodeType();
940 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
941 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
942 return unknownSchemaNode.getNodeParameter();
949 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
950 * consists from name of augmented node and serial number of its augmentation.
952 * @param builders map of builders which were created in the package to which the augmentation belongs
953 * @param genTypeName string with name of augmented node
954 * @return string with unique name for augmentation builder
956 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
958 if (builders != null) {
959 while (builders.containsKey(genTypeName + index)) {
963 return genTypeName + index;
967 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
968 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
969 * already part of them).
971 * @param module current module
972 * @param parent generated type builder which represents any node. The subnodes of this node are added
973 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
975 * @param childOf parent type
976 * @param schemaNodes set of data schema nodes which are the children of the node for which
977 * <code>typeBuilder</code> was created
978 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
979 * child nodes) could be added to it.
981 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
982 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
983 if (schemaNodes != null && parent != null) {
984 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
985 for (final DataSchemaNode schemaNode : schemaNodes) {
986 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
987 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
995 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
998 * @param module current module
999 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1000 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1001 * container, choice.
1002 * @param childOf parent type
1003 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1005 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1006 * The getter method could be added to it.
1008 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1009 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1010 if (schemaNodes != null && typeBuilder != null) {
1011 final Type baseInterface = childOf(typeBuilder);
1012 for (final DataSchemaNode schemaNode : schemaNodes) {
1013 if (!schemaNode.isAugmenting()) {
1014 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1022 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1024 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1025 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1026 * @param childOf parent type
1027 * @param module current module
1029 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1030 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1031 if (node != null && typeBuilder != null) {
1032 if (node instanceof LeafSchemaNode) {
1033 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1034 } else if (node instanceof LeafListSchemaNode) {
1035 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1036 } else if (node instanceof ContainerSchemaNode) {
1037 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1038 } else if (node instanceof ListSchemaNode) {
1039 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1040 } else if (node instanceof ChoiceSchemaNode) {
1041 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1043 // TODO: anyxml not yet supported
1044 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1045 typeBuilder.getFullyQualifiedName());
1051 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1052 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1053 * and names of all parents node.
1055 * @param context current module
1056 * @param basePackageName string with the module package name
1057 * @param parent parent type
1058 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1060 * @throws IllegalArgumentException
1062 * <li>if <code>basePackageName</code> is null</li>
1063 * <li>if <code>choiceNode</code> is null</li>
1066 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1067 final ChoiceSchemaNode choiceNode) {
1068 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1070 if (!choiceNode.isAddedByUses()) {
1071 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1072 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1073 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1074 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1075 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1076 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1078 final GeneratedType choiceType = choiceTypeBuilder.build();
1079 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1081 constructGetter(parent, choiceType, choiceNode);
1086 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1087 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1088 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1089 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1091 * @param context current module context
1092 * @param refChoiceType type which represents superior <i>case</i>
1093 * @param choiceNode choice case node which is mapped to generated type
1094 * @throws IllegalArgumentException
1096 * <li>if <code>refChoiceType</code> equals null</li>
1097 * <li>if <code>caseNodes</code> equals null</li>
1100 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1101 final ChoiceSchemaNode choiceNode) {
1102 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1103 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1105 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1106 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1107 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1108 caseTypeBuilder.addImplementsType(refChoiceType);
1109 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1110 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1111 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1112 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1113 if (caseChildNodes != null) {
1114 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1116 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1117 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1119 if (parent instanceof AugmentationSchemaNode) {
1120 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1121 final SchemaPath targetPath = augSchema.getTargetPath();
1122 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1123 if (targetSchemaNode instanceof DataSchemaNode
1124 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1125 if (targetSchemaNode instanceof DerivableSchemaNode) {
1126 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1129 if (targetSchemaNode == null) {
1130 throw new IllegalStateException(
1131 "Failed to find target node from grouping for augmentation " + augSchema
1132 + " in module " + context.module().getName());
1135 parent = targetSchemaNode;
1138 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1139 Type childOfType = findChildNodeByPath(parent.getPath());
1140 if (childOfType == null) {
1141 childOfType = findGroupingByPath(parent.getPath());
1143 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1145 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1149 processUsesAugments(caseNode, context);
1154 * Generates list of generated types for all the cases of a choice which are added to the choice through
1157 * @param module current module
1158 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1159 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1160 * of the augmenting choice will belong to pcg2.
1161 * @param targetType Type which represents target choice
1162 * @param targetNode node which represents target choice
1163 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1165 * @throws IllegalArgumentException
1167 * <li>if <code>basePackageName</code> is null</li>
1168 * <li>if <code>targetType</code> is null</li>
1169 * <li>if <code>augmentedNodes</code> is null</li>
1172 // FIXME: nullness rules need to untangled in this method
1173 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1174 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1175 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1176 final DataNodeContainer usesNodeParent) {
1177 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1178 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1180 for (final DataSchemaNode caseNode : augmentedNodes) {
1181 if (caseNode != null) {
1182 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1183 caseTypeBuilder.addImplementsType(targetType);
1185 CaseSchemaNode node = null;
1186 final String caseLocalName = caseNode.getQName().getLocalName();
1187 if (caseNode instanceof CaseSchemaNode) {
1188 node = (CaseSchemaNode) caseNode;
1189 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1190 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1191 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1192 if (dataSchemaNode instanceof ChoiceSchemaNode
1193 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1194 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1199 node = findNamedCase(targetNode, caseLocalName);
1201 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1202 if (childNodes != null) {
1203 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1205 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1206 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1211 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1212 final SchemaPath nodePath = targetNode.getPath();
1213 final SchemaPath parentSp = nodePath.getParent();
1214 if (parentSp.getParent() == null) {
1215 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1218 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1219 GeneratedTypeBuilder childOfType = null;
1220 if (parent instanceof CaseSchemaNode) {
1221 childOfType = findCaseByPath(parent.getPath());
1222 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1223 childOfType = findChildNodeByPath(parent.getPath());
1224 } else if (parent instanceof GroupingDefinition) {
1225 childOfType = findGroupingByPath(parent.getPath());
1228 if (childOfType == null) {
1229 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1235 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1236 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1237 return cases.isEmpty() ? null : cases.get(0);
1240 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1241 // New parser with encapsulated type
1242 if (leaf.getPath().equals(type.getPath())) {
1246 // Embedded type definition with new parser. Also takes care of the old parser with bits
1247 if (leaf.getPath().equals(type.getPath().getParent())) {
1254 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1255 final List<PatternConstraint> patternConstraints) {
1256 if (!patternConstraints.isEmpty()) {
1257 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1258 .append(BindingMapping.getPropertyName(leafName));
1259 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1260 typeProvider.resolveRegExpressions(patternConstraints));
1265 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1267 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1268 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1269 * @param module Module in which type was defined
1270 * @return boolean value
1272 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1274 * <li>true - in other cases</li>
1277 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1278 final ModuleContext context) {
1279 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1283 final Module parentModule = findParentModule(schemaContext, leaf);
1284 Type returnType = null;
1286 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1287 if (isInnerType(leaf, typeDef)) {
1288 if (typeDef instanceof EnumTypeDefinition) {
1289 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1290 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1291 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1292 typeBuilder, context);
1293 if (enumBuilder != null) {
1294 returnType = enumBuilder.toInstance(typeBuilder);
1296 typeProvider.putReferencedType(leaf.getPath(), returnType);
1297 } else if (typeDef instanceof UnionTypeDefinition) {
1298 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1299 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1300 // Store the inner type within the union so that we can find the reference for it
1301 context.addInnerTypedefType(typeDef.getPath(), returnType);
1302 } else if (typeDef instanceof BitsTypeDefinition) {
1303 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1305 if (genTOBuilder != null) {
1306 returnType = genTOBuilder.build();
1309 // It is constrained version of already declared type (inner declared type exists,
1310 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1311 // In order to get proper class we need to look up closest derived type
1312 // and apply restrictions from leaf type
1313 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1314 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1316 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1319 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1320 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1321 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1324 if (returnType == null) {
1328 if (typeDef instanceof EnumTypeDefinition) {
1329 typeProvider.putReferencedType(leaf.getPath(), returnType);
1332 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1333 processContextRefExtension(leaf, getter, parentModule);
1337 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1338 // Returns DerivedType in case of new parser.
1339 final TypeDefinition<?> baseType = typeDef.getBaseType();
1340 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1343 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1344 final Module module) {
1345 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1346 final QName nodeType = node.getNodeType();
1347 if ("context-reference".equals(nodeType.getLocalName())) {
1348 final String nodeParam = node.getNodeParameter();
1349 IdentitySchemaNode identity = null;
1350 String basePackageName = null;
1351 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1352 final Iterator<String> iterator = splittedElement.iterator();
1353 final int length = Iterables.size(splittedElement);
1355 identity = findIdentityByName(module.getIdentities(), iterator.next());
1356 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1357 } else if (length == 2) {
1358 final String prefix = iterator.next();
1359 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1360 if (dependentModule == null) {
1361 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1364 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1365 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1367 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1370 if (identity == null) {
1371 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1375 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1376 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1377 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1378 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1383 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1384 for (final IdentitySchemaNode id : identities) {
1385 if (id.getQName().getLocalName().equals(name)) {
1392 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1393 for (final ModuleImport imp : imports) {
1394 if (imp.getPrefix().equals(prefix)) {
1395 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1401 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1402 final boolean isReadOnly) {
1403 if (leaf != null && toBuilder != null) {
1405 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1406 if (typeDef instanceof UnionTypeDefinition) {
1407 // GeneratedType for this type definition should have be already created
1408 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1409 returnType = mc.getTypedefs().get(typeDef.getPath());
1410 if (returnType == null) {
1411 // This may still be an inner type, try to find it
1412 returnType = mc.getInnerType(typeDef.getPath());
1414 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1415 // Annonymous enumeration (already generated, since it is inherited via uses).
1416 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1417 QName qname = originalLeaf.getQName();
1418 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1420 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1422 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1428 * Converts <code>leaf</code> schema node to property of generated TO builder.
1430 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1431 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1432 * @param returnType property type
1433 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1434 * @return boolean value
1436 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1437 * name equals null or if leaf is added by <i>uses</i>.</li>
1438 * <li>true - other cases</li>
1441 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1442 final Type returnType, final boolean isReadOnly) {
1443 if (returnType == null) {
1446 final String leafName = leaf.getQName().getLocalName();
1447 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1448 propBuilder.setReadOnly(isReadOnly);
1449 propBuilder.setReturnType(returnType);
1450 addComment(propBuilder, leaf);
1452 toBuilder.addEqualsIdentity(propBuilder);
1453 toBuilder.addHashIdentity(propBuilder);
1454 toBuilder.addToStringProperty(propBuilder);
1459 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1461 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1462 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1463 * @param module module
1464 * @return boolean value
1466 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1467 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1468 * <li>false - other cases</li>
1471 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1472 final ModuleContext context) {
1473 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1477 final QName nodeName = node.getQName();
1479 final TypeDefinition<?> typeDef = node.getType();
1480 final Module parentModule = findParentModule(schemaContext, node);
1482 Type returnType = null;
1483 if (typeDef.getBaseType() == null) {
1484 if (typeDef instanceof EnumTypeDefinition) {
1485 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1486 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1487 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1488 typeBuilder, context);
1489 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1490 typeProvider.putReferencedType(node.getPath(), returnType);
1491 } else if (typeDef instanceof UnionTypeDefinition) {
1492 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1493 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1494 } else if (typeDef instanceof BitsTypeDefinition) {
1495 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1496 node, parentModule);
1497 returnType = genTOBuilder.build();
1499 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1500 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1501 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1504 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1505 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1506 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1509 constructGetter(typeBuilder, listTypeFor(returnType), node);
1513 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1514 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1515 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1516 returnTypeBuilder.setIsUnion(true);
1517 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1518 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1519 returnTypeBuilder.setModuleName(parentModule.getName());
1520 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1522 genTOBuilder.setTypedef(true);
1523 genTOBuilder.setIsUnion(true);
1524 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1526 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1530 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1531 final GeneratedTransferObject returnType, final Module parentModule) {
1532 // Append enclosing path hierarchy without dots
1533 final StringBuilder sb = new StringBuilder();
1534 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1535 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1536 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1537 unionBuilder.setIsUnionBuilder(true);
1539 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1540 method.setReturnType(returnType);
1541 method.addParameter(Types.STRING, "defaultValue");
1542 method.setAccessModifier(AccessModifier.PUBLIC);
1543 method.setStatic(true);
1545 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1546 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1547 if (types == null) {
1548 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1550 types.add(unionBuilderType);
1554 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1555 final SchemaNode schemaNode) {
1556 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1559 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1560 final SchemaNode schemaNode, final Type baseInterface) {
1561 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1562 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1566 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1567 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1568 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1569 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1570 * If <code>schemaNode</code> is instance of
1571 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1572 * which are specified in <i>uses</i>.
1574 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1575 * @param schemaNode schema node for which is created generated type builder
1576 * @param parent parent type (can be null)
1577 * @return generated type builder <code>schemaNode</code>
1579 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1580 final Type baseInterface, final ModuleContext context) {
1581 JavaTypeName name = renames.get(schemaNode);
1583 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1586 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1588 it.addImplementsType(baseInterface);
1589 if (!(schemaNode instanceof GroupingDefinition)) {
1590 it.addImplementsType(augmentable(it));
1592 if (schemaNode instanceof DataNodeContainer) {
1593 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1594 groupingsToGenTypes(context, containerSchema.getGroupings());
1595 addImplementedInterfaceFromUses(containerSchema, it);
1602 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1603 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1604 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1606 * @param packageName string with the package name to which returning generated type builder belongs
1607 * @param schemaNode schema node which provide data about the schema node name
1608 * @param prefix return type name prefix
1609 * @return generated type builder for <code>schemaNode</code>
1610 * @throws IllegalArgumentException
1612 * <li>if <code>schemaNode</code> is null</li>
1613 * <li>if <code>packageName</code> is null</li>
1614 * <li>if QName of schema node is null</li>
1615 * <li>if schemaNode name is null</li>
1618 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1619 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1620 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1621 final String schemaNodeName = schemaNode.getQName().getLocalName();
1622 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1624 // FIXME: Validation of name conflict
1625 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1626 final Module module = findParentModule(schemaContext, schemaNode);
1627 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1628 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1630 addCodegenInformation(newType, module, schemaNode);
1631 newType.setSchemaPath(schemaNode.getPath());
1632 newType.setModuleName(module.getName());
1634 final String packageName = identifier.packageName();
1635 final String simpleName = identifier.simpleName();
1636 if (!genTypeBuilders.containsKey(packageName)) {
1637 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1638 builders.put(simpleName, newType);
1639 genTypeBuilders.put(packageName, builders);
1641 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1642 if (!builders.containsKey(simpleName)) {
1643 builders.put(simpleName, newType);
1650 * Creates the name of the getter method name from <code>localName</code>.
1652 * @param localName string with the name of the getter method
1653 * @param returnType return type
1654 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1656 public static String getterMethodName(final String localName, final Type returnType) {
1657 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1661 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1662 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1663 * and <code>returnType</code> information are added to the builder.
1665 * @param interfaceBuilder generated type builder for which the getter method should be created
1666 * @param returnType type which represents the return type of the getter method
1667 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1668 * @param comment string with comment for the getter method
1669 * @param status status from yang file, for deprecated annotation
1670 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1672 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1673 final SchemaNode node) {
1674 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1675 getterMethodName(node.getQName().getLocalName(), returnType));
1676 getMethod.setReturnType(returnType);
1678 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1679 addComment(getMethod, node);
1684 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1685 final ListSchemaNode node) {
1686 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1687 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1688 getMethod.setReturnType(returnType).setDefault(true);
1689 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1693 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1696 * @param basePackageName string contains the module package name
1697 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1698 * or as a property to <code>genTOBuilder</code> if is part of the list key
1699 * @param typeBuilder generated type builder for the list schema node
1700 * @param genTOBuilder generated TO builder for the list keys
1701 * @param listKeys list of string which contains names of the list keys
1702 * @param module current module
1703 * @throws IllegalArgumentException
1705 * <li>if <code>schemaNode</code> equals null</li>
1706 * <li>if <code>typeBuilder</code> equals null</li>
1709 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1710 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1711 final List<String> listKeys) {
1712 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1713 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1715 if (schemaNode instanceof LeafSchemaNode) {
1716 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1717 final String leafName = leaf.getQName().getLocalName();
1718 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1719 if (listKeys.contains(leafName)) {
1721 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1723 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1726 } else if (!schemaNode.isAddedByUses()) {
1727 if (schemaNode instanceof LeafListSchemaNode) {
1728 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1729 } else if (schemaNode instanceof ContainerSchemaNode) {
1730 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1731 (ContainerSchemaNode) schemaNode);
1732 } else if (schemaNode instanceof ChoiceSchemaNode) {
1733 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1734 } else if (schemaNode instanceof ListSchemaNode) {
1735 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1740 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1741 final GeneratedTOBuilder genTOBuilder) {
1742 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1744 if (genTOBuilder != null) {
1745 final GeneratedTransferObject genTO = genTOBuilder.build();
1746 // Add Identifiable.getKey() for items
1747 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1748 .addAnnotation(OVERRIDE_ANNOTATION);
1749 context.addGeneratedTOBuilder(genTOBuilder);
1754 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1756 * @param list of string with names of the list keys
1757 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1758 * an empty list is returned.
1760 private static List<String> listKeys(final ListSchemaNode list) {
1761 final List<String> listKeys = new ArrayList<>();
1763 final List<QName> keyDefinition = list.getKeyDefinition();
1764 if (keyDefinition != null) {
1765 for (final QName keyDef : keyDefinition) {
1766 listKeys.add(keyDef.getLocalName());
1773 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1775 * @param packageName string with package name to which the list belongs
1776 * @param list list schema node which is source of data about the list name
1777 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1778 * null or list of key definitions is null or empty.
1780 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1781 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1782 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1783 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1784 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1790 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1791 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1792 * enclosing transfer objects.
1794 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1795 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1796 * @param leaf string with name for generated TO builder
1797 * @param parentModule parent module
1798 * @return generated TO builder for <code>typeDef</code>
1800 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1801 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1802 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1803 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1806 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1807 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1808 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1809 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1810 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1812 for (GeneratedTOBuilder builder : types) {
1813 if (builder.isUnion()) {
1814 final GeneratedTransferObject type = builder.build();
1815 createUnionBuilder(builder, typeBuilder, type, parentModule);
1819 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1823 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1824 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1825 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1828 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1829 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1830 * @param leaf string with name for generated TO builder
1831 * @param parentModule parent module
1832 * @return generated TO builder for <code>typeDef</code>
1834 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1835 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1836 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1837 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1838 typeDef, parentModule.getName());
1839 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1840 return genTOBuilder;
1845 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1846 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1847 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1848 * to <code>builder</code>
1850 * @param dataNodeContainer element which contains the list of used YANG groupings
1851 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1852 * @return generated type builder with all implemented types
1854 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1855 final GeneratedTypeBuilder builder) {
1856 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1857 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1858 if (genType == null) {
1859 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1860 + builder.getName());
1863 builder.addImplementsType(genType);
1868 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1869 for (final ModuleContext ctx : genCtx.values()) {
1870 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1871 if (result != null) {
1878 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1879 for (final ModuleContext ctx : genCtx.values()) {
1880 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1881 if (result != null) {
1888 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1889 for (final ModuleContext ctx : genCtx.values()) {
1890 final GeneratedTypeBuilder result = ctx.getCase(path);
1891 if (result != null) {
1898 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1899 if (status == Status.DEPRECATED) {
1900 builder.addAnnotation(DEPRECATED_ANNOTATION);