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 java.util.AbstractMap.SimpleImmutableEntry;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Optional;
55 import org.eclipse.jdt.annotation.Nullable;
56 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
57 import org.opendaylight.mdsal.binding.model.api.Constant;
58 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
60 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
61 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
62 import org.opendaylight.mdsal.binding.model.api.Restrictions;
63 import org.opendaylight.mdsal.binding.model.api.Type;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
73 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
74 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
75 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
76 import org.opendaylight.mdsal.binding.model.util.Types;
77 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
78 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
79 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
80 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
81 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.common.QNameModule;
84 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
85 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
94 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
95 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
101 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
102 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
103 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
104 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
106 import org.opendaylight.yangtools.yang.model.api.Status;
107 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
108 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.UsesNode;
110 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
111 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
113 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
114 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
115 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
116 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
117 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
121 abstract class AbstractTypeGenerator {
122 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
123 private static final Splitter COLON_SPLITTER = Splitter.on(':');
124 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
125 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
126 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
129 * Comparator based on augment target path.
131 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
132 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
133 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
135 while (thisIt.hasNext()) {
136 if (!otherIt.hasNext()) {
140 final int comp = thisIt.next().compareTo(otherIt.next());
146 return otherIt.hasNext() ? -1 : 0;
150 * Constant with the concrete name of identifier.
152 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
155 * Constant with the concrete name of namespace.
157 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
159 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
162 * Outer key represents the package name. Outer value represents map of all
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder 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
176 * when creating augmentation builder
178 private final SchemaContext schemaContext;
180 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
181 this.schemaContext = requireNonNull(context);
182 this.typeProvider = requireNonNull(typeProvider);
184 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
185 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
186 for (final Module contextModule : contextModules) {
187 contexts.add(moduleToGenTypes(contextModule));
190 contexts.forEach(this::allAugmentsToGenTypes);
193 final Collection<ModuleContext> moduleContexts() {
194 return genCtx.values();
197 final ModuleContext moduleContext(final QNameModule module) {
198 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
201 final AbstractTypeProvider typeProvider() {
205 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
207 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
209 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
210 Set<? extends SchemaNode> nodes);
212 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
214 private ModuleContext moduleToGenTypes(final Module module) {
215 final ModuleContext context = new ModuleContext(module);
216 genCtx.put(module.getQNameModule(), context);
217 allTypeDefinitionsToGenTypes(context);
218 groupingsToGenTypes(context, module.getGroupings());
219 rpcMethodsToGenType(context);
220 allIdentitiesToGenTypes(context);
221 notificationsToGenType(context);
223 if (!module.getChildNodes().isEmpty()) {
224 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
225 context.addModuleNode(moduleType);
226 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
232 * Converts all extended type definitions of module to the list of
233 * <code>Type</code> objects.
236 * module from which is obtained set of type definitions
237 * @throws IllegalArgumentException
239 * <li>if module is null</li>
240 * <li>if name of module is null</li>
242 * @throws IllegalStateException
243 * if set of type definitions from module is null
245 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
246 final Module module = context.module();
247 checkArgument(module.getName() != null, "Module name cannot be NULL.");
248 final DataNodeIterator it = new DataNodeIterator(module);
249 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
250 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
252 for (final TypeDefinition<?> typedef : typeDefinitions) {
253 if (typedef != null) {
254 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
256 context.addTypedefType(typedef.getPath(), type);
257 context.addTypeToSchema(type,typedef);
263 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
264 final DataSchemaNode node) {
265 if (node.isAugmenting() || node.isAddedByUses()) {
268 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
269 annotateDeprecatedIfNecessary(node.getStatus(), genType);
271 final Module module = context.module();
272 genType.setModuleName(module.getName());
273 addCodegenInformation(genType, module, node);
274 genType.setSchemaPath(node.getPath());
275 if (node instanceof DataNodeContainer) {
276 context.addChildNodeType(node, genType);
277 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
278 processUsesAugments((DataNodeContainer) node, context);
283 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
284 final Type baseInterface, final ContainerSchemaNode node) {
285 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
286 if (genType != null) {
287 constructGetter(parent, genType, node);
288 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
289 actionsToGenType(context, genType, node, null);
293 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
294 final Type baseInterface, final ListSchemaNode node) {
295 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
296 if (genType != null) {
297 constructGetter(parent, listTypeFor(genType), node);
299 final List<String> listKeys = listKeys(node);
300 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
301 if (genTOBuilder != null) {
302 final Type identifierMarker = identifier(genType);
303 final Type identifiableMarker = identifiable(genTOBuilder);
304 genTOBuilder.addImplementsType(identifierMarker);
305 genType.addImplementsType(identifiableMarker);
308 actionsToGenType(context, genType, node, genTOBuilder);
310 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
311 if (!schemaNode.isAugmenting()) {
312 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
317 if (genTOBuilder != null) {
318 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
319 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
320 genTOBuilder.setSUID(prop);
323 typeBuildersToGenTypes(context, genType, genTOBuilder);
327 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
328 for (final UsesNode usesNode : node.getUses()) {
329 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
330 usesAugmentationToGenTypes(context, augment, usesNode, node);
331 processUsesAugments(augment, context);
337 * Converts all <b>augmentation</b> of the module to the list
338 * <code>Type</code> objects.
341 * module from which is obtained list of all augmentation objects
342 * to iterate over them
343 * @throws IllegalArgumentException
345 * <li>if the module is null</li>
346 * <li>if the name of module is null</li>
348 * @throws IllegalStateException
349 * if set of augmentations from module is null
351 private void allAugmentsToGenTypes(final ModuleContext context) {
352 final Module module = context.module();
353 checkArgument(module != null, "Module reference cannot be NULL.");
354 checkArgument(module.getName() != null, "Module name cannot be NULL.");
355 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
357 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
358 augmentationToGenTypes(context, augment);
363 * Returns list of <code>AugmentationSchema</code> objects. The objects are
364 * sorted according to the length of their target path from the shortest to
368 * module from which is obtained list of all augmentation objects
369 * @return list of sorted <code>AugmentationSchema</code> objects obtained
370 * from <code>module</code>
371 * @throws IllegalArgumentException
373 * @throws IllegalStateException
374 * if set of module augmentations is null
376 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
377 checkArgument(module != null, "Module reference cannot be NULL.");
378 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
380 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
381 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
382 sortedAugmentations.sort(AUGMENT_COMP);
384 return sortedAugmentations;
388 * Create GeneratedTypeBuilder object from module argument.
391 * Module object from which builder will be created
392 * @return <code>GeneratedTypeBuilder</code> which is internal
393 * representation of the module
394 * @throws IllegalArgumentException
397 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
398 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
399 final Module module = context.module();
400 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
401 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
403 addCodegenInformation(moduleDataTypeBuilder, module);
404 return moduleDataTypeBuilder;
407 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
408 final Type parent, final T parentSchema, final Type keyType) {
409 for (final ActionDefinition action : parentSchema.getActions()) {
410 final GeneratedType input;
411 final GeneratedType output;
412 if (action.isAddedByUses()) {
413 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
414 input = context.getChildNode(orig.getInput().getPath()).build();
415 output = context.getChildNode(orig.getOutput().getPath()).build();
417 input = actionContainer(context, RPC_INPUT, action.getInput());
418 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
421 if (!(parentSchema instanceof GroupingDefinition)) {
422 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
423 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
424 // and do not capture an actual instantiation.
425 final QName qname = action.getQName();
426 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
427 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
428 BindingMapping.getClassName(qname)));
429 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
430 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
432 annotateDeprecatedIfNecessary(action.getStatus(), builder);
433 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
434 : action(parent, input, output));
436 addCodegenInformation(builder, context.module(), action);
437 context.addChildNodeType(action, builder);
442 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
443 for (UsesNode uses : parent.getUses()) {
444 final GroupingDefinition grp = findUsedGrouping(uses);
445 final Optional<ActionDefinition> found = grp.getActions().stream()
446 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
447 if (found.isPresent()) {
448 final ActionDefinition result = found.get();
449 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
453 return Optional.empty();
456 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
457 final ContainerSchemaNode schema) {
458 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
459 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
460 return genType.build();
464 * Converts all <b>RPCs</b> input and output substatements of the module
465 * to the list of <code>Type</code> objects. In addition are to containers
466 * and lists which belong to input or output also part of returning list.
469 * module from which is obtained set of all rpc objects to
471 * @throws IllegalArgumentException
473 * <li>if the module is null</li>
474 * <li>if the name of module is null</li>
476 * @throws IllegalStateException
477 * if set of rpcs from module is null
479 private void rpcMethodsToGenType(final ModuleContext context) {
480 final Module module = context.module();
481 checkArgument(module.getName() != null, "Module name cannot be NULL.");
482 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
483 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
484 if (rpcDefinitions.isEmpty()) {
488 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
489 interfaceBuilder.addImplementsType(RPC_SERVICE);
491 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
493 for (final RpcDefinition rpc : rpcDefinitions) {
495 final String rpcName = BindingMapping.getClassName(rpc.getQName());
496 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
497 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
499 // Do not refer to annotation class, as it may not be available at runtime
500 method.addAnnotation("javax.annotation", "CheckReturnValue");
501 addComment(method, rpc);
503 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
504 method.setReturnType(listenableFutureTypeFor(
505 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
509 context.addTopLevelNodeType(interfaceBuilder);
512 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
513 final ContainerSchemaNode schema, final Type type) {
514 processUsesAugments(schema, context);
515 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
516 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
518 addImplementedInterfaceFromUses(schema, outType);
519 outType.addImplementsType(type);
520 outType.addImplementsType(augmentable(outType));
521 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
522 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
523 context.addChildNodeType(schema, outType);
524 return outType.build();
528 * Converts all <b>notifications</b> of the module to the list of
529 * <code>Type</code> objects. In addition are to this list added containers
530 * and lists which are part of this notification.
533 * module from which is obtained set of all notification objects
534 * to iterate over them
535 * @throws IllegalArgumentException
537 * <li>if the module equals null</li>
538 * <li>if the name of module equals null</li>
540 * @throws IllegalStateException
541 * if set of notifications from module is null
543 private void notificationsToGenType(final ModuleContext context) {
544 final Module module = context.module();
545 checkArgument(module.getName() != null, "Module name cannot be NULL.");
546 final Set<NotificationDefinition> notifications = module.getNotifications();
547 if (notifications.isEmpty()) {
551 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
552 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
554 for (final NotificationDefinition notification : notifications) {
555 if (notification != null) {
556 processUsesAugments(notification, context);
558 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
559 context.modulePackageName(), notification, DATA_OBJECT, context);
560 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
561 notificationInterface.addImplementsType(NOTIFICATION);
562 context.addChildNodeType(notification, notificationInterface);
564 // Notification object
565 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
566 notification.getChildNodes());
568 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
569 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
570 .setReturnType(Types.primitiveVoidType()), notification);
574 addCodegenInformation(listenerInterface, module, "notifications", notifications);
575 context.addTopLevelNodeType(listenerInterface);
579 * Converts all <b>identities</b> of the module to the list of
580 * <code>Type</code> objects.
583 * module from which is obtained set of all identity objects to
585 * @param schemaContext
586 * schema context only used as input parameter for method
587 * {@link BindingGeneratorImpl#identityToGenType}
590 private void allIdentitiesToGenTypes(final ModuleContext context) {
591 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
593 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
594 for (final IdentitySchemaNode identity : schemaIdentities) {
595 identityToGenType(context, identity);
601 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
602 * created transport object builder. If identity contains base identity then
603 * reference to base identity is added to superior identity as its extend.
604 * If identity doesn't contain base identity then only reference to abstract
605 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
606 * BaseIdentity} is added
610 * @param basePackageName
611 * string contains the module package name
613 * IdentitySchemaNode which contains data about identity
615 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
616 if (identity == null) {
619 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
620 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
621 BindingMapping.getClassName(identity.getQName())));
622 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
623 if (!baseIdentities.isEmpty()) {
624 for (IdentitySchemaNode baseIdentity : baseIdentities) {
625 final QName qname = baseIdentity.getQName();
626 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
627 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
628 newType.addImplementsType(gto);
631 newType.addImplementsType(BASE_IDENTITY);
634 final Module module = context.module();
635 addCodegenInformation(newType, module, identity);
636 newType.setModuleName(module.getName());
637 newType.setSchemaPath(identity.getPath());
639 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
640 identity.getQName().getLocalName());
642 context.addIdentityType(identity.getQName(), newType);
645 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
646 final JavaTypeName yangModuleInfo, final String localName) {
647 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
648 new SimpleImmutableEntry<>(yangModuleInfo, localName));
652 * Converts all <b>groupings</b> of the module to the list of
653 * <code>Type</code> objects. Firstly are groupings sorted according mutual
654 * dependencies. At least dependent (independent) groupings are in the list
655 * saved at first positions. For every grouping the record is added to map
656 * {@link ModuleContext#groupings allGroupings}
661 * collection of groupings from which types will be generated
664 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
665 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
666 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
667 // node of grouping is resolved to the method.
668 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
669 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
670 context.addGroupingType(grouping.getPath(), genType);
671 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
672 groupingsToGenTypes(context, grouping.getGroupings());
673 processUsesAugments(grouping, context);
674 actionsToGenType(context, genType, grouping, null);
679 * Adds enumeration builder created from <code>enumTypeDef</code> to
680 * <code>typeBuilder</code>.
682 * Each <code>enumTypeDef</code> item is added to builder with its name and
686 * EnumTypeDefinition contains enum data
688 * string contains name which will be assigned to enumeration
691 * GeneratedTypeBuilder to which will be enum builder assigned
693 * Module in which type should be generated
694 * @return enumeration builder which contains data from
695 * <code>enumTypeDef</code>
697 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
698 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
699 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
700 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
701 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
702 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
703 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
710 * Generates type builder for <code>module</code>.
713 * Module which is source of package name for generated type
716 * string which is added to the module class name representation
718 * @return instance of GeneratedTypeBuilder which represents
719 * <code>module</code>.
720 * @throws IllegalArgumentException
721 * if <code>module</code> is null
723 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
724 final Module module = context.module();
725 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
726 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
727 JavaTypeName.create(context.modulePackageName(), moduleName));
729 moduleBuilder.setModuleName(moduleName);
730 addCodegenInformation(moduleBuilder, module);
731 return moduleBuilder;
735 * Converts <code>augSchema</code> to list of <code>Type</code> which
736 * contains generated type for augmentation. In addition there are also
737 * generated types for all containers, list and choices which are child of
738 * <code>augSchema</code> node or a generated types for cases are added if
739 * augmented node is choice.
741 * @param augmentPackageName
742 * string with the name of the package to which the augmentation
745 * AugmentationSchema which is contains data about augmentation
746 * (target path, childs...)
749 * @throws IllegalArgumentException
751 * <li>if <code>augmentPackageName</code> equals null</li>
752 * <li>if <code>augSchema</code> equals null</li>
754 * @throws IllegalStateException
755 * if augment target path is null
757 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
758 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
759 checkState(augSchema.getTargetPath() != null,
760 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
762 processUsesAugments(augSchema, context);
763 final SchemaPath targetPath = augSchema.getTargetPath();
764 SchemaNode targetSchemaNode = null;
766 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
767 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
768 if (targetSchemaNode instanceof DerivableSchemaNode) {
769 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
771 if (targetSchemaNode == null) {
772 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
773 + " in module " + context.module().getName());
776 if (targetSchemaNode == null) {
777 throw new IllegalArgumentException("augment target not found: " + targetPath);
780 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
781 if (targetTypeBuilder == null) {
782 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
784 if (targetTypeBuilder == null) {
785 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
788 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
789 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
790 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
793 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
794 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
798 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
799 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
800 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
801 checkState(augSchema.getTargetPath() != null,
802 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
804 processUsesAugments(augSchema, context);
805 final SchemaPath targetPath = augSchema.getTargetPath();
806 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
807 if (targetSchemaNode == null) {
808 throw new IllegalArgumentException("augment target not found: " + targetPath);
811 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
812 if (targetTypeBuilder == null) {
813 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
815 if (targetTypeBuilder == null) {
816 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
819 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
820 if (usesNodeParent instanceof SchemaNode) {
821 addRawAugmentGenTypeDefinition(context,
822 packageNameForAugmentedGeneratedType(context.modulePackageName(),
823 ((SchemaNode) usesNodeParent).getPath()),
824 targetTypeBuilder.build(), augSchema);
826 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
829 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
830 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
834 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
835 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
837 if (targetGrouping instanceof GroupingDefinition) {
838 return (GroupingDefinition) targetGrouping;
841 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
845 * Convenient method to find node added by uses statement.
849 * @param parentUsesNode
850 * parent of uses node
851 * @return node from its original location in grouping
853 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
854 SchemaNode result = findUsedGrouping(parentUsesNode);
855 for (final QName node : targetPath.getPathFromRoot()) {
856 if (result instanceof DataNodeContainer) {
857 final QName resultNode = node.withModule(result.getQName().getModule());
858 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
859 } else if (result instanceof ChoiceSchemaNode) {
860 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
863 if (result == null) {
867 if (result instanceof DerivableSchemaNode) {
868 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
869 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
870 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
871 result = originalNode.get();
875 if (result instanceof DataSchemaNode) {
876 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
877 if (resultDataSchemaNode.isAddedByUses()) {
878 // The original node is required, but we have only the copy of
879 // the original node.
880 // Maybe this indicates a bug in Yang parser.
881 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
884 return resultDataSchemaNode;
887 throw new IllegalStateException(
888 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
893 * Returns a generated type builder for an augmentation.
895 * The name of the type builder is equal to the name of augmented node with
896 * serial number as suffix.
900 * @param augmentPackageName
901 * string with contains the package name to which the augment
903 * @param basePackageName
904 * string with the package name to which the augmented node
906 * @param targetTypeRef
909 * augmentation schema which contains data about the child nodes
910 * and uses of augment
911 * @return generated type builder for augment
913 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
914 final String augmentPackageName, final Type targetTypeRef,
915 final AugmentationSchemaNode augSchema) {
916 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
917 if (augmentBuilders == null) {
918 augmentBuilders = new HashMap<>();
919 genTypeBuilders.put(augmentPackageName, augmentBuilders);
921 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
924 if (augIdentifier != null) {
925 augTypeName = BindingMapping.getClassName(augIdentifier);
927 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
930 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
931 JavaTypeName.create(augmentPackageName, augTypeName));
933 augTypeBuilder.addImplementsType(DATA_OBJECT);
934 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
935 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
936 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
938 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
939 augmentBuilders.put(augTypeName, augTypeBuilder);
941 if (!augSchema.getChildNodes().isEmpty()) {
942 context.addTypeToAugmentation(augTypeBuilder, augSchema);
945 context.addAugmentType(augTypeBuilder);
946 return augTypeBuilder;
949 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
950 final AugmentationSchemaNode augSchema) {
951 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
956 * @param unknownSchemaNodes
957 * @return nodeParameter of UnknownSchemaNode
959 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
960 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
961 final QName nodeType = unknownSchemaNode.getNodeType();
962 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
963 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
964 return unknownSchemaNode.getNodeParameter();
971 * Returns first unique name for the augment generated type builder. The
972 * generated type builder name for augment consists from name of augmented
973 * node and serial number of its augmentation.
976 * map of builders which were created in the package to which the
977 * augmentation belongs
979 * string with name of augmented node
980 * @return string with unique name for augmentation builder
982 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
984 if (builders != null) {
985 while (builders.containsKey(genTypeName + index)) {
989 return genTypeName + index;
993 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
994 * node for which <code>typeBuilder</code> was created.
996 * The subnodes aren't mapped to the methods if they are part of grouping or
997 * augment (in this case are already part of them).
1002 * generated type builder which represents any node. The subnodes
1003 * of this node are added to the <code>typeBuilder</code> as
1004 * methods. The subnode can be of type leaf, leaf-list, list,
1005 * container, choice.
1008 * @param schemaNodes
1009 * set of data schema nodes which are the children of the node
1010 * for which <code>typeBuilder</code> was created
1011 * @return generated type builder which is the same builder as input
1012 * parameter. The getter methods (representing child nodes) could be
1015 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1016 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1017 if (schemaNodes != null && parent != null) {
1018 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1019 for (final DataSchemaNode schemaNode : schemaNodes) {
1020 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1021 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1029 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1030 * node for which <code>typeBuilder</code> was created.
1034 * @param typeBuilder
1035 * generated type builder which represents any node. The subnodes
1036 * of this node are added to the <code>typeBuilder</code> as
1037 * methods. The subnode can be of type leaf, leaf-list, list,
1038 * container, choice.
1041 * @param schemaNodes
1042 * set of data schema nodes which are the children of the node
1043 * for which <code>typeBuilder</code> was created
1044 * @return generated type builder which is the same object as the input
1045 * parameter <code>typeBuilder</code>. The getter method could be
1048 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1049 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1050 if (schemaNodes != null && typeBuilder != null) {
1051 final Type baseInterface = childOf(typeBuilder);
1052 for (final DataSchemaNode schemaNode : schemaNodes) {
1053 if (!schemaNode.isAugmenting()) {
1054 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1062 * Adds to <code>typeBuilder</code> a method which is derived from
1063 * <code>schemaNode</code>.
1066 * data schema node which is added to <code>typeBuilder</code> as
1068 * @param typeBuilder
1069 * generated type builder to which is <code>schemaNode</code>
1070 * added as a method.
1076 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1077 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1078 if (node != null && typeBuilder != null) {
1079 if (node instanceof LeafSchemaNode) {
1080 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1081 } else if (node instanceof LeafListSchemaNode) {
1082 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1083 } else if (node instanceof ContainerSchemaNode) {
1084 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1085 } else if (node instanceof ListSchemaNode) {
1086 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1087 } else if (node instanceof ChoiceSchemaNode) {
1088 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1090 // TODO: anyxml not yet supported
1091 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1092 typeBuilder.getFullyQualifiedName());
1098 * Converts <code>choiceNode</code> to the list of generated types for
1099 * choice and its cases.
1101 * The package names for choice and for its cases are created as
1102 * concatenation of the module package (<code>basePackageName</code>) and
1103 * names of all parents node.
1107 * @param basePackageName
1108 * string with the module package name
1112 * choice node which is mapped to generated type. Also child
1113 * nodes - cases are mapped to generated types.
1114 * @throws IllegalArgumentException
1116 * <li>if <code>basePackageName</code> is null</li>
1117 * <li>if <code>choiceNode</code> is null</li>
1120 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1121 final ChoiceSchemaNode choiceNode) {
1122 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1124 if (!choiceNode.isAddedByUses()) {
1125 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1126 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1127 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1128 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1129 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1130 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1132 final GeneratedType choiceType = choiceTypeBuilder.build();
1133 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1135 constructGetter(parent, choiceType, choiceNode);
1140 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1142 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1143 * The package names for the builder is created as concatenation of the module package and names of all parents
1144 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1145 * and <i>choice</i> type
1148 * current module context
1149 * @param refChoiceType
1150 * type which represents superior <i>case</i>
1152 * choice case node which is mapped to generated type
1153 * @throws IllegalArgumentException
1155 * <li>if <code>refChoiceType</code> equals null</li>
1156 * <li>if <code>caseNodes</code> equals null</li>
1159 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1160 final ChoiceSchemaNode choiceNode) {
1161 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1162 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1164 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1165 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1166 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1167 caseTypeBuilder.addImplementsType(refChoiceType);
1168 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1169 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1170 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1171 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1172 if (caseChildNodes != null) {
1173 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1175 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1176 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1178 if (parent instanceof AugmentationSchemaNode) {
1179 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1180 final SchemaPath targetPath = augSchema.getTargetPath();
1181 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1182 if (targetSchemaNode instanceof DataSchemaNode
1183 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1184 if (targetSchemaNode instanceof DerivableSchemaNode) {
1185 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1188 if (targetSchemaNode == null) {
1189 throw new IllegalStateException(
1190 "Failed to find target node from grouping for augmentation " + augSchema
1191 + " in module " + context.module().getName());
1194 parent = targetSchemaNode;
1197 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1198 Type childOfType = findChildNodeByPath(parent.getPath());
1199 if (childOfType == null) {
1200 childOfType = findGroupingByPath(parent.getPath());
1202 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1204 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1208 processUsesAugments(caseNode, context);
1213 * Generates list of generated types for all the cases of a choice which are
1214 * added to the choice through the augment.
1218 * @param basePackageName
1219 * string contains name of package to which augment belongs. If
1220 * an augmented choice is from an other package (pcg1) than an
1221 * augmenting choice (pcg2) then case's of the augmenting choice
1222 * will belong to pcg2.
1224 * Type which represents target choice
1226 * node which represents target choice
1227 * @param augmentedNodes
1228 * set of choice case nodes for which is checked if are/aren't
1229 * added to choice through augmentation
1230 * @throws IllegalArgumentException
1232 * <li>if <code>basePackageName</code> is null</li>
1233 * <li>if <code>targetType</code> is null</li>
1234 * <li>if <code>augmentedNodes</code> is null</li>
1237 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1238 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1239 final DataNodeContainer usesNodeParent) {
1240 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1241 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1243 for (final DataSchemaNode caseNode : augmentedNodes) {
1244 if (caseNode != null) {
1245 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1246 caseTypeBuilder.addImplementsType(targetType);
1248 CaseSchemaNode node = null;
1249 final String caseLocalName = caseNode.getQName().getLocalName();
1250 if (caseNode instanceof CaseSchemaNode) {
1251 node = (CaseSchemaNode) caseNode;
1252 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1253 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1254 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1255 if (dataSchemaNode instanceof ChoiceSchemaNode
1256 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1257 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1262 node = findNamedCase(targetNode, caseLocalName);
1264 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1265 if (childNodes != null) {
1266 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1268 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1269 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1274 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1275 final SchemaPath nodePath = targetNode.getPath();
1276 final SchemaPath parentSp = nodePath.getParent();
1277 if (parentSp.getParent() == null) {
1278 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1281 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1282 GeneratedTypeBuilder childOfType = null;
1283 if (parent instanceof CaseSchemaNode) {
1284 childOfType = findCaseByPath(parent.getPath());
1285 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1286 childOfType = findChildNodeByPath(parent.getPath());
1287 } else if (parent instanceof GroupingDefinition) {
1288 childOfType = findGroupingByPath(parent.getPath());
1291 if (childOfType == null) {
1292 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1298 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1299 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1300 return cases.isEmpty() ? null : cases.get(0);
1303 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1304 // New parser with encapsulated type
1305 if (leaf.getPath().equals(type.getPath())) {
1309 // Embedded type definition with new parser. Also takes care of the old parser with bits
1310 if (leaf.getPath().equals(type.getPath().getParent())) {
1317 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1318 final List<PatternConstraint> patternConstraints) {
1319 if (!patternConstraints.isEmpty()) {
1320 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1321 .append(BindingMapping.getPropertyName(leafName));
1322 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1323 typeProvider.resolveRegExpressions(patternConstraints));
1328 * Converts <code>leaf</code> to the getter method which is added to
1329 * <code>typeBuilder</code>.
1331 * @param typeBuilder
1332 * generated type builder to which is added getter method as
1333 * <code>leaf</code> mapping
1335 * leaf schema node which is mapped as getter method which is
1336 * added to <code>typeBuilder</code>
1338 * Module in which type was defined
1339 * @return boolean value
1341 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1343 * <li>true - in other cases</li>
1346 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1347 final ModuleContext context) {
1348 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1352 final Module parentModule = findParentModule(schemaContext, leaf);
1353 Type returnType = null;
1355 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1356 if (isInnerType(leaf, typeDef)) {
1357 if (typeDef instanceof EnumTypeDefinition) {
1358 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1359 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1360 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1361 typeBuilder, context);
1362 if (enumBuilder != null) {
1363 returnType = enumBuilder.toInstance(typeBuilder);
1365 typeProvider.putReferencedType(leaf.getPath(), returnType);
1366 } else if (typeDef instanceof UnionTypeDefinition) {
1367 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1369 if (genTOBuilder != null) {
1370 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1371 // Store the inner type within the union so that we can find the reference for it
1372 context.addInnerTypedefType(typeDef.getPath(), returnType);
1374 } else if (typeDef instanceof BitsTypeDefinition) {
1375 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1377 if (genTOBuilder != null) {
1378 returnType = genTOBuilder.build();
1381 // It is constrained version of already declared type (inner declared type exists,
1382 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1383 // In order to get proper class we need to look up closest derived type
1384 // and apply restrictions from leaf type
1385 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1386 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1388 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1391 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1392 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1393 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1396 if (returnType == null) {
1400 if (typeDef instanceof EnumTypeDefinition) {
1401 typeProvider.putReferencedType(leaf.getPath(), returnType);
1404 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1405 processContextRefExtension(leaf, getter, parentModule);
1409 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1410 // Returns DerivedType in case of new parser.
1411 final TypeDefinition<?> baseType = typeDef.getBaseType();
1412 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1415 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1416 final Module module) {
1417 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1418 final QName nodeType = node.getNodeType();
1419 if ("context-reference".equals(nodeType.getLocalName())) {
1420 final String nodeParam = node.getNodeParameter();
1421 IdentitySchemaNode identity = null;
1422 String basePackageName = null;
1423 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1424 final Iterator<String> iterator = splittedElement.iterator();
1425 final int length = Iterables.size(splittedElement);
1427 identity = findIdentityByName(module.getIdentities(), iterator.next());
1428 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1429 } else if (length == 2) {
1430 final String prefix = iterator.next();
1431 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1432 if (dependentModule == null) {
1433 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1436 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1437 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1439 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1442 if (identity == null) {
1443 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1447 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1448 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1449 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1450 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1455 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1456 for (final IdentitySchemaNode id : identities) {
1457 if (id.getQName().getLocalName().equals(name)) {
1464 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1465 for (final ModuleImport imp : imports) {
1466 if (imp.getPrefix().equals(prefix)) {
1467 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1473 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1474 final boolean isReadOnly) {
1475 if (leaf != null && toBuilder != null) {
1477 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1478 if (typeDef instanceof UnionTypeDefinition) {
1479 // GeneratedType for this type definition should have be already created
1480 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1481 returnType = mc.getTypedefs().get(typeDef.getPath());
1482 if (returnType == null) {
1483 // This may still be an inner type, try to find it
1484 returnType = mc.getInnerType(typeDef.getPath());
1486 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1487 // Annonymous enumeration (already generated, since it is inherited via uses).
1488 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1489 QName qname = originalLeaf.getQName();
1490 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1492 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1494 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1500 * Converts <code>leaf</code> schema node to property of generated TO
1504 * generated TO builder to which is <code>leaf</code> added as
1507 * leaf schema node which is added to <code>toBuilder</code> as
1512 * boolean value which says if leaf property is|isn't read only
1513 * @return boolean value
1515 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1516 * name equals null or if leaf is added by <i>uses</i>.</li>
1517 * <li>true - other cases</li>
1520 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1521 final Type returnType, final boolean isReadOnly) {
1522 if (returnType == null) {
1525 final String leafName = leaf.getQName().getLocalName();
1526 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1527 propBuilder.setReadOnly(isReadOnly);
1528 propBuilder.setReturnType(returnType);
1529 addComment(propBuilder, leaf);
1531 toBuilder.addEqualsIdentity(propBuilder);
1532 toBuilder.addHashIdentity(propBuilder);
1533 toBuilder.addToStringProperty(propBuilder);
1538 * Converts <code>node</code> leaf list schema node to getter method of
1539 * <code>typeBuilder</code>.
1541 * @param typeBuilder
1542 * generated type builder to which is <code>node</code> added as
1545 * leaf list schema node which is added to
1546 * <code>typeBuilder</code> as getter method
1547 * @param module module
1548 * @return boolean value
1550 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1551 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1552 * <li>false - other cases</li>
1555 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1556 final ModuleContext context) {
1557 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1561 final QName nodeName = node.getQName();
1563 final TypeDefinition<?> typeDef = node.getType();
1564 final Module parentModule = findParentModule(schemaContext, node);
1566 Type returnType = null;
1567 if (typeDef.getBaseType() == null) {
1568 if (typeDef instanceof EnumTypeDefinition) {
1569 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1570 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1571 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1572 typeBuilder, context);
1573 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1574 typeProvider.putReferencedType(node.getPath(), returnType);
1575 } else if (typeDef instanceof UnionTypeDefinition) {
1576 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1577 node, parentModule);
1578 if (genTOBuilder != null) {
1579 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1581 } else if (typeDef instanceof BitsTypeDefinition) {
1582 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1583 node, parentModule);
1584 returnType = genTOBuilder.build();
1586 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1587 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1588 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1591 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1592 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1593 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1596 final ParameterizedType listType = listTypeFor(returnType);
1597 constructGetter(typeBuilder, listType, node);
1601 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1602 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1603 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1605 addCodegenInformation(returnType, parentModule, typeDef);
1606 returnType.setSchemaPath(typeDef.getPath());
1607 returnType.setModuleName(parentModule.getName());
1609 genTOBuilder.setTypedef(true);
1610 genTOBuilder.setIsUnion(true);
1611 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1615 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1618 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1619 method.setReturnType(returnType);
1620 method.addParameter(Types.STRING, "defaultValue");
1621 method.setAccessModifier(AccessModifier.PUBLIC);
1622 method.setStatic(true);
1624 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1625 if (types == null) {
1626 typeProvider.getAdditionalTypes().put(parentModule,
1627 Sets.newHashSet(unionBuilder.build()));
1629 types.add(unionBuilder.build());
1631 return returnType.build();
1634 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1635 final GeneratedTypeBuilder typeBuilder) {
1636 // Append enclosing path hierarchy without dots
1637 final StringBuilder sb = new StringBuilder();
1638 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1639 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1640 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1641 unionBuilder.setIsUnionBuilder(true);
1642 return unionBuilder;
1645 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1646 final SchemaNode schemaNode) {
1647 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1650 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1651 final SchemaNode schemaNode, final Type baseInterface) {
1652 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1653 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1658 * Instantiates generated type builder with <code>packageName</code> and
1659 * <code>schemaNode</code>.
1661 * The new builder always implements
1662 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1663 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1664 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1666 * If <code>schemaNode</code> is instance of
1667 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1668 * DataNodeContainer} it can also implement nodes which are specified in
1671 * @param packageName
1672 * string with the name of the package to which
1673 * <code>schemaNode</code> belongs.
1675 * schema node for which is created generated type builder
1677 * parent type (can be null)
1678 * @return generated type builder <code>schemaNode</code>
1680 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1681 final Type baseInterface, final ModuleContext context) {
1682 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1683 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1685 it.addImplementsType(baseInterface);
1686 if (!(schemaNode instanceof GroupingDefinition)) {
1687 it.addImplementsType(augmentable(it));
1689 if (schemaNode instanceof DataNodeContainer) {
1690 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1691 groupingsToGenTypes(context, containerSchema.getGroupings());
1692 addImplementedInterfaceFromUses(containerSchema, it);
1699 * Wraps the calling of the same overloaded method.
1701 * @param packageName
1702 * string with the package name to which returning generated type
1705 * schema node which provide data about the schema node name
1706 * @return generated type builder for <code>schemaNode</code>
1708 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1709 final String prefix) {
1710 return addRawInterfaceDefinition(
1711 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1712 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1716 * Returns reference to generated type builder for specified
1717 * <code>schemaNode</code> with <code>packageName</code>.
1719 * Firstly the generated type builder is searched in
1720 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1721 * found it is created and added to <code>genTypeBuilders</code>.
1723 * @param packageName
1724 * string with the package name to which returning generated type
1727 * schema node which provide data about the schema node name
1729 * return type name prefix
1730 * @return generated type builder for <code>schemaNode</code>
1731 * @throws IllegalArgumentException
1733 * <li>if <code>schemaNode</code> is null</li>
1734 * <li>if <code>packageName</code> is null</li>
1735 * <li>if QName of schema node is null</li>
1736 * <li>if schemaNode name is null</li>
1740 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1741 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1742 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1743 final String schemaNodeName = schemaNode.getQName().getLocalName();
1744 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1746 // FIXME: Validation of name conflict
1747 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1748 final Module module = findParentModule(schemaContext, schemaNode);
1749 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1750 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1752 addCodegenInformation(newType, module, schemaNode);
1753 newType.setSchemaPath(schemaNode.getPath());
1754 newType.setModuleName(module.getName());
1756 final String packageName = identifier.packageName();
1757 final String simpleName = identifier.simpleName();
1758 if (!genTypeBuilders.containsKey(packageName)) {
1759 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1760 builders.put(simpleName, newType);
1761 genTypeBuilders.put(packageName, builders);
1763 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1764 if (!builders.containsKey(simpleName)) {
1765 builders.put(simpleName, newType);
1772 * Creates the name of the getter method name from <code>localName</code>.
1775 * string with the name of the getter method
1778 * @return string with the name of the getter method for
1779 * <code>methodName</code> in JAVA method format
1781 public static String getterMethodName(final String localName, final Type returnType) {
1782 final StringBuilder method = new StringBuilder();
1783 if (BOOLEAN.equals(returnType)) {
1784 method.append("is");
1786 method.append("get");
1788 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1789 method.append(name);
1790 return method.toString();
1794 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1796 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1797 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1799 * @param interfaceBuilder generated type builder for which the getter method should be created
1800 * @param returnType type which represents the return type of the getter method
1801 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1802 * @param comment string with comment for the getter method
1803 * @param status status from yang file, for deprecated annotation
1804 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1806 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1807 final SchemaNode node) {
1808 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1809 getterMethodName(node.getQName().getLocalName(), returnType));
1810 getMethod.setReturnType(returnType);
1812 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1813 if (!returnType.getPackageName().isEmpty()) {
1814 // The return type has a package, so it's not a primitive type
1815 getMethod.addAnnotation("javax.annotation", "Nullable");
1817 addComment(getMethod, node);
1823 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1824 * or to <code>genTOBuilder</code> as property.
1826 * @param basePackageName
1827 * string contains the module package name
1829 * data schema node which should be added as getter method to
1830 * <code>typeBuilder</code> or as a property to
1831 * <code>genTOBuilder</code> if is part of the list key
1832 * @param typeBuilder
1833 * generated type builder for the list schema node
1834 * @param genTOBuilder
1835 * generated TO builder for the list keys
1837 * list of string which contains names of the list keys
1840 * @throws IllegalArgumentException
1842 * <li>if <code>schemaNode</code> equals null</li>
1843 * <li>if <code>typeBuilder</code> equals null</li>
1846 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1847 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1848 final List<String> listKeys) {
1849 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1850 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1852 if (schemaNode instanceof LeafSchemaNode) {
1853 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1854 final String leafName = leaf.getQName().getLocalName();
1855 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1856 if (listKeys.contains(leafName)) {
1858 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1860 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1863 } else if (!schemaNode.isAddedByUses()) {
1864 if (schemaNode instanceof LeafListSchemaNode) {
1865 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1866 } else if (schemaNode instanceof ContainerSchemaNode) {
1867 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1868 (ContainerSchemaNode) schemaNode);
1869 } else if (schemaNode instanceof ChoiceSchemaNode) {
1870 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1871 } else if (schemaNode instanceof ListSchemaNode) {
1872 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1877 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1878 final GeneratedTOBuilder genTOBuilder) {
1879 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1881 if (genTOBuilder != null) {
1882 final GeneratedTransferObject genTO = genTOBuilder.build();
1883 // Add Identifiable.getKey() for items
1884 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1885 .addAnnotation(OVERRIDE_ANNOTATION);
1886 context.addGeneratedTOBuilder(genTOBuilder);
1891 * Selects the names of the list keys from <code>list</code> and returns
1892 * them as the list of the strings
1895 * of string with names of the list keys
1896 * @return list of string which represents names of the list keys. If the
1897 * <code>list</code> contains no keys then the empty list is
1900 private static List<String> listKeys(final ListSchemaNode list) {
1901 final List<String> listKeys = new ArrayList<>();
1903 final List<QName> keyDefinition = list.getKeyDefinition();
1904 if (keyDefinition != null) {
1905 for (final QName keyDef : keyDefinition) {
1906 listKeys.add(keyDef.getLocalName());
1913 * Generates for the <code>list</code> which contains any list keys special
1914 * generated TO builder.
1916 * @param packageName
1917 * string with package name to which the list belongs
1919 * list schema node which is source of data about the list name
1920 * @return generated TO builder which represents the keys of the
1921 * <code>list</code> or null if <code>list</code> is null or list of
1922 * key definitions is null or empty.
1924 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1925 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1926 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1927 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1928 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1934 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1936 * If more then one generated TO builder is created for enclosing then all
1937 * of the generated TO builders are added to <code>typeBuilder</code> as
1938 * enclosing transfer objects.
1941 * type definition which can be of type <code>UnionType</code> or
1942 * <code>BitsTypeDefinition</code>
1943 * @param typeBuilder
1944 * generated type builder to which is added generated TO created
1945 * from <code>typeDef</code>
1947 * string with name for generated TO builder
1948 * @param parentModule
1950 * @return generated TO builder for <code>typeDef</code>
1952 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1953 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1954 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1955 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1958 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1959 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1960 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1961 for (final GeneratedTOBuilder genTOBuilder : types) {
1962 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1965 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1966 return resultTOBuilder;
1970 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1971 * also added to <code>typeBuilder</code> as enclosing transfer object.
1973 * If more then one generated TO builder is created for enclosing then all
1974 * of the generated TO builders are added to <code>typeBuilder</code> as
1975 * enclosing transfer objects.
1978 * type definition which can be of type <code>UnionType</code> or
1979 * <code>BitsTypeDefinition</code>
1980 * @param typeBuilder
1981 * generated type builder to which is added generated TO created
1982 * from <code>typeDef</code>
1984 * string with name for generated TO builder
1985 * @param parentModule
1987 * @return generated TO builder for <code>typeDef</code>
1989 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1990 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1991 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1992 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1993 typeDef, parentModule.getName());
1994 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1995 return genTOBuilder;
1999 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
2000 final List<GeneratedTOBuilder> genTOBuilders) {
2001 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2002 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2004 return genTOBuilders.get(0);
2008 * Adds the implemented types to type builder.
2010 * The method passes through the list of <i>uses</i> in
2011 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2012 * generated type from {@link ModuleContext#groupings
2013 * allGroupings} which is added as <i>implements type</i> to
2014 * <code>builder</code>
2016 * @param dataNodeContainer
2017 * element which contains the list of used YANG groupings
2019 * builder to which are added implemented types according to
2020 * <code>dataNodeContainer</code>
2021 * @return generated type builder with all implemented types
2023 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2024 final GeneratedTypeBuilder builder) {
2025 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2026 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2027 if (genType == null) {
2028 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2029 + builder.getName());
2032 builder.addImplementsType(genType);
2037 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2038 for (final ModuleContext ctx : genCtx.values()) {
2039 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2040 if (result != null) {
2047 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2048 for (final ModuleContext ctx : genCtx.values()) {
2049 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2050 if (result != null) {
2057 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2058 for (final ModuleContext ctx : genCtx.values()) {
2059 final GeneratedTypeBuilder result = ctx.getCase(path);
2060 if (result != null) {
2067 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2068 if (status == Status.DEPRECATED) {
2069 builder.addAnnotation(DEPRECATED_ANNOTATION);