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.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
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.DATA_OBJECT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
23 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
24 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
25 import static org.opendaylight.mdsal.binding.model.util.Types.VOID;
26 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
31 import com.google.common.base.Splitter;
32 import com.google.common.collect.Iterables;
33 import com.google.common.collect.Sets;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Comparator;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
41 import java.util.Optional;
43 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
44 import org.opendaylight.mdsal.binding.model.api.Constant;
45 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
46 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
47 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
48 import org.opendaylight.mdsal.binding.model.api.Restrictions;
49 import org.opendaylight.mdsal.binding.model.api.Type;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
53 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
54 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
55 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
58 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
59 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
60 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
61 import org.opendaylight.mdsal.binding.model.util.Types;
62 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.CodegenGeneratedTOBuilder;
63 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
64 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTypeBuilderImpl;
65 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
66 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
68 import org.opendaylight.yangtools.yang.binding.BindingMapping;
69 import org.opendaylight.yangtools.yang.binding.DataContainer;
70 import org.opendaylight.yangtools.yang.binding.RpcService;
71 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.common.RpcResult;
74 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
79 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
82 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
83 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.Module;
88 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
89 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.Status;
95 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.UsesNode;
98 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
99 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
100 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
104 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
105 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
106 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
107 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
111 abstract class AbstractTypeGenerator {
112 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
113 private static final Splitter COLON_SPLITTER = Splitter.on(':');
116 * Comparator based on augment target path.
118 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
119 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
120 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
122 while (thisIt.hasNext()) {
123 if (!otherIt.hasNext()) {
127 final int comp = thisIt.next().compareTo(otherIt.next());
133 return otherIt.hasNext() ? -1 : 0;
137 * Constant with the concrete name of identifier.
139 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
142 * Constant with the concrete name of namespace.
144 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
146 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
149 * Outer key represents the package name. Outer value represents map of all
150 * builders in the same package. Inner key represents the schema node name
151 * (in JAVA class/interface name format). Inner value represents instance of
152 * builder for schema node specified in key part.
154 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
157 * Provide methods for converting YANG types to JAVA types.
159 private final AbstractTypeProvider typeProvider;
162 * Holds reference to schema context to resolve data of augmented element
163 * when creating augmentation builder
165 private final SchemaContext schemaContext;
167 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
168 this.schemaContext = requireNonNull(context);
169 this.typeProvider = requireNonNull(typeProvider);
171 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
172 for (final Module contextModule : contextModules) {
173 moduleToGenTypes(contextModule, schemaContext);
175 for (final Module contextModule : contextModules) {
176 allAugmentsToGenTypes(contextModule);
180 final Collection<ModuleContext> moduleContexts() {
181 return genCtx.values();
184 final ModuleContext moduleContext(final Module module) {
185 return checkNotNull(genCtx.get(module), "Module context not found for module %s", module);
188 final AbstractTypeProvider typeProvider() {
192 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
194 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
196 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
197 Set<? extends SchemaNode> nodes);
199 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
201 private void moduleToGenTypes(final Module m, final SchemaContext context) {
202 genCtx.put(m, new ModuleContext());
203 allTypeDefinitionsToGenTypes(m);
204 groupingsToGenTypes(m, m.getGroupings());
205 rpcMethodsToGenType(m);
206 allIdentitiesToGenTypes(m, context);
207 notificationsToGenType(m);
209 if (!m.getChildNodes().isEmpty()) {
210 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
211 genCtx.get(m).addModuleNode(moduleType);
212 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
213 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
218 * Converts all extended type definitions of module to the list of
219 * <code>Type</code> objects.
222 * module from which is obtained set of type definitions
223 * @throws IllegalArgumentException
225 * <li>if module is null</li>
226 * <li>if name of module is null</li>
228 * @throws IllegalStateException
229 * if set of type definitions from module is null
231 private void allTypeDefinitionsToGenTypes(final Module module) {
232 checkArgument(module != null, "Module reference cannot be NULL.");
233 checkArgument(module.getName() != null, "Module name cannot be NULL.");
234 final DataNodeIterator it = new DataNodeIterator(module);
235 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
236 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
238 for (final TypeDefinition<?> typedef : typeDefinitions) {
239 if (typedef != null) {
240 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,
243 final ModuleContext ctx = genCtx.get(module);
244 ctx.addTypedefType(typedef.getPath(), type);
245 ctx.addTypeToSchema(type,typedef);
251 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
252 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
253 if (node.isAugmenting() || node.isAddedByUses()) {
256 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
257 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
258 annotateDeprecatedIfNecessary(node.getStatus(), genType);
260 genType.setModuleName(module.getName());
261 addCodegenInformation(genType, module, node);
262 genType.setSchemaPath(node.getPath().getPathFromRoot());
263 if (node instanceof DataNodeContainer) {
264 genCtx.get(module).addChildNodeType(node, genType);
265 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
266 processUsesAugments((DataNodeContainer) node, module);
271 private void containerToGenType(final Module module, final String basePackageName,
272 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
273 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
274 if (genType != null) {
275 constructGetter(parent, genType, node);
276 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
280 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
281 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
282 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
283 if (genType != null) {
284 constructGetter(parent, Types.listTypeFor(genType), node);
286 final List<String> listKeys = listKeys(node);
287 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
288 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
289 if (genTOBuilder != null) {
290 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
291 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
292 genTOBuilder.addImplementsType(identifierMarker);
293 genType.addImplementsType(identifiableMarker);
296 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
297 if (!schemaNode.isAugmenting()) {
298 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
303 if (genTOBuilder != null) {
304 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
305 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
306 genTOBuilder.setSUID(prop);
309 typeBuildersToGenTypes(module, genType, genTOBuilder);
313 private void processUsesAugments(final DataNodeContainer node, final Module module) {
314 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
315 for (final UsesNode usesNode : node.getUses()) {
316 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
317 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
318 processUsesAugments(augment, module);
324 * Converts all <b>augmentation</b> of the module to the list
325 * <code>Type</code> objects.
328 * module from which is obtained list of all augmentation objects
329 * to iterate over them
330 * @throws IllegalArgumentException
332 * <li>if the module is null</li>
333 * <li>if the name of module is null</li>
335 * @throws IllegalStateException
336 * if set of augmentations from module is null
338 private void allAugmentsToGenTypes(final Module module) {
339 checkArgument(module != null, "Module reference cannot be NULL.");
340 checkArgument(module.getName() != null, "Module name cannot be NULL.");
341 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
343 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
344 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
345 augmentationToGenTypes(basePackageName, augment, module);
350 * Returns list of <code>AugmentationSchema</code> objects. The objects are
351 * sorted according to the length of their target path from the shortest to
355 * module from which is obtained list of all augmentation objects
356 * @return list of sorted <code>AugmentationSchema</code> objects obtained
357 * from <code>module</code>
358 * @throws IllegalArgumentException
360 * @throws IllegalStateException
361 * if set of module augmentations is null
363 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
364 checkArgument(module != null, "Module reference cannot be NULL.");
365 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
367 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
368 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
369 sortedAugmentations.sort(AUGMENT_COMP);
371 return sortedAugmentations;
375 * Create GeneratedTypeBuilder object from module argument.
378 * Module object from which builder will be created
379 * @return <code>GeneratedTypeBuilder</code> which is internal
380 * representation of the module
381 * @throws IllegalArgumentException
384 private GeneratedTypeBuilder moduleToDataType(final Module module) {
385 checkArgument(module != null, "Module reference cannot be NULL.");
387 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
388 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
389 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
391 addCodegenInformation(moduleDataTypeBuilder, module);
392 return moduleDataTypeBuilder;
396 * Converts all <b>RPCs</b> input and output substatements of the module
397 * to the list of <code>Type</code> objects. In addition are to containers
398 * and lists which belong to input or output also part of returning list.
401 * module from which is obtained set of all rpc objects to
403 * @throws IllegalArgumentException
405 * <li>if the module is null</li>
406 * <li>if the name of module is null</li>
408 * @throws IllegalStateException
409 * if set of rpcs from module is null
411 private void rpcMethodsToGenType(final Module module) {
412 checkArgument(module != null, "Module reference cannot be NULL.");
413 checkArgument(module.getName() != null, "Module name cannot be NULL.");
414 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
415 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
416 if (rpcDefinitions.isEmpty()) {
420 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
421 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
422 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
424 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
426 for (final RpcDefinition rpc : rpcDefinitions) {
428 final String rpcName = BindingMapping.getClassName(rpc.getQName());
429 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
430 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
431 final ContainerSchemaNode input = rpc.getInput();
432 final ContainerSchemaNode output = rpc.getOutput();
434 // Do not refer to annotation class, as it may not be available at runtime
435 method.addAnnotation("javax.annotation", "CheckReturnValue");
437 //in case of implicit RPC input (StatementSource.CONTEXT),
438 // stay compatible (no input argument generated)
439 if (input != null && isExplicitStatement(input)) {
440 processUsesAugments(input, module);
441 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
442 addImplementedInterfaceFromUses(input, inType);
443 inType.addImplementsType(DATA_OBJECT);
444 inType.addImplementsType(augmentable(inType));
445 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
446 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
447 genCtx.get(module).addChildNodeType(input, inType);
448 final GeneratedType inTypeInstance = inType.toInstance();
449 method.addParameter(inTypeInstance, "input");
452 Type outTypeInstance = VOID;
453 //in case of implicit RPC output (StatementSource.CONTEXT),
454 //stay compatible (Future<RpcResult<Void>> return type generated)
455 if (output != null && isExplicitStatement(output)) {
456 processUsesAugments(output, module);
457 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
458 addImplementedInterfaceFromUses(output, outType);
459 outType.addImplementsType(DATA_OBJECT);
460 outType.addImplementsType(augmentable(outType));
461 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
462 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
463 genCtx.get(module).addChildNodeType(output, outType);
464 outTypeInstance = outType.toInstance();
467 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
468 addComment(method, rpc);
469 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
473 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
476 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
477 return node instanceof EffectiveStatement
478 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
482 * Converts all <b>notifications</b> of the module to the list of
483 * <code>Type</code> objects. In addition are to this list added containers
484 * and lists which are part of this notification.
487 * module from which is obtained set of all notification objects
488 * to iterate over them
489 * @throws IllegalArgumentException
491 * <li>if the module equals null</li>
492 * <li>if the name of module equals null</li>
494 * @throws IllegalStateException
495 * if set of notifications from module is null
497 private void notificationsToGenType(final Module module) {
498 checkArgument(module != null, "Module reference cannot be NULL.");
499 checkArgument(module.getName() != null, "Module name cannot be NULL.");
500 final Set<NotificationDefinition> notifications = module.getNotifications();
501 if (notifications.isEmpty()) {
505 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
506 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
507 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
509 for (final NotificationDefinition notification : notifications) {
510 if (notification != null) {
511 processUsesAugments(notification, module);
513 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
514 notification, null, module);
515 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
516 notificationInterface.addImplementsType(NOTIFICATION);
517 genCtx.get(module).addChildNodeType(notification, notificationInterface);
519 // Notification object
520 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
521 notification.getChildNodes());
523 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
524 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
525 .setReturnType(Types.VOID), notification);
529 addCodegenInformation(listenerInterface, module, "notifications", notifications);
530 genCtx.get(module).addTopLevelNodeType(listenerInterface);
534 * Converts all <b>identities</b> of the module to the list of
535 * <code>Type</code> objects.
538 * module from which is obtained set of all identity objects to
541 * schema context only used as input parameter for method
542 * {@link BindingGeneratorImpl#identityToGenType}
545 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
546 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
547 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
549 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
550 for (final IdentitySchemaNode identity : schemaIdentities) {
551 identityToGenType(module, basePackageName, identity, context);
557 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
558 * created transport object builder. If identity contains base identity then
559 * reference to base identity is added to superior identity as its extend.
560 * If identity doesn't contain base identity then only reference to abstract
561 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
562 * BaseIdentity} is added
566 * @param basePackageName
567 * string contains the module package name
569 * IdentitySchemaNode which contains data about identity
571 * SchemaContext which is used to get package and name
572 * information about base of identity
575 private void identityToGenType(final Module module, final String basePackageName,
576 final IdentitySchemaNode identity, final SchemaContext context) {
577 if (identity == null) {
580 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
581 final String genTypeName = BindingMapping.getClassName(identity.getQName());
582 final GeneratedTOBuilder newType = typeProvider.newGeneratedTOBuilder(packageName, genTypeName);
583 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
584 if (baseIdentities.isEmpty()) {
585 final GeneratedTOBuilder gto = typeProvider.newGeneratedTOBuilder(
586 BaseIdentity.class.getPackage().getName(), BaseIdentity.class.getSimpleName());
587 newType.setExtendsType(gto.toInstance());
589 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
590 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
591 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
593 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
594 final GeneratedTransferObject gto = new CodegenGeneratedTOBuilder(returnTypePkgName, returnTypeName)
596 newType.setExtendsType(gto);
598 newType.setAbstract(true);
600 addCodegenInformation(newType, module, identity);
601 newType.setModuleName(module.getName());
602 newType.setSchemaPath(identity.getPath().getPathFromRoot());
604 final QName qname = identity.getQName();
605 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
607 genCtx.get(module).addIdentityType(identity.getQName(), newType);
611 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
613 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
617 * Converts all <b>groupings</b> of the module to the list of
618 * <code>Type</code> objects. Firstly are groupings sorted according mutual
619 * dependencies. At least dependent (independent) groupings are in the list
620 * saved at first positions. For every grouping the record is added to map
621 * {@link ModuleContext#groupings allGroupings}
626 * collection of groupings from which types will be generated
629 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
630 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
631 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
633 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
634 groupingToGenType(basePackageName, grouping, module);
639 * Converts individual grouping to GeneratedType. Firstly generated type
640 * builder is created and every child node of grouping is resolved to the
643 * @param basePackageName
644 * string contains the module package name
646 * GroupingDefinition which contains data about grouping
650 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
651 final Module module) {
652 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
653 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
654 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
655 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
656 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
657 groupingsToGenTypes(module, grouping.getGroupings());
658 processUsesAugments(grouping, module);
662 * Adds enumeration builder created from <code>enumTypeDef</code> to
663 * <code>typeBuilder</code>.
665 * Each <code>enumTypeDef</code> item is added to builder with its name and
669 * EnumTypeDefinition contains enum data
671 * string contains name which will be assigned to enumeration
674 * GeneratedTypeBuilder to which will be enum builder assigned
676 * Module in which type should be generated
677 * @return enumeration builder which contains data from
678 * <code>enumTypeDef</code>
680 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
681 final GeneratedTypeBuilder typeBuilder, final Module module) {
682 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
683 final String enumerationName = BindingMapping.getClassName(enumName);
684 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
685 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
686 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
687 ModuleContext ctx = genCtx.get(module);
688 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
695 * Generates type builder for <code>module</code>.
698 * Module which is source of package name for generated type
701 * string which is added to the module class name representation
703 * @return instance of GeneratedTypeBuilder which represents
704 * <code>module</code>.
705 * @throws IllegalArgumentException
706 * if <code>module</code> is null
708 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
709 checkArgument(module != null, "Module reference cannot be NULL.");
710 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
711 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
713 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
715 moduleBuilder.setModuleName(moduleName);
716 addCodegenInformation(moduleBuilder, module);
717 return moduleBuilder;
721 * Converts <code>augSchema</code> to list of <code>Type</code> which
722 * contains generated type for augmentation. In addition there are also
723 * generated types for all containers, list and choices which are child of
724 * <code>augSchema</code> node or a generated types for cases are added if
725 * augmented node is choice.
727 * @param augmentPackageName
728 * string with the name of the package to which the augmentation
731 * AugmentationSchema which is contains data about augmentation
732 * (target path, childs...)
735 * @throws IllegalArgumentException
737 * <li>if <code>augmentPackageName</code> equals null</li>
738 * <li>if <code>augSchema</code> equals null</li>
740 * @throws IllegalStateException
741 * if augment target path is null
743 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
744 final Module module) {
745 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
746 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
747 checkState(augSchema.getTargetPath() != null,
748 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
750 processUsesAugments(augSchema, module);
751 final SchemaPath targetPath = augSchema.getTargetPath();
752 SchemaNode targetSchemaNode = null;
754 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
755 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
756 if (targetSchemaNode instanceof DerivableSchemaNode) {
757 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
759 if (targetSchemaNode == null) {
760 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
761 + " in module " + module.getName());
764 if (targetSchemaNode == null) {
765 throw new IllegalArgumentException("augment target not found: " + targetPath);
768 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
769 if (targetTypeBuilder == null) {
770 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
772 if (targetTypeBuilder == null) {
773 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
776 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
777 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
778 targetTypeBuilder.getName());
779 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
782 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
783 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
787 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
788 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
789 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
790 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
791 checkState(augSchema.getTargetPath() != null,
792 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
794 processUsesAugments(augSchema, module);
795 final SchemaPath targetPath = augSchema.getTargetPath();
796 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
797 if (targetSchemaNode == null) {
798 throw new IllegalArgumentException("augment target not found: " + targetPath);
801 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
802 if (targetTypeBuilder == null) {
803 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
805 if (targetTypeBuilder == null) {
806 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
809 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
810 String packageName = augmentPackageName;
811 if (usesNodeParent instanceof SchemaNode) {
812 packageName = packageNameForAugmentedGeneratedType(augmentPackageName,
813 ((SchemaNode) usesNodeParent).getPath());
815 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
818 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
819 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
824 * Convenient method to find node added by uses statement.
828 * @param parentUsesNode
829 * parent of uses node
830 * @return node from its original location in grouping
832 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
833 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
835 if (!(targetGrouping instanceof GroupingDefinition)) {
836 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
839 SchemaNode result = targetGrouping;
840 for (final QName node : targetPath.getPathFromRoot()) {
841 if (result instanceof DataNodeContainer) {
842 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
843 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
844 } else if (result instanceof ChoiceSchemaNode) {
845 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
848 if (result == null) {
852 if (result instanceof DerivableSchemaNode) {
853 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
854 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
855 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
856 result = originalNode.get();
860 if (result instanceof DataSchemaNode) {
861 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
862 if (resultDataSchemaNode.isAddedByUses()) {
863 // The original node is required, but we have only the copy of
864 // the original node.
865 // Maybe this indicates a bug in Yang parser.
866 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
869 return resultDataSchemaNode;
872 throw new IllegalStateException(
873 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
878 * Returns a generated type builder for an augmentation.
880 * The name of the type builder is equal to the name of augmented node with
881 * serial number as suffix.
885 * @param augmentPackageName
886 * string with contains the package name to which the augment
888 * @param basePackageName
889 * string with the package name to which the augmented node
891 * @param targetTypeRef
894 * augmentation schema which contains data about the child nodes
895 * and uses of augment
896 * @return generated type builder for augment
898 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
899 final String basePackageName, final Type targetTypeRef, final AugmentationSchemaNode augSchema) {
900 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
901 if (augmentBuilders == null) {
902 augmentBuilders = new HashMap<>();
903 genTypeBuilders.put(augmentPackageName, augmentBuilders);
905 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
908 if (augIdentifier != null) {
909 augTypeName = BindingMapping.getClassName(augIdentifier);
911 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
914 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
916 augTypeBuilder.addImplementsType(DATA_OBJECT);
917 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
918 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
919 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
921 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
922 augmentBuilders.put(augTypeName, augTypeBuilder);
924 if (!augSchema.getChildNodes().isEmpty()) {
925 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
928 genCtx.get(module).addAugmentType(augTypeBuilder);
929 return augTypeBuilder;
934 * @param unknownSchemaNodes
935 * @return nodeParameter of UnknownSchemaNode
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
950 * generated type builder name for augment consists from name of augmented
951 * node and serial number of its augmentation.
954 * map of builders which were created in the package to which the
955 * augmentation belongs
957 * string with name of augmented node
958 * @return string with unique name for augmentation builder
960 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
962 if (builders != null) {
963 while (builders.containsKey(genTypeName + index)) {
967 return genTypeName + index;
971 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
972 * node for which <code>typeBuilder</code> was created.
974 * The subnodes aren't mapped to the methods if they are part of grouping or
975 * augment (in this case are already part of them).
979 * @param basePackageName
980 * string contains the module package name
982 * generated type builder which represents any node. The subnodes
983 * of this node are added to the <code>typeBuilder</code> as
984 * methods. The subnode can be of type leaf, leaf-list, list,
989 * set of data schema nodes which are the children of the node
990 * for which <code>typeBuilder</code> was created
991 * @return generated type builder which is the same builder as input
992 * parameter. The getter methods (representing child nodes) could be
995 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
996 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
997 if (schemaNodes != null && parent != null) {
998 for (final DataSchemaNode schemaNode : schemaNodes) {
999 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1000 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1008 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1009 * node for which <code>typeBuilder</code> was created.
1013 * @param basePackageName
1014 * string contains the module package name
1015 * @param typeBuilder
1016 * generated type builder which represents any node. The subnodes
1017 * of this node are added to the <code>typeBuilder</code> as
1018 * methods. The subnode can be of type leaf, leaf-list, list,
1019 * container, choice.
1022 * @param schemaNodes
1023 * set of data schema nodes which are the children of the node
1024 * for which <code>typeBuilder</code> was created
1025 * @return generated type builder which is the same object as the input
1026 * parameter <code>typeBuilder</code>. The getter method could be
1029 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1030 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1031 final Iterable<DataSchemaNode> schemaNodes) {
1032 if (schemaNodes != null && typeBuilder != null) {
1033 for (final DataSchemaNode schemaNode : schemaNodes) {
1034 if (!schemaNode.isAugmenting()) {
1035 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1043 * Adds to <code>typeBuilder</code> a method which is derived from
1044 * <code>schemaNode</code>.
1046 * @param basePackageName
1047 * string with the module package name
1049 * data schema node which is added to <code>typeBuilder</code> as
1051 * @param typeBuilder
1052 * generated type builder to which is <code>schemaNode</code>
1053 * added as a method.
1059 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1060 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1061 if (node != null && typeBuilder != null) {
1062 if (node instanceof LeafSchemaNode) {
1063 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1064 } else if (node instanceof LeafListSchemaNode) {
1065 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1066 } else if (node instanceof ContainerSchemaNode) {
1067 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1068 } else if (node instanceof ListSchemaNode) {
1069 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1070 } else if (node instanceof ChoiceSchemaNode) {
1071 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1073 // TODO: anyxml not yet supported
1074 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1075 typeBuilder.getFullyQualifiedName());
1081 * Converts <code>choiceNode</code> to the list of generated types for
1082 * choice and its cases.
1084 * The package names for choice and for its cases are created as
1085 * concatenation of the module package (<code>basePackageName</code>) and
1086 * names of all parents node.
1090 * @param basePackageName
1091 * string with the module package name
1095 * choice node which is mapped to generated type. Also child
1096 * nodes - cases are mapped to generated types.
1097 * @throws IllegalArgumentException
1099 * <li>if <code>basePackageName</code> is null</li>
1100 * <li>if <code>choiceNode</code> is null</li>
1103 private void choiceToGeneratedType(final Module module, final String basePackageName,
1104 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1105 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1106 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1108 if (!choiceNode.isAddedByUses()) {
1109 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1110 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1111 constructGetter(parent, choiceTypeBuilder, choiceNode);
1112 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1113 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1114 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1115 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1120 * Converts <code>caseNodes</code> set to list of corresponding generated
1123 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1124 * created generated type builder. The package names for the builder is
1125 * created as concatenation of the module package (
1126 * <code>basePackageName</code>) and names of all parents nodes of the
1127 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1128 * between every case builder and <i>choice</i> type
1132 * @param basePackageName
1133 * string with the module package name
1134 * @param refChoiceType
1135 * type which represents superior <i>case</i>
1137 * choice case node which is mapped to generated type
1138 * @throws IllegalArgumentException
1140 * <li>if <code>basePackageName</code> equals null</li>
1141 * <li>if <code>refChoiceType</code> equals null</li>
1142 * <li>if <code>caseNodes</code> equals null</li>
1145 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1146 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1147 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1148 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1149 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1151 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1152 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1153 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1154 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
1156 caseTypeBuilder.addImplementsType(refChoiceType);
1157 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1158 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1159 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1160 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1161 if (caseChildNodes != null) {
1162 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1164 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1165 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1167 if (parent instanceof AugmentationSchemaNode) {
1168 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1169 final SchemaPath targetPath = augSchema.getTargetPath();
1170 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1171 if (targetSchemaNode instanceof DataSchemaNode
1172 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1173 if (targetSchemaNode instanceof DerivableSchemaNode) {
1174 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1177 if (targetSchemaNode == null) {
1178 throw new IllegalStateException(
1179 "Failed to find target node from grouping for augmentation " + augSchema
1180 + " in module " + module.getName());
1183 parent = targetSchemaNode;
1186 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1187 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1188 if (childOfType == null) {
1189 childOfType = findGroupingByPath(parent.getPath());
1191 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1193 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1198 processUsesAugments(caseNode, module);
1203 * Generates list of generated types for all the cases of a choice which are
1204 * added to the choice through the augment.
1208 * @param basePackageName
1209 * string contains name of package to which augment belongs. If
1210 * an augmented choice is from an other package (pcg1) than an
1211 * augmenting choice (pcg2) then case's of the augmenting choice
1212 * will belong to pcg2.
1214 * Type which represents target choice
1216 * node which represents target choice
1217 * @param augmentedNodes
1218 * set of choice case nodes for which is checked if are/aren't
1219 * added to choice through augmentation
1220 * @throws IllegalArgumentException
1222 * <li>if <code>basePackageName</code> is null</li>
1223 * <li>if <code>targetType</code> is null</li>
1224 * <li>if <code>augmentedNodes</code> is null</li>
1227 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1228 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1229 final DataNodeContainer usesNodeParent) {
1230 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1231 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1232 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1234 for (final DataSchemaNode caseNode : augmentedNodes) {
1235 if (caseNode != null) {
1236 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1237 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1238 caseTypeBuilder.addImplementsType(targetType);
1241 final SchemaPath nodeSp = targetNode.getPath();
1242 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1244 GeneratedTypeBuilder childOfType = null;
1245 if (parent instanceof Module) {
1246 childOfType = genCtx.get(parent).getModuleNode();
1247 } else if (parent instanceof CaseSchemaNode) {
1248 childOfType = findCaseByPath(parent.getPath());
1249 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1250 childOfType = findChildNodeByPath(parent.getPath());
1251 } else if (parent instanceof GroupingDefinition) {
1252 childOfType = findGroupingByPath(parent.getPath());
1255 if (childOfType == null) {
1256 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1259 CaseSchemaNode node = null;
1260 final String caseLocalName = caseNode.getQName().getLocalName();
1261 if (caseNode instanceof CaseSchemaNode) {
1262 node = (CaseSchemaNode) caseNode;
1263 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1264 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1265 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1266 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1267 ().getLocalName())) {
1268 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1273 node = findNamedCase(targetNode, caseLocalName);
1275 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1276 if (childNodes != null) {
1277 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1279 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1280 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1285 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1286 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1287 return cases.isEmpty() ? null : cases.get(0);
1290 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1291 // New parser with encapsulated type
1292 if (leaf.getPath().equals(type.getPath())) {
1296 // Embedded type definition with new parser. Also takes care of the old parser with bits
1297 if (leaf.getPath().equals(type.getPath().getParent())) {
1305 * Converts <code>leaf</code> to the getter method which is added to
1306 * <code>typeBuilder</code>.
1308 * @param typeBuilder
1309 * generated type builder to which is added getter method as
1310 * <code>leaf</code> mapping
1312 * leaf schema node which is mapped as getter method which is
1313 * added to <code>typeBuilder</code>
1315 * Module in which type was defined
1316 * @return boolean value
1318 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1320 * <li>true - in other cases</li>
1323 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1324 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1328 final Module parentModule = findParentModule(schemaContext, leaf);
1329 Type returnType = null;
1331 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1332 if (isInnerType(leaf, typeDef)) {
1333 if (typeDef instanceof EnumTypeDefinition) {
1334 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1335 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1336 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1337 typeBuilder, module);
1338 if (enumBuilder != null) {
1339 returnType = enumBuilder.toInstance(typeBuilder);
1341 typeProvider.putReferencedType(leaf.getPath(), returnType);
1342 } else if (typeDef instanceof UnionTypeDefinition) {
1343 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1344 if (genTOBuilder != null) {
1345 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1346 // Store the inner type within the union so that we can find the reference for it
1347 genCtx.get(module).addInnerTypedefType(typeDef.getPath(), returnType);
1349 } else if (typeDef instanceof BitsTypeDefinition) {
1350 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1351 if (genTOBuilder != null) {
1352 returnType = genTOBuilder.toInstance();
1355 // It is constrained version of already declared type (inner declared type exists,
1356 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1357 // In order to get proper class we need to look up closest derived type
1358 // and apply restrictions from leaf type
1359 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1360 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1364 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1365 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1368 if (returnType == null) {
1372 if (typeDef instanceof EnumTypeDefinition) {
1373 typeProvider.putReferencedType(leaf.getPath(), returnType);
1376 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1377 processContextRefExtension(leaf, getter, parentModule);
1381 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1382 // Returns DerivedType in case of new parser.
1383 final TypeDefinition<?> baseType = typeDef.getBaseType();
1384 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1387 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1388 final Module module) {
1389 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1390 final QName nodeType = node.getNodeType();
1391 if ("context-reference".equals(nodeType.getLocalName())) {
1392 final String nodeParam = node.getNodeParameter();
1393 IdentitySchemaNode identity = null;
1394 String basePackageName = null;
1395 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1396 final Iterator<String> iterator = splittedElement.iterator();
1397 final int length = Iterables.size(splittedElement);
1399 identity = findIdentityByName(module.getIdentities(), iterator.next());
1400 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1401 } else if (length == 2) {
1402 final String prefix = iterator.next();
1403 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1404 if (dependentModule == null) {
1405 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1408 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1409 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1411 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1414 if (identity == null) {
1415 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1419 final Class<RoutingContext> clazz = RoutingContext.class;
1420 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1421 clazz.getSimpleName());
1422 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1423 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1424 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1429 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1430 for (final IdentitySchemaNode id : identities) {
1431 if (id.getQName().getLocalName().equals(name)) {
1438 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1439 for (final ModuleImport imp : imports) {
1440 if (imp.getPrefix().equals(prefix)) {
1441 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1447 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1448 final boolean isReadOnly, final Module module) {
1449 if (leaf != null && toBuilder != null) {
1451 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1452 if (typeDef instanceof UnionTypeDefinition) {
1453 // GeneratedType for this type definition should have be already created
1454 final QName qname = typeDef.getQName();
1455 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1456 final ModuleContext mc = genCtx.get(unionModule);
1457 returnType = mc.getTypedefs().get(typeDef.getPath());
1458 if (returnType == null) {
1459 // This may still be an inner type, try to find it
1460 returnType = mc.getInnerType(typeDef.getPath());
1462 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1463 // Annonymous enumeration (already generated, since it is inherited via uses).
1464 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1465 QName qname = originalLeaf.getQName();
1466 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
1467 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1469 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1471 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1477 * Converts <code>leaf</code> schema node to property of generated TO
1481 * generated TO builder to which is <code>leaf</code> added as
1484 * leaf schema node which is added to <code>toBuilder</code> as
1489 * boolean value which says if leaf property is|isn't read only
1490 * @return boolean value
1492 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1493 * name equals null or if leaf is added by <i>uses</i>.</li>
1494 * <li>true - other cases</li>
1497 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1498 final Type returnType, final boolean isReadOnly) {
1499 if (returnType == null) {
1502 final String leafName = leaf.getQName().getLocalName();
1503 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1504 propBuilder.setReadOnly(isReadOnly);
1505 propBuilder.setReturnType(returnType);
1506 addComment(propBuilder, leaf);
1508 toBuilder.addEqualsIdentity(propBuilder);
1509 toBuilder.addHashIdentity(propBuilder);
1510 toBuilder.addToStringProperty(propBuilder);
1515 * Converts <code>node</code> leaf list schema node to getter method of
1516 * <code>typeBuilder</code>.
1518 * @param typeBuilder
1519 * generated type builder to which is <code>node</code> added as
1522 * leaf list schema node which is added to
1523 * <code>typeBuilder</code> as getter method
1524 * @param module module
1525 * @return boolean value
1527 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1528 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1529 * <li>false - other cases</li>
1532 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1533 final Module module) {
1534 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1538 final QName nodeName = node.getQName();
1540 final TypeDefinition<?> typeDef = node.getType();
1541 final Module parentModule = findParentModule(schemaContext, node);
1543 Type returnType = null;
1544 if (typeDef.getBaseType() == null) {
1545 if (typeDef instanceof EnumTypeDefinition) {
1546 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1547 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1548 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1549 typeBuilder, module);
1550 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1551 typeProvider.putReferencedType(node.getPath(), returnType);
1552 } else if (typeDef instanceof UnionTypeDefinition) {
1553 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1554 if (genTOBuilder != null) {
1555 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1557 } else if (typeDef instanceof BitsTypeDefinition) {
1558 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1559 returnType = genTOBuilder.toInstance();
1561 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1562 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1565 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1566 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1569 final ParameterizedType listType = Types.listTypeFor(returnType);
1570 constructGetter(typeBuilder, listType, node);
1574 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1575 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1576 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getPackageName(),
1577 genTOBuilder.getName());
1579 addCodegenInformation(returnType, parentModule, typeDef);
1580 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1581 returnType.setModuleName(parentModule.getName());
1583 genTOBuilder.setTypedef(true);
1584 genTOBuilder.setIsUnion(true);
1585 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1589 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1592 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1593 method.setReturnType(returnType);
1594 method.addParameter(Types.STRING, "defaultValue");
1595 method.setAccessModifier(AccessModifier.PUBLIC);
1596 method.setStatic(true);
1598 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1599 if (types == null) {
1600 typeProvider.getAdditionalTypes().put(parentModule,
1601 Sets.newHashSet(unionBuilder.toInstance()));
1603 types.add(unionBuilder.toInstance());
1605 return returnType.toInstance();
1608 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1609 final GeneratedTypeBuilder typeBuilder) {
1610 final String outerCls = Types.getOuterClassName(genTOBuilder);
1611 final StringBuilder name;
1612 if (outerCls != null) {
1613 name = new StringBuilder(outerCls);
1615 name = new StringBuilder();
1617 name.append(genTOBuilder.getName());
1618 name.append("Builder");
1619 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(typeBuilder.getPackageName(),
1621 unionBuilder.setIsUnionBuilder(true);
1622 return unionBuilder;
1625 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1626 final Module module) {
1627 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1631 * Instantiates generated type builder with <code>packageName</code> and
1632 * <code>schemaNode</code>.
1634 * The new builder always implements
1635 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1636 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1637 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1639 * If <code>schemaNode</code> is instance of
1640 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1641 * DataNodeContainer} it can also implement nodes which are specified in
1644 * @param packageName
1645 * string with the name of the package to which
1646 * <code>schemaNode</code> belongs.
1648 * schema node for which is created generated type builder
1650 * parent type (can be null)
1651 * @return generated type builder <code>schemaNode</code>
1653 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1654 final Type parent, final Module module) {
1655 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1656 if (parent == null) {
1657 it.addImplementsType(DATA_OBJECT);
1659 it.addImplementsType(BindingTypes.childOf(parent));
1661 if (!(schemaNode instanceof GroupingDefinition)) {
1662 it.addImplementsType(augmentable(it));
1665 if (schemaNode instanceof DataNodeContainer) {
1666 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1667 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1674 * Wraps the calling of the same overloaded method.
1676 * @param packageName
1677 * string with the package name to which returning generated type
1680 * schema node which provide data about the schema node name
1681 * @return generated type builder for <code>schemaNode</code>
1683 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1684 return addRawInterfaceDefinition(packageName, schemaNode, "");
1688 * Returns reference to generated type builder for specified
1689 * <code>schemaNode</code> with <code>packageName</code>.
1691 * Firstly the generated type builder is searched in
1692 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1693 * found it is created and added to <code>genTypeBuilders</code>.
1695 * @param packageName
1696 * string with the package name to which returning generated type
1699 * schema node which provide data about the schema node name
1701 * return type name prefix
1702 * @return generated type builder for <code>schemaNode</code>
1703 * @throws IllegalArgumentException
1705 * <li>if <code>schemaNode</code> is null</li>
1706 * <li>if <code>packageName</code> is null</li>
1707 * <li>if QName of schema node is null</li>
1708 * <li>if schemaNode name is null</li>
1712 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1713 final String prefix) {
1714 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1715 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1716 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1717 final String schemaNodeName = schemaNode.getQName().getLocalName();
1718 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1721 if (prefix == null) {
1722 genTypeName = BindingMapping.getClassName(schemaNodeName);
1724 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1727 // FIXME: Validation of name conflict
1728 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1729 final Module module = findParentModule(schemaContext, schemaNode);
1730 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1732 addCodegenInformation(newType, module, schemaNode);
1733 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1734 newType.setModuleName(module.getName());
1736 if (!genTypeBuilders.containsKey(packageName)) {
1737 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1738 builders.put(genTypeName, newType);
1739 genTypeBuilders.put(packageName, builders);
1741 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1742 if (!builders.containsKey(genTypeName)) {
1743 builders.put(genTypeName, newType);
1750 * Creates the name of the getter method name from <code>localName</code>.
1753 * string with the name of the getter method
1756 * @return string with the name of the getter method for
1757 * <code>methodName</code> in JAVA method format
1759 public static String getterMethodName(final String localName, final Type returnType) {
1760 final StringBuilder method = new StringBuilder();
1761 if (BOOLEAN.equals(returnType)) {
1762 method.append("is");
1764 method.append("get");
1766 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1767 method.append(name);
1768 return method.toString();
1772 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1774 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1775 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1777 * @param interfaceBuilder generated type builder for which the getter method should be created
1778 * @param returnType type which represents the return type of the getter method
1779 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1780 * @param comment string with comment for the getter method
1781 * @param status status from yang file, for deprecated annotation
1782 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1784 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1785 final SchemaNode node) {
1786 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1787 getterMethodName(node.getQName().getLocalName(), returnType));
1788 getMethod.setReturnType(returnType);
1790 if (node.getStatus() == Status.DEPRECATED) {
1791 getMethod.addAnnotation("", "Deprecated");
1793 addComment(getMethod, node);
1799 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1800 * or to <code>genTOBuilder</code> as property.
1802 * @param basePackageName
1803 * string contains the module package name
1805 * data schema node which should be added as getter method to
1806 * <code>typeBuilder</code> or as a property to
1807 * <code>genTOBuilder</code> if is part of the list key
1808 * @param typeBuilder
1809 * generated type builder for the list schema node
1810 * @param genTOBuilder
1811 * generated TO builder for the list keys
1813 * list of string which contains names of the list keys
1816 * @throws IllegalArgumentException
1818 * <li>if <code>schemaNode</code> equals null</li>
1819 * <li>if <code>typeBuilder</code> equals null</li>
1822 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1823 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1824 final Module module) {
1825 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1826 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1828 if (schemaNode instanceof LeafSchemaNode) {
1829 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1830 final String leafName = leaf.getQName().getLocalName();
1831 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, module);
1832 if (listKeys.contains(leafName)) {
1834 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1836 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1839 } else if (!schemaNode.isAddedByUses()) {
1840 if (schemaNode instanceof LeafListSchemaNode) {
1841 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1842 } else if (schemaNode instanceof ContainerSchemaNode) {
1843 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1844 } else if (schemaNode instanceof ChoiceSchemaNode) {
1845 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1846 } else if (schemaNode instanceof ListSchemaNode) {
1847 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1852 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1853 final GeneratedTOBuilder genTOBuilder) {
1854 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1856 if (genTOBuilder != null) {
1857 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1859 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1860 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1861 getMethod.setReturnType(genTO);
1862 getMethod.setComment("Returns Primary Key of Yang List Type");
1863 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1868 * Selects the names of the list keys from <code>list</code> and returns
1869 * them as the list of the strings
1872 * of string with names of the list keys
1873 * @return list of string which represents names of the list keys. If the
1874 * <code>list</code> contains no keys then the empty list is
1877 private static List<String> listKeys(final ListSchemaNode list) {
1878 final List<String> listKeys = new ArrayList<>();
1880 final List<QName> keyDefinition = list.getKeyDefinition();
1881 if (keyDefinition != null) {
1882 for (final QName keyDef : keyDefinition) {
1883 listKeys.add(keyDef.getLocalName());
1890 * Generates for the <code>list</code> which contains any list keys special
1891 * generated TO builder.
1893 * @param packageName
1894 * string with package name to which the list belongs
1896 * list schema node which is source of data about the list name
1897 * @return generated TO builder which represents the keys of the
1898 * <code>list</code> or null if <code>list</code> is null or list of
1899 * key definitions is null or empty.
1901 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1902 GeneratedTOBuilder genTOBuilder = null;
1903 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1904 final String listName = list.getQName().getLocalName() + "Key";
1905 final String genTOName = BindingMapping.getClassName(listName);
1906 genTOBuilder = typeProvider.newGeneratedTOBuilder(packageName, genTOName);
1908 return genTOBuilder;
1912 * Builds generated TO builders for <code>typeDef</code> of type
1913 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
1914 * also added to <code>typeBuilder</code> as enclosing transfer object.
1916 * If more then one generated TO builder is created for enclosing then all
1917 * of the generated TO builders are added to <code>typeBuilder</code> as
1918 * enclosing transfer objects.
1921 * type definition which can be of type <code>UnionType</code> or
1922 * <code>BitsTypeDefinition</code>
1923 * @param typeBuilder
1924 * generated type builder to which is added generated TO created
1925 * from <code>typeDef</code>
1927 * string with name for generated TO builder
1928 * @param parentModule
1930 * @return generated TO builder for <code>typeDef</code>
1932 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1933 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1934 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1935 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1936 final String packageName = typeBuilder.getFullyQualifiedName();
1937 if (typeDef instanceof UnionTypeDefinition) {
1938 final List<GeneratedTOBuilder> types = typeProvider
1939 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
1940 classNameFromLeaf, leaf);
1941 genTOBuilders.addAll(types);
1943 GeneratedTOBuilder resultTOBuilder;
1944 if (types.isEmpty()) {
1945 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1947 resultTOBuilder = types.remove(0);
1948 for (final GeneratedTOBuilder genTOBuilder : types) {
1949 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1952 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1953 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1954 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1955 resultTOBuilder.addHashIdentity(genPropBuilder);
1956 resultTOBuilder.addToStringProperty(genPropBuilder);
1958 } else if (typeDef instanceof BitsTypeDefinition) {
1959 genTOBuilders.add(typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1960 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1962 if (!genTOBuilders.isEmpty()) {
1963 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1964 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1966 return genTOBuilders.get(0);
1973 * Adds the implemented types to type builder.
1975 * The method passes through the list of <i>uses</i> in
1976 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1977 * generated type from {@link ModuleContext#groupings
1978 * allGroupings} which is added as <i>implements type</i> to
1979 * <code>builder</code>
1981 * @param dataNodeContainer
1982 * element which contains the list of used YANG groupings
1984 * builder to which are added implemented types according to
1985 * <code>dataNodeContainer</code>
1986 * @return generated type builder with all implemented types
1988 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1989 final GeneratedTypeBuilder builder) {
1990 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1991 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1992 if (genType == null) {
1993 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1994 + builder.getName());
1997 builder.addImplementsType(genType);
2002 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2003 for (final ModuleContext ctx : genCtx.values()) {
2004 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2005 if (result != null) {
2012 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2013 for (final ModuleContext ctx : genCtx.values()) {
2014 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2015 if (result != null) {
2022 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2023 for (final ModuleContext ctx : genCtx.values()) {
2024 final GeneratedTypeBuilder result = ctx.getCase(path);
2025 if (result != null) {
2032 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2033 if (status == Status.DEPRECATED) {
2034 builder.addAnnotation("", "Deprecated");