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.TypeConstants;
62 import org.opendaylight.mdsal.binding.model.util.Types;
63 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.CodegenGeneratedTOBuilder;
64 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
65 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
66 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
67 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
68 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
69 import org.opendaylight.yangtools.yang.binding.BindingMapping;
70 import org.opendaylight.yangtools.yang.binding.DataContainer;
71 import org.opendaylight.yangtools.yang.binding.RpcService;
72 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
83 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
84 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.Module;
89 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
90 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
95 import org.opendaylight.yangtools.yang.model.api.Status;
96 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.UsesNode;
99 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
100 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
101 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
104 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
106 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
107 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
113 abstract class AbstractTypeGenerator {
114 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
115 private static final Splitter COLON_SPLITTER = Splitter.on(':');
118 * Comparator based on augment target path.
120 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
121 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
122 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
124 while (thisIt.hasNext()) {
125 if (!otherIt.hasNext()) {
129 final int comp = thisIt.next().compareTo(otherIt.next());
135 return otherIt.hasNext() ? -1 : 0;
139 * Constant with the concrete name of identifier.
141 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
144 * Constant with the concrete name of namespace.
146 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
148 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
151 * Outer key represents the package name. Outer value represents map of all
152 * builders in the same package. Inner key represents the schema node name
153 * (in JAVA class/interface name format). Inner value represents instance of
154 * builder for schema node specified in key part.
156 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
159 * Provide methods for converting YANG types to JAVA types.
161 private final AbstractTypeProvider typeProvider;
164 * Holds reference to schema context to resolve data of augmented element
165 * when creating augmentation builder
167 private final SchemaContext schemaContext;
169 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
170 this.schemaContext = requireNonNull(context);
171 this.typeProvider = requireNonNull(typeProvider);
173 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
174 for (final Module contextModule : contextModules) {
175 moduleToGenTypes(contextModule, schemaContext);
177 for (final Module contextModule : contextModules) {
178 allAugmentsToGenTypes(contextModule);
182 final Collection<ModuleContext> moduleContexts() {
183 return genCtx.values();
186 final ModuleContext moduleContext(final Module module) {
187 return checkNotNull(genCtx.get(module), "Module context not found for module %s", module);
190 final AbstractTypeProvider typeProvider() {
194 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
196 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
198 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
199 Set<? extends SchemaNode> nodes);
201 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
203 private void moduleToGenTypes(final Module m, final SchemaContext context) {
204 genCtx.put(m, new ModuleContext());
205 allTypeDefinitionsToGenTypes(m);
206 groupingsToGenTypes(m, m.getGroupings());
207 rpcMethodsToGenType(m);
208 allIdentitiesToGenTypes(m, context);
209 notificationsToGenType(m);
211 if (!m.getChildNodes().isEmpty()) {
212 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
213 genCtx.get(m).addModuleNode(moduleType);
214 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
215 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
220 * Converts all extended type definitions of module to the list of
221 * <code>Type</code> objects.
224 * module from which is obtained set of type definitions
225 * @throws IllegalArgumentException
227 * <li>if module is null</li>
228 * <li>if name of module is null</li>
230 * @throws IllegalStateException
231 * if set of type definitions from module is null
233 private void allTypeDefinitionsToGenTypes(final Module module) {
234 checkArgument(module != null, "Module reference cannot be NULL.");
235 checkArgument(module.getName() != null, "Module name cannot be NULL.");
236 final DataNodeIterator it = new DataNodeIterator(module);
237 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
238 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
240 for (final TypeDefinition<?> typedef : typeDefinitions) {
241 if (typedef != null) {
242 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,
245 final ModuleContext ctx = genCtx.get(module);
246 ctx.addTypedefType(typedef.getPath(), type);
247 ctx.addTypeToSchema(type,typedef);
253 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
254 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
255 if (node.isAugmenting() || node.isAddedByUses()) {
258 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
259 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
260 annotateDeprecatedIfNecessary(node.getStatus(), genType);
262 genType.setModuleName(module.getName());
263 addCodegenInformation(genType, module, node);
264 genType.setSchemaPath(node.getPath());
265 if (node instanceof DataNodeContainer) {
266 genCtx.get(module).addChildNodeType(node, genType);
267 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
268 processUsesAugments((DataNodeContainer) node, module);
273 private void containerToGenType(final Module module, final String basePackageName,
274 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
275 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
276 if (genType != null) {
277 constructGetter(parent, genType, node);
278 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
282 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
283 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
284 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
285 if (genType != null) {
286 constructGetter(parent, Types.listTypeFor(genType), node);
288 final List<String> listKeys = listKeys(node);
289 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
290 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
291 if (genTOBuilder != null) {
292 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
293 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
294 genTOBuilder.addImplementsType(identifierMarker);
295 genType.addImplementsType(identifiableMarker);
298 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
299 if (!schemaNode.isAugmenting()) {
300 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
305 if (genTOBuilder != null) {
306 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
307 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
308 genTOBuilder.setSUID(prop);
311 typeBuildersToGenTypes(module, genType, genTOBuilder);
315 private void processUsesAugments(final DataNodeContainer node, final Module module) {
316 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
317 for (final UsesNode usesNode : node.getUses()) {
318 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
319 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
320 processUsesAugments(augment, module);
326 * Converts all <b>augmentation</b> of the module to the list
327 * <code>Type</code> objects.
330 * module from which is obtained list of all augmentation objects
331 * to iterate over them
332 * @throws IllegalArgumentException
334 * <li>if the module is null</li>
335 * <li>if the name of module is null</li>
337 * @throws IllegalStateException
338 * if set of augmentations from module is null
340 private void allAugmentsToGenTypes(final Module module) {
341 checkArgument(module != null, "Module reference cannot be NULL.");
342 checkArgument(module.getName() != null, "Module name cannot be NULL.");
343 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
345 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
346 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
347 augmentationToGenTypes(basePackageName, augment, module);
352 * Returns list of <code>AugmentationSchema</code> objects. The objects are
353 * sorted according to the length of their target path from the shortest to
357 * module from which is obtained list of all augmentation objects
358 * @return list of sorted <code>AugmentationSchema</code> objects obtained
359 * from <code>module</code>
360 * @throws IllegalArgumentException
362 * @throws IllegalStateException
363 * if set of module augmentations is null
365 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
366 checkArgument(module != null, "Module reference cannot be NULL.");
367 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
369 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
370 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
371 sortedAugmentations.sort(AUGMENT_COMP);
373 return sortedAugmentations;
377 * Create GeneratedTypeBuilder object from module argument.
380 * Module object from which builder will be created
381 * @return <code>GeneratedTypeBuilder</code> which is internal
382 * representation of the module
383 * @throws IllegalArgumentException
386 private GeneratedTypeBuilder moduleToDataType(final Module module) {
387 checkArgument(module != null, "Module reference cannot be NULL.");
389 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
390 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
391 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
393 addCodegenInformation(moduleDataTypeBuilder, module);
394 return moduleDataTypeBuilder;
398 * Converts all <b>RPCs</b> input and output substatements of the module
399 * to the list of <code>Type</code> objects. In addition are to containers
400 * and lists which belong to input or output also part of returning list.
403 * module from which is obtained set of all rpc objects to
405 * @throws IllegalArgumentException
407 * <li>if the module is null</li>
408 * <li>if the name of module is null</li>
410 * @throws IllegalStateException
411 * if set of rpcs from module is null
413 private void rpcMethodsToGenType(final Module module) {
414 checkArgument(module != null, "Module reference cannot be NULL.");
415 checkArgument(module.getName() != null, "Module name cannot be NULL.");
416 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
417 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
418 if (rpcDefinitions.isEmpty()) {
422 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
423 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
424 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
426 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
428 for (final RpcDefinition rpc : rpcDefinitions) {
430 final String rpcName = BindingMapping.getClassName(rpc.getQName());
431 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
432 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
433 final ContainerSchemaNode input = rpc.getInput();
434 final ContainerSchemaNode output = rpc.getOutput();
436 // Do not refer to annotation class, as it may not be available at runtime
437 method.addAnnotation("javax.annotation", "CheckReturnValue");
439 //in case of implicit RPC input (StatementSource.CONTEXT),
440 // stay compatible (no input argument generated)
441 if (input != null && isExplicitStatement(input)) {
442 processUsesAugments(input, module);
443 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
444 addImplementedInterfaceFromUses(input, inType);
445 inType.addImplementsType(DATA_OBJECT);
446 inType.addImplementsType(augmentable(inType));
447 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
448 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
449 genCtx.get(module).addChildNodeType(input, inType);
450 final GeneratedType inTypeInstance = inType.build();
451 method.addParameter(inTypeInstance, "input");
454 Type outTypeInstance = VOID;
455 //in case of implicit RPC output (StatementSource.CONTEXT),
456 //stay compatible (Future<RpcResult<Void>> return type generated)
457 if (output != null && isExplicitStatement(output)) {
458 processUsesAugments(output, module);
459 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
460 addImplementedInterfaceFromUses(output, outType);
461 outType.addImplementsType(DATA_OBJECT);
462 outType.addImplementsType(augmentable(outType));
463 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
464 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
465 genCtx.get(module).addChildNodeType(output, outType);
466 outTypeInstance = outType.build();
469 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
470 addComment(method, rpc);
471 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
475 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
478 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
479 return node instanceof EffectiveStatement
480 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
484 * Converts all <b>notifications</b> of the module to the list of
485 * <code>Type</code> objects. In addition are to this list added containers
486 * and lists which are part of this notification.
489 * module from which is obtained set of all notification objects
490 * to iterate over them
491 * @throws IllegalArgumentException
493 * <li>if the module equals null</li>
494 * <li>if the name of module equals null</li>
496 * @throws IllegalStateException
497 * if set of notifications from module is null
499 private void notificationsToGenType(final Module module) {
500 checkArgument(module != null, "Module reference cannot be NULL.");
501 checkArgument(module.getName() != null, "Module name cannot be NULL.");
502 final Set<NotificationDefinition> notifications = module.getNotifications();
503 if (notifications.isEmpty()) {
507 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
508 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
509 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
511 for (final NotificationDefinition notification : notifications) {
512 if (notification != null) {
513 processUsesAugments(notification, module);
515 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
516 notification, null, module);
517 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
518 notificationInterface.addImplementsType(NOTIFICATION);
519 genCtx.get(module).addChildNodeType(notification, notificationInterface);
521 // Notification object
522 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
523 notification.getChildNodes());
525 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
526 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
527 .setReturnType(Types.VOID), notification);
531 addCodegenInformation(listenerInterface, module, "notifications", notifications);
532 genCtx.get(module).addTopLevelNodeType(listenerInterface);
536 * Converts all <b>identities</b> of the module to the list of
537 * <code>Type</code> objects.
540 * module from which is obtained set of all identity objects to
543 * schema context only used as input parameter for method
544 * {@link BindingGeneratorImpl#identityToGenType}
547 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
548 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
549 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
551 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
552 for (final IdentitySchemaNode identity : schemaIdentities) {
553 identityToGenType(module, basePackageName, identity, context);
559 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
560 * created transport object builder. If identity contains base identity then
561 * reference to base identity is added to superior identity as its extend.
562 * If identity doesn't contain base identity then only reference to abstract
563 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
564 * BaseIdentity} is added
568 * @param basePackageName
569 * string contains the module package name
571 * IdentitySchemaNode which contains data about identity
573 * SchemaContext which is used to get package and name
574 * information about base of identity
577 private void identityToGenType(final Module module, final String basePackageName,
578 final IdentitySchemaNode identity, final SchemaContext context) {
579 if (identity == null) {
582 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
583 final String genTypeName = BindingMapping.getClassName(identity.getQName());
584 final GeneratedTOBuilder newType = typeProvider.newGeneratedTOBuilder(packageName, genTypeName);
585 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
586 if (baseIdentities.isEmpty()) {
587 final GeneratedTOBuilder gto = typeProvider.newGeneratedTOBuilder(
588 BaseIdentity.class.getPackage().getName(), BaseIdentity.class.getSimpleName());
589 newType.setExtendsType(gto.build());
591 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
592 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
593 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
595 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
596 final GeneratedTransferObject gto = new CodegenGeneratedTOBuilder(returnTypePkgName, returnTypeName)
598 newType.setExtendsType(gto);
600 newType.setAbstract(true);
602 addCodegenInformation(newType, module, identity);
603 newType.setModuleName(module.getName());
604 newType.setSchemaPath(identity.getPath());
606 final QName qname = identity.getQName();
607 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
609 genCtx.get(module).addIdentityType(identity.getQName(), newType);
613 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
615 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
619 * Converts all <b>groupings</b> of the module to the list of
620 * <code>Type</code> objects. Firstly are groupings sorted according mutual
621 * dependencies. At least dependent (independent) groupings are in the list
622 * saved at first positions. For every grouping the record is added to map
623 * {@link ModuleContext#groupings allGroupings}
628 * collection of groupings from which types will be generated
631 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
632 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
633 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
635 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
636 groupingToGenType(basePackageName, grouping, module);
641 * Converts individual grouping to GeneratedType. Firstly generated type
642 * builder is created and every child node of grouping is resolved to the
645 * @param basePackageName
646 * string contains the module package name
648 * GroupingDefinition which contains data about grouping
652 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
653 final Module module) {
654 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
655 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
656 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
657 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
658 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
659 groupingsToGenTypes(module, grouping.getGroupings());
660 processUsesAugments(grouping, module);
664 * Adds enumeration builder created from <code>enumTypeDef</code> to
665 * <code>typeBuilder</code>.
667 * Each <code>enumTypeDef</code> item is added to builder with its name and
671 * EnumTypeDefinition contains enum data
673 * string contains name which will be assigned to enumeration
676 * GeneratedTypeBuilder to which will be enum builder assigned
678 * Module in which type should be generated
679 * @return enumeration builder which contains data from
680 * <code>enumTypeDef</code>
682 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
683 final GeneratedTypeBuilder typeBuilder, final Module module) {
684 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
685 final String enumerationName = BindingMapping.getClassName(enumName);
686 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
687 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
688 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
689 ModuleContext ctx = genCtx.get(module);
690 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
697 * Generates type builder for <code>module</code>.
700 * Module which is source of package name for generated type
703 * string which is added to the module class name representation
705 * @return instance of GeneratedTypeBuilder which represents
706 * <code>module</code>.
707 * @throws IllegalArgumentException
708 * if <code>module</code> is null
710 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
711 checkArgument(module != null, "Module reference cannot be NULL.");
712 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
713 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
715 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(packageName, moduleName);
717 moduleBuilder.setModuleName(moduleName);
718 addCodegenInformation(moduleBuilder, module);
719 return moduleBuilder;
723 * Converts <code>augSchema</code> to list of <code>Type</code> which
724 * contains generated type for augmentation. In addition there are also
725 * generated types for all containers, list and choices which are child of
726 * <code>augSchema</code> node or a generated types for cases are added if
727 * augmented node is choice.
729 * @param augmentPackageName
730 * string with the name of the package to which the augmentation
733 * AugmentationSchema which is contains data about augmentation
734 * (target path, childs...)
737 * @throws IllegalArgumentException
739 * <li>if <code>augmentPackageName</code> equals null</li>
740 * <li>if <code>augSchema</code> equals null</li>
742 * @throws IllegalStateException
743 * if augment target path is null
745 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
746 final Module module) {
747 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
748 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
749 checkState(augSchema.getTargetPath() != null,
750 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
752 processUsesAugments(augSchema, module);
753 final SchemaPath targetPath = augSchema.getTargetPath();
754 SchemaNode targetSchemaNode = null;
756 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
757 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
758 if (targetSchemaNode instanceof DerivableSchemaNode) {
759 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
761 if (targetSchemaNode == null) {
762 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
763 + " in module " + module.getName());
766 if (targetSchemaNode == null) {
767 throw new IllegalArgumentException("augment target not found: " + targetPath);
770 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
771 if (targetTypeBuilder == null) {
772 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
774 if (targetTypeBuilder == null) {
775 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
778 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
779 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
780 targetTypeBuilder.getName());
781 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
784 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.build(),
785 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
789 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
790 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
791 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
792 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
793 checkState(augSchema.getTargetPath() != null,
794 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
796 processUsesAugments(augSchema, module);
797 final SchemaPath targetPath = augSchema.getTargetPath();
798 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
799 if (targetSchemaNode == null) {
800 throw new IllegalArgumentException("augment target not found: " + targetPath);
803 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
804 if (targetTypeBuilder == null) {
805 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
807 if (targetTypeBuilder == null) {
808 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
811 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
812 String packageName = augmentPackageName;
813 if (usesNodeParent instanceof SchemaNode) {
814 packageName = packageNameForAugmentedGeneratedType(augmentPackageName,
815 ((SchemaNode) usesNodeParent).getPath());
817 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.build(),
820 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.build(),
821 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
826 * Convenient method to find node added by uses statement.
830 * @param parentUsesNode
831 * parent of uses node
832 * @return node from its original location in grouping
834 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
835 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
837 if (!(targetGrouping instanceof GroupingDefinition)) {
838 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
841 SchemaNode result = targetGrouping;
842 for (final QName node : targetPath.getPathFromRoot()) {
843 if (result instanceof DataNodeContainer) {
844 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
845 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
846 } else if (result instanceof ChoiceSchemaNode) {
847 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
850 if (result == null) {
854 if (result instanceof DerivableSchemaNode) {
855 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
856 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
857 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
858 result = originalNode.get();
862 if (result instanceof DataSchemaNode) {
863 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
864 if (resultDataSchemaNode.isAddedByUses()) {
865 // The original node is required, but we have only the copy of
866 // the original node.
867 // Maybe this indicates a bug in Yang parser.
868 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
871 return resultDataSchemaNode;
874 throw new IllegalStateException(
875 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
880 * Returns a generated type builder for an augmentation.
882 * The name of the type builder is equal to the name of augmented node with
883 * serial number as suffix.
887 * @param augmentPackageName
888 * string with contains the package name to which the augment
890 * @param basePackageName
891 * string with the package name to which the augmented node
893 * @param targetTypeRef
896 * augmentation schema which contains data about the child nodes
897 * and uses of augment
898 * @return generated type builder for augment
900 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
901 final String basePackageName, final Type targetTypeRef, final AugmentationSchemaNode augSchema) {
902 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
903 if (augmentBuilders == null) {
904 augmentBuilders = new HashMap<>();
905 genTypeBuilders.put(augmentPackageName, augmentBuilders);
907 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
910 if (augIdentifier != null) {
911 augTypeName = BindingMapping.getClassName(augIdentifier);
913 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
916 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(augmentPackageName,
919 augTypeBuilder.addImplementsType(DATA_OBJECT);
920 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
921 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
922 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
924 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
925 augmentBuilders.put(augTypeName, augTypeBuilder);
927 if (!augSchema.getChildNodes().isEmpty()) {
928 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
931 genCtx.get(module).addAugmentType(augTypeBuilder);
932 return augTypeBuilder;
937 * @param unknownSchemaNodes
938 * @return nodeParameter of UnknownSchemaNode
940 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
941 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
942 final QName nodeType = unknownSchemaNode.getNodeType();
943 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
944 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
945 return unknownSchemaNode.getNodeParameter();
952 * Returns first unique name for the augment generated type builder. The
953 * generated type builder name for augment consists from name of augmented
954 * node and serial number of its augmentation.
957 * map of builders which were created in the package to which the
958 * augmentation belongs
960 * string with name of augmented node
961 * @return string with unique name for augmentation builder
963 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
965 if (builders != null) {
966 while (builders.containsKey(genTypeName + index)) {
970 return genTypeName + index;
974 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
975 * node for which <code>typeBuilder</code> was created.
977 * The subnodes aren't mapped to the methods if they are part of grouping or
978 * augment (in this case are already part of them).
982 * @param basePackageName
983 * string contains the module package name
985 * generated type builder which represents any node. The subnodes
986 * of this node are added to the <code>typeBuilder</code> as
987 * methods. The subnode can be of type leaf, leaf-list, list,
992 * set of data schema nodes which are the children of the node
993 * for which <code>typeBuilder</code> was created
994 * @return generated type builder which is the same builder as input
995 * parameter. The getter methods (representing child nodes) could be
998 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
999 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1000 if (schemaNodes != null && parent != null) {
1001 for (final DataSchemaNode schemaNode : schemaNodes) {
1002 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1003 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1011 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1012 * node for which <code>typeBuilder</code> was created.
1016 * @param basePackageName
1017 * string contains the module package name
1018 * @param typeBuilder
1019 * generated type builder which represents any node. The subnodes
1020 * of this node are added to the <code>typeBuilder</code> as
1021 * methods. The subnode can be of type leaf, leaf-list, list,
1022 * container, choice.
1025 * @param schemaNodes
1026 * set of data schema nodes which are the children of the node
1027 * for which <code>typeBuilder</code> was created
1028 * @return generated type builder which is the same object as the input
1029 * parameter <code>typeBuilder</code>. The getter method could be
1032 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1033 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1034 final Iterable<DataSchemaNode> schemaNodes) {
1035 if (schemaNodes != null && typeBuilder != null) {
1036 for (final DataSchemaNode schemaNode : schemaNodes) {
1037 if (!schemaNode.isAugmenting()) {
1038 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1046 * Adds to <code>typeBuilder</code> a method which is derived from
1047 * <code>schemaNode</code>.
1049 * @param basePackageName
1050 * string with the module package name
1052 * data schema node which is added to <code>typeBuilder</code> as
1054 * @param typeBuilder
1055 * generated type builder to which is <code>schemaNode</code>
1056 * added as a method.
1062 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1063 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1064 if (node != null && typeBuilder != null) {
1065 if (node instanceof LeafSchemaNode) {
1066 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1067 } else if (node instanceof LeafListSchemaNode) {
1068 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1069 } else if (node instanceof ContainerSchemaNode) {
1070 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1071 } else if (node instanceof ListSchemaNode) {
1072 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1073 } else if (node instanceof ChoiceSchemaNode) {
1074 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1076 // TODO: anyxml not yet supported
1077 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1078 typeBuilder.getFullyQualifiedName());
1084 * Converts <code>choiceNode</code> to the list of generated types for
1085 * choice and its cases.
1087 * The package names for choice and for its cases are created as
1088 * concatenation of the module package (<code>basePackageName</code>) and
1089 * names of all parents node.
1093 * @param basePackageName
1094 * string with the module package name
1098 * choice node which is mapped to generated type. Also child
1099 * nodes - cases are mapped to generated types.
1100 * @throws IllegalArgumentException
1102 * <li>if <code>basePackageName</code> is null</li>
1103 * <li>if <code>choiceNode</code> is null</li>
1106 private void choiceToGeneratedType(final Module module, final String basePackageName,
1107 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1108 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1109 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1111 if (!choiceNode.isAddedByUses()) {
1112 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1113 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1114 constructGetter(parent, choiceTypeBuilder, choiceNode);
1115 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1116 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1117 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1118 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.build(), choiceNode);
1123 * Converts <code>caseNodes</code> set to list of corresponding generated
1126 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1127 * created generated type builder. The package names for the builder is
1128 * created as concatenation of the module package (
1129 * <code>basePackageName</code>) and names of all parents nodes of the
1130 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1131 * between every case builder and <i>choice</i> type
1135 * @param basePackageName
1136 * string with the module package name
1137 * @param refChoiceType
1138 * type which represents superior <i>case</i>
1140 * choice case node which is mapped to generated type
1141 * @throws IllegalArgumentException
1143 * <li>if <code>basePackageName</code> equals null</li>
1144 * <li>if <code>refChoiceType</code> equals null</li>
1145 * <li>if <code>caseNodes</code> equals null</li>
1148 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1149 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1150 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1151 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1152 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1154 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1155 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1156 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1157 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
1159 caseTypeBuilder.addImplementsType(refChoiceType);
1160 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1161 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1162 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1163 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1164 if (caseChildNodes != null) {
1165 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1167 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1168 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1170 if (parent instanceof AugmentationSchemaNode) {
1171 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1172 final SchemaPath targetPath = augSchema.getTargetPath();
1173 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1174 if (targetSchemaNode instanceof DataSchemaNode
1175 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1176 if (targetSchemaNode instanceof DerivableSchemaNode) {
1177 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1180 if (targetSchemaNode == null) {
1181 throw new IllegalStateException(
1182 "Failed to find target node from grouping for augmentation " + augSchema
1183 + " in module " + module.getName());
1186 parent = targetSchemaNode;
1189 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1190 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1191 if (childOfType == null) {
1192 childOfType = findGroupingByPath(parent.getPath());
1194 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1196 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1201 processUsesAugments(caseNode, module);
1206 * Generates list of generated types for all the cases of a choice which are
1207 * added to the choice through the augment.
1211 * @param basePackageName
1212 * string contains name of package to which augment belongs. If
1213 * an augmented choice is from an other package (pcg1) than an
1214 * augmenting choice (pcg2) then case's of the augmenting choice
1215 * will belong to pcg2.
1217 * Type which represents target choice
1219 * node which represents target choice
1220 * @param augmentedNodes
1221 * set of choice case nodes for which is checked if are/aren't
1222 * added to choice through augmentation
1223 * @throws IllegalArgumentException
1225 * <li>if <code>basePackageName</code> is null</li>
1226 * <li>if <code>targetType</code> is null</li>
1227 * <li>if <code>augmentedNodes</code> is null</li>
1230 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1231 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1232 final DataNodeContainer usesNodeParent) {
1233 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1234 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1235 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1237 for (final DataSchemaNode caseNode : augmentedNodes) {
1238 if (caseNode != null) {
1239 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1240 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1241 caseTypeBuilder.addImplementsType(targetType);
1244 final SchemaPath nodeSp = targetNode.getPath();
1245 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1247 GeneratedTypeBuilder childOfType = null;
1248 if (parent instanceof Module) {
1249 childOfType = genCtx.get(parent).getModuleNode();
1250 } else if (parent instanceof CaseSchemaNode) {
1251 childOfType = findCaseByPath(parent.getPath());
1252 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1253 childOfType = findChildNodeByPath(parent.getPath());
1254 } else if (parent instanceof GroupingDefinition) {
1255 childOfType = findGroupingByPath(parent.getPath());
1258 if (childOfType == null) {
1259 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1262 CaseSchemaNode node = null;
1263 final String caseLocalName = caseNode.getQName().getLocalName();
1264 if (caseNode instanceof CaseSchemaNode) {
1265 node = (CaseSchemaNode) caseNode;
1266 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1267 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1268 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1269 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1270 ().getLocalName())) {
1271 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1276 node = findNamedCase(targetNode, caseLocalName);
1278 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1279 if (childNodes != null) {
1280 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1282 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1283 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1288 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1289 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1290 return cases.isEmpty() ? null : cases.get(0);
1293 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1294 // New parser with encapsulated type
1295 if (leaf.getPath().equals(type.getPath())) {
1299 // Embedded type definition with new parser. Also takes care of the old parser with bits
1300 if (leaf.getPath().equals(type.getPath().getParent())) {
1307 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1308 final List<PatternConstraint> patternConstraints) {
1309 if (!patternConstraints.isEmpty()) {
1310 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1311 .append(BindingMapping.getPropertyName(leafName).toUpperCase());
1312 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1313 typeProvider.resolveRegExpressions(patternConstraints));
1318 * Converts <code>leaf</code> to the getter method which is added to
1319 * <code>typeBuilder</code>.
1321 * @param typeBuilder
1322 * generated type builder to which is added getter method as
1323 * <code>leaf</code> mapping
1325 * leaf schema node which is mapped as getter method which is
1326 * added to <code>typeBuilder</code>
1328 * Module in which type was defined
1329 * @return boolean value
1331 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1333 * <li>true - in other cases</li>
1336 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1337 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1341 final Module parentModule = findParentModule(schemaContext, leaf);
1342 Type returnType = null;
1344 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1345 if (isInnerType(leaf, typeDef)) {
1346 if (typeDef instanceof EnumTypeDefinition) {
1347 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1348 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1349 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1350 typeBuilder, module);
1351 if (enumBuilder != null) {
1352 returnType = enumBuilder.toInstance(typeBuilder);
1354 typeProvider.putReferencedType(leaf.getPath(), returnType);
1355 } else if (typeDef instanceof UnionTypeDefinition) {
1356 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1357 if (genTOBuilder != null) {
1358 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1359 // Store the inner type within the union so that we can find the reference for it
1360 genCtx.get(module).addInnerTypedefType(typeDef.getPath(), returnType);
1362 } else if (typeDef instanceof BitsTypeDefinition) {
1363 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1364 if (genTOBuilder != null) {
1365 returnType = genTOBuilder.build();
1368 // It is constrained version of already declared type (inner declared type exists,
1369 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1370 // In order to get proper class we need to look up closest derived type
1371 // and apply restrictions from leaf type
1372 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1373 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1375 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1378 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1379 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1380 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1383 if (returnType == null) {
1387 if (typeDef instanceof EnumTypeDefinition) {
1388 typeProvider.putReferencedType(leaf.getPath(), returnType);
1391 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1392 processContextRefExtension(leaf, getter, parentModule);
1396 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1397 // Returns DerivedType in case of new parser.
1398 final TypeDefinition<?> baseType = typeDef.getBaseType();
1399 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1402 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1403 final Module module) {
1404 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1405 final QName nodeType = node.getNodeType();
1406 if ("context-reference".equals(nodeType.getLocalName())) {
1407 final String nodeParam = node.getNodeParameter();
1408 IdentitySchemaNode identity = null;
1409 String basePackageName = null;
1410 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1411 final Iterator<String> iterator = splittedElement.iterator();
1412 final int length = Iterables.size(splittedElement);
1414 identity = findIdentityByName(module.getIdentities(), iterator.next());
1415 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1416 } else if (length == 2) {
1417 final String prefix = iterator.next();
1418 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1419 if (dependentModule == null) {
1420 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1423 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1424 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1426 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1429 if (identity == null) {
1430 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1434 final Class<RoutingContext> clazz = RoutingContext.class;
1435 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1436 clazz.getSimpleName());
1437 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1438 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1439 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1444 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1445 for (final IdentitySchemaNode id : identities) {
1446 if (id.getQName().getLocalName().equals(name)) {
1453 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1454 for (final ModuleImport imp : imports) {
1455 if (imp.getPrefix().equals(prefix)) {
1456 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1462 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1463 final boolean isReadOnly, final Module module) {
1464 if (leaf != null && toBuilder != null) {
1466 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1467 if (typeDef instanceof UnionTypeDefinition) {
1468 // GeneratedType for this type definition should have be already created
1469 final QName qname = typeDef.getQName();
1470 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1471 final ModuleContext mc = genCtx.get(unionModule);
1472 returnType = mc.getTypedefs().get(typeDef.getPath());
1473 if (returnType == null) {
1474 // This may still be an inner type, try to find it
1475 returnType = mc.getInnerType(typeDef.getPath());
1477 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1478 // Annonymous enumeration (already generated, since it is inherited via uses).
1479 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1480 QName qname = originalLeaf.getQName();
1481 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
1482 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1484 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1486 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1492 * Converts <code>leaf</code> schema node to property of generated TO
1496 * generated TO builder to which is <code>leaf</code> added as
1499 * leaf schema node which is added to <code>toBuilder</code> as
1504 * boolean value which says if leaf property is|isn't read only
1505 * @return boolean value
1507 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1508 * name equals null or if leaf is added by <i>uses</i>.</li>
1509 * <li>true - other cases</li>
1512 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1513 final Type returnType, final boolean isReadOnly) {
1514 if (returnType == null) {
1517 final String leafName = leaf.getQName().getLocalName();
1518 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1519 propBuilder.setReadOnly(isReadOnly);
1520 propBuilder.setReturnType(returnType);
1521 addComment(propBuilder, leaf);
1523 toBuilder.addEqualsIdentity(propBuilder);
1524 toBuilder.addHashIdentity(propBuilder);
1525 toBuilder.addToStringProperty(propBuilder);
1530 * Converts <code>node</code> leaf list schema node to getter method of
1531 * <code>typeBuilder</code>.
1533 * @param typeBuilder
1534 * generated type builder to which is <code>node</code> added as
1537 * leaf list schema node which is added to
1538 * <code>typeBuilder</code> as getter method
1539 * @param module module
1540 * @return boolean value
1542 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1543 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1544 * <li>false - other cases</li>
1547 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1548 final Module module) {
1549 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1553 final QName nodeName = node.getQName();
1555 final TypeDefinition<?> typeDef = node.getType();
1556 final Module parentModule = findParentModule(schemaContext, node);
1558 Type returnType = null;
1559 if (typeDef.getBaseType() == null) {
1560 if (typeDef instanceof EnumTypeDefinition) {
1561 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1562 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1563 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1564 typeBuilder, module);
1565 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1566 typeProvider.putReferencedType(node.getPath(), returnType);
1567 } else if (typeDef instanceof UnionTypeDefinition) {
1568 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1569 if (genTOBuilder != null) {
1570 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1572 } else if (typeDef instanceof BitsTypeDefinition) {
1573 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1574 returnType = genTOBuilder.build();
1576 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1577 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1578 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1581 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1582 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1583 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1586 final ParameterizedType listType = Types.listTypeFor(returnType);
1587 constructGetter(typeBuilder, listType, node);
1591 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1592 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1593 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getPackageName(),
1594 genTOBuilder.getName());
1596 addCodegenInformation(returnType, parentModule, typeDef);
1597 returnType.setSchemaPath(typeDef.getPath());
1598 returnType.setModuleName(parentModule.getName());
1600 genTOBuilder.setTypedef(true);
1601 genTOBuilder.setIsUnion(true);
1602 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1606 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1609 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1610 method.setReturnType(returnType);
1611 method.addParameter(Types.STRING, "defaultValue");
1612 method.setAccessModifier(AccessModifier.PUBLIC);
1613 method.setStatic(true);
1615 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1616 if (types == null) {
1617 typeProvider.getAdditionalTypes().put(parentModule,
1618 Sets.newHashSet(unionBuilder.build()));
1620 types.add(unionBuilder.build());
1622 return returnType.build();
1625 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1626 final GeneratedTypeBuilder typeBuilder) {
1627 final String outerCls = Types.getOuterClassName(genTOBuilder);
1628 final StringBuilder name;
1629 if (outerCls != null) {
1630 name = new StringBuilder(outerCls);
1632 name = new StringBuilder();
1634 name.append(genTOBuilder.getName());
1635 name.append("Builder");
1636 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(typeBuilder.getPackageName(),
1638 unionBuilder.setIsUnionBuilder(true);
1639 return unionBuilder;
1642 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1643 final Module module) {
1644 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1648 * Instantiates generated type builder with <code>packageName</code> and
1649 * <code>schemaNode</code>.
1651 * The new builder always implements
1652 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1653 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1654 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1656 * If <code>schemaNode</code> is instance of
1657 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1658 * DataNodeContainer} it can also implement nodes which are specified in
1661 * @param packageName
1662 * string with the name of the package to which
1663 * <code>schemaNode</code> belongs.
1665 * schema node for which is created generated type builder
1667 * parent type (can be null)
1668 * @return generated type builder <code>schemaNode</code>
1670 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1671 final Type parent, final Module module) {
1672 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1673 if (parent == null) {
1674 it.addImplementsType(DATA_OBJECT);
1676 it.addImplementsType(BindingTypes.childOf(parent));
1678 if (!(schemaNode instanceof GroupingDefinition)) {
1679 it.addImplementsType(augmentable(it));
1682 if (schemaNode instanceof DataNodeContainer) {
1683 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1684 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1691 * Wraps the calling of the same overloaded method.
1693 * @param packageName
1694 * string with the package name to which returning generated type
1697 * schema node which provide data about the schema node name
1698 * @return generated type builder for <code>schemaNode</code>
1700 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1701 return addRawInterfaceDefinition(packageName, schemaNode, "");
1705 * Returns reference to generated type builder for specified
1706 * <code>schemaNode</code> with <code>packageName</code>.
1708 * Firstly the generated type builder is searched in
1709 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1710 * found it is created and added to <code>genTypeBuilders</code>.
1712 * @param packageName
1713 * string with the package name to which returning generated type
1716 * schema node which provide data about the schema node name
1718 * return type name prefix
1719 * @return generated type builder for <code>schemaNode</code>
1720 * @throws IllegalArgumentException
1722 * <li>if <code>schemaNode</code> is null</li>
1723 * <li>if <code>packageName</code> is null</li>
1724 * <li>if QName of schema node is null</li>
1725 * <li>if schemaNode name is null</li>
1729 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1730 final String prefix) {
1731 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1732 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1733 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1734 final String schemaNodeName = schemaNode.getQName().getLocalName();
1735 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1738 if (prefix == null) {
1739 genTypeName = BindingMapping.getClassName(schemaNodeName);
1741 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1744 // FIXME: Validation of name conflict
1745 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(packageName, genTypeName);
1746 final Module module = findParentModule(schemaContext, schemaNode);
1747 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1749 addCodegenInformation(newType, module, schemaNode);
1750 newType.setSchemaPath(schemaNode.getPath());
1751 newType.setModuleName(module.getName());
1753 if (!genTypeBuilders.containsKey(packageName)) {
1754 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1755 builders.put(genTypeName, newType);
1756 genTypeBuilders.put(packageName, builders);
1758 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1759 if (!builders.containsKey(genTypeName)) {
1760 builders.put(genTypeName, newType);
1767 * Creates the name of the getter method name from <code>localName</code>.
1770 * string with the name of the getter method
1773 * @return string with the name of the getter method for
1774 * <code>methodName</code> in JAVA method format
1776 public static String getterMethodName(final String localName, final Type returnType) {
1777 final StringBuilder method = new StringBuilder();
1778 if (BOOLEAN.equals(returnType)) {
1779 method.append("is");
1781 method.append("get");
1783 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1784 method.append(name);
1785 return method.toString();
1789 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1791 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1792 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1794 * @param interfaceBuilder generated type builder for which the getter method should be created
1795 * @param returnType type which represents the return type of the getter method
1796 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1797 * @param comment string with comment for the getter method
1798 * @param status status from yang file, for deprecated annotation
1799 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1801 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1802 final SchemaNode node) {
1803 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1804 getterMethodName(node.getQName().getLocalName(), returnType));
1805 getMethod.setReturnType(returnType);
1807 if (node.getStatus() == Status.DEPRECATED) {
1808 getMethod.addAnnotation("", "Deprecated");
1810 addComment(getMethod, node);
1816 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1817 * or to <code>genTOBuilder</code> as property.
1819 * @param basePackageName
1820 * string contains the module package name
1822 * data schema node which should be added as getter method to
1823 * <code>typeBuilder</code> or as a property to
1824 * <code>genTOBuilder</code> if is part of the list key
1825 * @param typeBuilder
1826 * generated type builder for the list schema node
1827 * @param genTOBuilder
1828 * generated TO builder for the list keys
1830 * list of string which contains names of the list keys
1833 * @throws IllegalArgumentException
1835 * <li>if <code>schemaNode</code> equals null</li>
1836 * <li>if <code>typeBuilder</code> equals null</li>
1839 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1840 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1841 final Module module) {
1842 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1843 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1845 if (schemaNode instanceof LeafSchemaNode) {
1846 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1847 final String leafName = leaf.getQName().getLocalName();
1848 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, module);
1849 if (listKeys.contains(leafName)) {
1851 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1853 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1856 } else if (!schemaNode.isAddedByUses()) {
1857 if (schemaNode instanceof LeafListSchemaNode) {
1858 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1859 } else if (schemaNode instanceof ContainerSchemaNode) {
1860 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1861 } else if (schemaNode instanceof ChoiceSchemaNode) {
1862 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1863 } else if (schemaNode instanceof ListSchemaNode) {
1864 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1869 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1870 final GeneratedTOBuilder genTOBuilder) {
1871 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1873 if (genTOBuilder != null) {
1874 final GeneratedTransferObject genTO = genTOBuilder.build();
1876 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1877 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1878 getMethod.setReturnType(genTO);
1879 getMethod.setComment("Returns Primary Key of Yang List Type");
1880 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1885 * Selects the names of the list keys from <code>list</code> and returns
1886 * them as the list of the strings
1889 * of string with names of the list keys
1890 * @return list of string which represents names of the list keys. If the
1891 * <code>list</code> contains no keys then the empty list is
1894 private static List<String> listKeys(final ListSchemaNode list) {
1895 final List<String> listKeys = new ArrayList<>();
1897 final List<QName> keyDefinition = list.getKeyDefinition();
1898 if (keyDefinition != null) {
1899 for (final QName keyDef : keyDefinition) {
1900 listKeys.add(keyDef.getLocalName());
1907 * Generates for the <code>list</code> which contains any list keys special
1908 * generated TO builder.
1910 * @param packageName
1911 * string with package name to which the list belongs
1913 * list schema node which is source of data about the list name
1914 * @return generated TO builder which represents the keys of the
1915 * <code>list</code> or null if <code>list</code> is null or list of
1916 * key definitions is null or empty.
1918 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1919 GeneratedTOBuilder genTOBuilder = null;
1920 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1921 final String listName = list.getQName().getLocalName() + "Key";
1922 final String genTOName = BindingMapping.getClassName(listName);
1923 genTOBuilder = typeProvider.newGeneratedTOBuilder(packageName, genTOName);
1925 return genTOBuilder;
1929 * Builds generated TO builders for <code>typeDef</code> of type
1930 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
1931 * also added to <code>typeBuilder</code> as enclosing transfer object.
1933 * If more then one generated TO builder is created for enclosing then all
1934 * of the generated TO builders are added to <code>typeBuilder</code> as
1935 * enclosing transfer objects.
1938 * type definition which can be of type <code>UnionType</code> or
1939 * <code>BitsTypeDefinition</code>
1940 * @param typeBuilder
1941 * generated type builder to which is added generated TO created
1942 * from <code>typeDef</code>
1944 * string with name for generated TO builder
1945 * @param parentModule
1947 * @return generated TO builder for <code>typeDef</code>
1949 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1950 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1951 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1952 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1953 final String packageName = typeBuilder.getFullyQualifiedName();
1954 if (typeDef instanceof UnionTypeDefinition) {
1955 final List<GeneratedTOBuilder> types = typeProvider
1956 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
1957 classNameFromLeaf, leaf);
1958 genTOBuilders.addAll(types);
1960 GeneratedTOBuilder resultTOBuilder;
1961 if (types.isEmpty()) {
1962 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1964 resultTOBuilder = types.remove(0);
1965 for (final GeneratedTOBuilder genTOBuilder : types) {
1966 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1969 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1970 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1971 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1972 resultTOBuilder.addHashIdentity(genPropBuilder);
1973 resultTOBuilder.addToStringProperty(genPropBuilder);
1975 } else if (typeDef instanceof BitsTypeDefinition) {
1976 genTOBuilders.add(typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1977 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1979 if (!genTOBuilders.isEmpty()) {
1980 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1981 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1983 return genTOBuilders.get(0);
1990 * Adds the implemented types to type builder.
1992 * The method passes through the list of <i>uses</i> in
1993 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1994 * generated type from {@link ModuleContext#groupings
1995 * allGroupings} which is added as <i>implements type</i> to
1996 * <code>builder</code>
1998 * @param dataNodeContainer
1999 * element which contains the list of used YANG groupings
2001 * builder to which are added implemented types according to
2002 * <code>dataNodeContainer</code>
2003 * @return generated type builder with all implemented types
2005 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2006 final GeneratedTypeBuilder builder) {
2007 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2008 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2009 if (genType == null) {
2010 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2011 + builder.getName());
2014 builder.addImplementsType(genType);
2019 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2020 for (final ModuleContext ctx : genCtx.values()) {
2021 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2022 if (result != null) {
2029 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2030 for (final ModuleContext ctx : genCtx.values()) {
2031 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2032 if (result != null) {
2039 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2040 for (final ModuleContext ctx : genCtx.values()) {
2041 final GeneratedTypeBuilder result = ctx.getCase(path);
2042 if (result != null) {
2049 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2050 if (status == Status.DEPRECATED) {
2051 builder.addAnnotation("", "Deprecated");