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.encodeAngleBrackets;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
24 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
25 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
26 import static org.opendaylight.mdsal.binding.model.util.Types.VOID;
27 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
30 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
32 import com.google.common.base.Splitter;
33 import com.google.common.collect.Iterables;
34 import com.google.common.collect.Sets;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Comparator;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.List;
42 import java.util.Optional;
44 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
45 import org.opendaylight.mdsal.binding.model.api.Constant;
46 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
47 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
48 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
49 import org.opendaylight.mdsal.binding.model.api.Restrictions;
50 import org.opendaylight.mdsal.binding.model.api.Type;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
53 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
54 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
55 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
59 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
60 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
61 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
62 import org.opendaylight.mdsal.binding.model.util.Types;
63 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
64 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
65 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTypeBuilderImpl;
66 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
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.UnionTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
105 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
106 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
107 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
108 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
109 import org.slf4j.Logger;
110 import org.slf4j.LoggerFactory;
112 abstract class AbstractTypeGenerator {
113 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
114 private static final Splitter COLON_SPLITTER = Splitter.on(':');
117 * Comparator based on augment target path.
119 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
120 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
121 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
123 while (thisIt.hasNext()) {
124 if (!otherIt.hasNext()) {
128 final int comp = thisIt.next().compareTo(otherIt.next());
134 return otherIt.hasNext() ? -1 : 0;
138 * Constant with the concrete name of identifier.
140 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
143 * Constant with the concrete name of namespace.
145 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
147 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
150 * Outer key represents the package name. Outer value represents map of all
151 * builders in the same package. Inner key represents the schema node name
152 * (in JAVA class/interface name format). Inner value represents instance of
153 * builder for schema node specified in key part.
155 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
158 * Provide methods for converting YANG types to JAVA types.
160 private final TypeProviderImpl typeProvider;
163 * Holds reference to schema context to resolve data of augmented element
164 * when creating augmentation builder
166 private final SchemaContext schemaContext;
168 AbstractTypeGenerator(final SchemaContext context, final TypeProviderImpl typeProvider) {
169 this.schemaContext = requireNonNull(context);
170 this.typeProvider = requireNonNull(typeProvider);
172 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
173 for (final Module contextModule : contextModules) {
174 moduleToGenTypes(contextModule, schemaContext);
176 for (final Module contextModule : contextModules) {
177 allAugmentsToGenTypes(contextModule);
181 final Collection<ModuleContext> moduleContexts() {
182 return genCtx.values();
185 final ModuleContext moduleContext(final Module module) {
186 return checkNotNull(genCtx.get(module), "Module context not found for module %s", module);
189 final TypeProviderImpl typeProvider() {
193 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
195 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
197 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
198 Set<? extends SchemaNode> nodes);
200 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
202 private void moduleToGenTypes(final Module m, final SchemaContext context) {
203 genCtx.put(m, new ModuleContext());
204 allTypeDefinitionsToGenTypes(m);
205 groupingsToGenTypes(m, m.getGroupings());
206 rpcMethodsToGenType(m);
207 allIdentitiesToGenTypes(m, context);
208 notificationsToGenType(m);
210 if (!m.getChildNodes().isEmpty()) {
211 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
212 genCtx.get(m).addModuleNode(moduleType);
213 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
214 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
219 * Converts all extended type definitions of module to the list of
220 * <code>Type</code> objects.
223 * module from which is obtained set of type definitions
224 * @throws IllegalArgumentException
226 * <li>if module is null</li>
227 * <li>if name of module is null</li>
229 * @throws IllegalStateException
230 * if set of type definitions from module is null
232 private void allTypeDefinitionsToGenTypes(final Module module) {
233 checkArgument(module != null, "Module reference cannot be NULL.");
234 checkArgument(module.getName() != null, "Module name cannot be NULL.");
235 final DataNodeIterator it = new DataNodeIterator(module);
236 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
237 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
239 for (final TypeDefinition<?> typedef : typeDefinitions) {
240 if (typedef != null) {
241 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,
244 final ModuleContext ctx = genCtx.get(module);
245 ctx.addTypedefType(typedef.getPath(), type);
246 ctx.addTypeToSchema(type,typedef);
252 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
253 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
254 if (node.isAugmenting() || node.isAddedByUses()) {
257 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
258 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
259 annotateDeprecatedIfNecessary(node.getStatus(), genType);
261 genType.setModuleName(module.getName());
262 addCodegenInformation(genType, module, node);
263 genType.setSchemaPath(node.getPath().getPathFromRoot());
264 if (node instanceof DataNodeContainer) {
265 genCtx.get(module).addChildNodeType(node, genType);
266 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
267 processUsesAugments((DataNodeContainer) node, module);
272 private void containerToGenType(final Module module, final String basePackageName,
273 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
274 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
275 if (genType != null) {
276 constructGetter(parent, genType, node);
277 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
281 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
282 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
283 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
284 if (genType != null) {
285 constructGetter(parent, Types.listTypeFor(genType), node);
287 final List<String> listKeys = listKeys(node);
288 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
289 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
290 if (genTOBuilder != null) {
291 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
292 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
293 genTOBuilder.addImplementsType(identifierMarker);
294 genType.addImplementsType(identifiableMarker);
297 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
298 if (!schemaNode.isAugmenting()) {
299 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
304 if (genTOBuilder != null) {
305 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
306 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
307 genTOBuilder.setSUID(prop);
310 typeBuildersToGenTypes(module, genType, genTOBuilder);
314 private void processUsesAugments(final DataNodeContainer node, final Module module) {
315 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
316 for (final UsesNode usesNode : node.getUses()) {
317 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
318 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
319 processUsesAugments(augment, module);
325 * Converts all <b>augmentation</b> of the module to the list
326 * <code>Type</code> objects.
329 * module from which is obtained list of all augmentation objects
330 * to iterate over them
331 * @throws IllegalArgumentException
333 * <li>if the module is null</li>
334 * <li>if the name of module is null</li>
336 * @throws IllegalStateException
337 * if set of augmentations from module is null
339 private void allAugmentsToGenTypes(final Module module) {
340 checkArgument(module != null, "Module reference cannot be NULL.");
341 checkArgument(module.getName() != null, "Module name cannot be NULL.");
342 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
344 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
345 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
346 augmentationToGenTypes(basePackageName, augment, module);
351 * Returns list of <code>AugmentationSchema</code> objects. The objects are
352 * sorted according to the length of their target path from the shortest to
356 * module from which is obtained list of all augmentation objects
357 * @return list of sorted <code>AugmentationSchema</code> objects obtained
358 * from <code>module</code>
359 * @throws IllegalArgumentException
361 * @throws IllegalStateException
362 * if set of module augmentations is null
364 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
365 checkArgument(module != null, "Module reference cannot be NULL.");
366 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
368 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
369 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
370 sortedAugmentations.sort(AUGMENT_COMP);
372 return sortedAugmentations;
376 * Create GeneratedTypeBuilder object from module argument.
379 * Module object from which builder will be created
380 * @return <code>GeneratedTypeBuilder</code> which is internal
381 * representation of the module
382 * @throws IllegalArgumentException
385 private GeneratedTypeBuilder moduleToDataType(final Module module) {
386 checkArgument(module != null, "Module reference cannot be NULL.");
388 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
389 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
390 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
392 addCodegenInformation(moduleDataTypeBuilder, module);
393 return moduleDataTypeBuilder;
397 * Converts all <b>RPCs</b> input and output substatements of the module
398 * to the list of <code>Type</code> objects. In addition are to containers
399 * and lists which belong to input or output also part of returning list.
402 * module from which is obtained set of all rpc objects to
404 * @throws IllegalArgumentException
406 * <li>if the module is null</li>
407 * <li>if the name of module is null</li>
409 * @throws IllegalStateException
410 * if set of rpcs from module is null
412 private void rpcMethodsToGenType(final Module module) {
413 checkArgument(module != null, "Module reference cannot be NULL.");
414 checkArgument(module.getName() != null, "Module name cannot be NULL.");
415 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
416 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
417 if (rpcDefinitions.isEmpty()) {
421 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
422 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
423 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
425 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
427 for (final RpcDefinition rpc : rpcDefinitions) {
429 final String rpcName = BindingMapping.getClassName(rpc.getQName());
430 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
431 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
432 final ContainerSchemaNode input = rpc.getInput();
433 final ContainerSchemaNode output = rpc.getOutput();
435 // Do not refer to annotation class, as it may not be available at runtime
436 method.addAnnotation("javax.annotation", "CheckReturnValue");
438 //in case of implicit RPC input (StatementSource.CONTEXT),
439 // stay compatible (no input argument generated)
440 if (input != null && isExplicitStatement(input)) {
441 processUsesAugments(input, module);
442 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
443 addImplementedInterfaceFromUses(input, inType);
444 inType.addImplementsType(DATA_OBJECT);
445 inType.addImplementsType(augmentable(inType));
446 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
447 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
448 genCtx.get(module).addChildNodeType(input, inType);
449 final GeneratedType inTypeInstance = inType.toInstance();
450 method.addParameter(inTypeInstance, "input");
453 Type outTypeInstance = VOID;
454 //in case of implicit RPC output (StatementSource.CONTEXT),
455 //stay compatible (Future<RpcResult<Void>> return type generated)
456 if (output != null && isExplicitStatement(output)) {
457 processUsesAugments(output, module);
458 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
459 addImplementedInterfaceFromUses(output, outType);
460 outType.addImplementsType(DATA_OBJECT);
461 outType.addImplementsType(augmentable(outType));
462 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
463 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
464 genCtx.get(module).addChildNodeType(output, outType);
465 outTypeInstance = outType.toInstance();
468 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
469 addComment(method, rpc);
470 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
474 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
477 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
478 return node instanceof EffectiveStatement
479 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
483 * Converts all <b>notifications</b> of the module to the list of
484 * <code>Type</code> objects. In addition are to this list added containers
485 * and lists which are part of this notification.
488 * module from which is obtained set of all notification objects
489 * to iterate over them
490 * @throws IllegalArgumentException
492 * <li>if the module equals null</li>
493 * <li>if the name of module equals null</li>
495 * @throws IllegalStateException
496 * if set of notifications from module is null
498 private void notificationsToGenType(final Module module) {
499 checkArgument(module != null, "Module reference cannot be NULL.");
500 checkArgument(module.getName() != null, "Module name cannot be NULL.");
501 final Set<NotificationDefinition> notifications = module.getNotifications();
502 if (notifications.isEmpty()) {
506 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
507 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
508 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
510 for (final NotificationDefinition notification : notifications) {
511 if (notification != null) {
512 processUsesAugments(notification, module);
514 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
515 notification, null, module);
516 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
517 notificationInterface.addImplementsType(NOTIFICATION);
518 genCtx.get(module).addChildNodeType(notification, notificationInterface);
520 // Notification object
521 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
522 notification.getChildNodes());
524 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
525 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
526 .setReturnType(Types.VOID), notification);
530 addCodegenInformation(listenerInterface, module, "notifications", notifications);
531 genCtx.get(module).addTopLevelNodeType(listenerInterface);
535 * Converts all <b>identities</b> of the module to the list of
536 * <code>Type</code> objects.
539 * module from which is obtained set of all identity objects to
542 * schema context only used as input parameter for method
543 * {@link BindingGeneratorImpl#identityToGenType}
546 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
547 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
548 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
550 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
551 for (final IdentitySchemaNode identity : schemaIdentities) {
552 identityToGenType(module, basePackageName, identity, context);
558 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
559 * created transport object builder. If identity contains base identity then
560 * reference to base identity is added to superior identity as its extend.
561 * If identity doesn't contain base identity then only reference to abstract
562 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
563 * BaseIdentity} is added
567 * @param basePackageName
568 * string contains the module package name
570 * IdentitySchemaNode which contains data about identity
572 * SchemaContext which is used to get package and name
573 * information about base of identity
576 private void identityToGenType(final Module module, final String basePackageName,
577 final IdentitySchemaNode identity, final SchemaContext context) {
578 if (identity == null) {
581 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
582 final String genTypeName = BindingMapping.getClassName(identity.getQName());
583 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
584 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
585 if (baseIdentities.isEmpty()) {
586 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
587 BaseIdentity.class.getSimpleName());
588 newType.setExtendsType(gto.toInstance());
590 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
591 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
592 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
594 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
595 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
597 newType.setExtendsType(gto);
599 newType.setAbstract(true);
601 addCodegenInformation(newType, module, identity);
602 newType.setModuleName(module.getName());
603 newType.setSchemaPath(identity.getPath().getPathFromRoot());
605 final QName qname = identity.getQName();
606 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
608 genCtx.get(module).addIdentityType(identity.getQName(), newType);
612 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
614 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
618 * Converts all <b>groupings</b> of the module to the list of
619 * <code>Type</code> objects. Firstly are groupings sorted according mutual
620 * dependencies. At least dependent (independent) groupings are in the list
621 * saved at first positions. For every grouping the record is added to map
622 * {@link ModuleContext#groupings allGroupings}
627 * collection of groupings from which types will be generated
630 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
631 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
632 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
634 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
635 groupingToGenType(basePackageName, grouping, module);
640 * Converts individual grouping to GeneratedType. Firstly generated type
641 * builder is created and every child node of grouping is resolved to the
644 * @param basePackageName
645 * string contains the module package name
647 * GroupingDefinition which contains data about grouping
651 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
652 final Module module) {
653 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
654 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
655 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
656 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
657 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
658 groupingsToGenTypes(module, grouping.getGroupings());
659 processUsesAugments(grouping, module);
663 * Adds enumeration builder created from <code>enumTypeDef</code> to
664 * <code>typeBuilder</code>.
666 * Each <code>enumTypeDef</code> item is added to builder with its name and
670 * EnumTypeDefinition contains enum data
672 * string contains name which will be assigned to enumeration
675 * GeneratedTypeBuilder to which will be enum builder assigned
677 * Module in which type should be generated
678 * @return enumeration builder which contains data from
679 * <code>enumTypeDef</code>
681 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
682 final GeneratedTypeBuilder typeBuilder, final Module module) {
683 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
684 final String enumerationName = BindingMapping.getClassName(enumName);
685 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
686 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
687 enumBuilder.setDescription(enumTypedefDescription);
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 GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(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.toInstance(),
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.toInstance(),
820 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
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 = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
918 augTypeBuilder.addImplementsType(DATA_OBJECT);
919 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
920 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
921 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
923 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
924 augmentBuilders.put(augTypeName, augTypeBuilder);
926 if (!augSchema.getChildNodes().isEmpty()) {
927 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
930 genCtx.get(module).addAugmentType(augTypeBuilder);
931 return augTypeBuilder;
936 * @param unknownSchemaNodes
937 * @return nodeParameter of UnknownSchemaNode
939 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
940 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
941 final QName nodeType = unknownSchemaNode.getNodeType();
942 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
943 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
944 return unknownSchemaNode.getNodeParameter();
951 * Returns first unique name for the augment generated type builder. The
952 * generated type builder name for augment consists from name of augmented
953 * node and serial number of its augmentation.
956 * map of builders which were created in the package to which the
957 * augmentation belongs
959 * string with name of augmented node
960 * @return string with unique name for augmentation builder
962 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
964 if (builders != null) {
965 while (builders.containsKey(genTypeName + index)) {
969 return genTypeName + index;
973 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
974 * node for which <code>typeBuilder</code> was created.
976 * The subnodes aren't mapped to the methods if they are part of grouping or
977 * augment (in this case are already part of them).
981 * @param basePackageName
982 * string contains the module package name
984 * generated type builder which represents any node. The subnodes
985 * of this node are added to the <code>typeBuilder</code> as
986 * methods. The subnode can be of type leaf, leaf-list, list,
991 * set of data schema nodes which are the children of the node
992 * for which <code>typeBuilder</code> was created
993 * @return generated type builder which is the same builder as input
994 * parameter. The getter methods (representing child nodes) could be
997 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
998 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
999 if (schemaNodes != null && parent != null) {
1000 for (final DataSchemaNode schemaNode : schemaNodes) {
1001 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1002 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1010 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1011 * node for which <code>typeBuilder</code> was created.
1015 * @param basePackageName
1016 * string contains the module package name
1017 * @param typeBuilder
1018 * generated type builder which represents any node. The subnodes
1019 * of this node are added to the <code>typeBuilder</code> as
1020 * methods. The subnode can be of type leaf, leaf-list, list,
1021 * container, choice.
1024 * @param schemaNodes
1025 * set of data schema nodes which are the children of the node
1026 * for which <code>typeBuilder</code> was created
1027 * @return generated type builder which is the same object as the input
1028 * parameter <code>typeBuilder</code>. The getter method could be
1031 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1032 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1033 final Iterable<DataSchemaNode> schemaNodes) {
1034 if (schemaNodes != null && typeBuilder != null) {
1035 for (final DataSchemaNode schemaNode : schemaNodes) {
1036 if (!schemaNode.isAugmenting()) {
1037 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1045 * Adds to <code>typeBuilder</code> a method which is derived from
1046 * <code>schemaNode</code>.
1048 * @param basePackageName
1049 * string with the module package name
1051 * data schema node which is added to <code>typeBuilder</code> as
1053 * @param typeBuilder
1054 * generated type builder to which is <code>schemaNode</code>
1055 * added as a method.
1061 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1062 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1063 if (node != null && typeBuilder != null) {
1064 if (node instanceof LeafSchemaNode) {
1065 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1066 } else if (node instanceof LeafListSchemaNode) {
1067 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1068 } else if (node instanceof ContainerSchemaNode) {
1069 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1070 } else if (node instanceof ListSchemaNode) {
1071 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1072 } else if (node instanceof ChoiceSchemaNode) {
1073 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1075 // TODO: anyxml not yet supported
1076 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1077 typeBuilder.getFullyQualifiedName());
1083 * Converts <code>choiceNode</code> to the list of generated types for
1084 * choice and its cases.
1086 * The package names for choice and for its cases are created as
1087 * concatenation of the module package (<code>basePackageName</code>) and
1088 * names of all parents node.
1092 * @param basePackageName
1093 * string with the module package name
1097 * choice node which is mapped to generated type. Also child
1098 * nodes - cases are mapped to generated types.
1099 * @throws IllegalArgumentException
1101 * <li>if <code>basePackageName</code> is null</li>
1102 * <li>if <code>choiceNode</code> is null</li>
1105 private void choiceToGeneratedType(final Module module, final String basePackageName,
1106 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1107 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1108 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1110 if (!choiceNode.isAddedByUses()) {
1111 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1112 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1113 constructGetter(parent, choiceTypeBuilder, choiceNode);
1114 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1115 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1116 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1117 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1122 * Converts <code>caseNodes</code> set to list of corresponding generated
1125 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1126 * created generated type builder. The package names for the builder is
1127 * created as concatenation of the module package (
1128 * <code>basePackageName</code>) and names of all parents nodes of the
1129 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1130 * between every case builder and <i>choice</i> type
1134 * @param basePackageName
1135 * string with the module package name
1136 * @param refChoiceType
1137 * type which represents superior <i>case</i>
1139 * choice case node which is mapped to generated type
1140 * @throws IllegalArgumentException
1142 * <li>if <code>basePackageName</code> equals null</li>
1143 * <li>if <code>refChoiceType</code> equals null</li>
1144 * <li>if <code>caseNodes</code> equals null</li>
1147 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1148 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1149 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1150 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1151 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1153 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1154 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1155 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1156 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
1158 caseTypeBuilder.addImplementsType(refChoiceType);
1159 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1160 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1161 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1162 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1163 if (caseChildNodes != null) {
1164 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1166 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1167 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1169 if (parent instanceof AugmentationSchemaNode) {
1170 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1171 final SchemaPath targetPath = augSchema.getTargetPath();
1172 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1173 if (targetSchemaNode instanceof DataSchemaNode
1174 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1175 if (targetSchemaNode instanceof DerivableSchemaNode) {
1176 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1179 if (targetSchemaNode == null) {
1180 throw new IllegalStateException(
1181 "Failed to find target node from grouping for augmentation " + augSchema
1182 + " in module " + module.getName());
1185 parent = targetSchemaNode;
1188 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1189 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1190 if (childOfType == null) {
1191 childOfType = findGroupingByPath(parent.getPath());
1193 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1195 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1200 processUsesAugments(caseNode, module);
1205 * Generates list of generated types for all the cases of a choice which are
1206 * added to the choice through the augment.
1210 * @param basePackageName
1211 * string contains name of package to which augment belongs. If
1212 * an augmented choice is from an other package (pcg1) than an
1213 * augmenting choice (pcg2) then case's of the augmenting choice
1214 * will belong to pcg2.
1216 * Type which represents target choice
1218 * node which represents target choice
1219 * @param augmentedNodes
1220 * set of choice case nodes for which is checked if are/aren't
1221 * added to choice through augmentation
1222 * @throws IllegalArgumentException
1224 * <li>if <code>basePackageName</code> is null</li>
1225 * <li>if <code>targetType</code> is null</li>
1226 * <li>if <code>augmentedNodes</code> is null</li>
1229 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1230 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1231 final DataNodeContainer usesNodeParent) {
1232 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1233 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1234 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1236 for (final DataSchemaNode caseNode : augmentedNodes) {
1237 if (caseNode != null) {
1238 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1239 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1240 caseTypeBuilder.addImplementsType(targetType);
1243 final SchemaPath nodeSp = targetNode.getPath();
1244 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1246 GeneratedTypeBuilder childOfType = null;
1247 if (parent instanceof Module) {
1248 childOfType = genCtx.get(parent).getModuleNode();
1249 } else if (parent instanceof CaseSchemaNode) {
1250 childOfType = findCaseByPath(parent.getPath());
1251 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1252 childOfType = findChildNodeByPath(parent.getPath());
1253 } else if (parent instanceof GroupingDefinition) {
1254 childOfType = findGroupingByPath(parent.getPath());
1257 if (childOfType == null) {
1258 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1261 CaseSchemaNode node = null;
1262 final String caseLocalName = caseNode.getQName().getLocalName();
1263 if (caseNode instanceof CaseSchemaNode) {
1264 node = (CaseSchemaNode) caseNode;
1265 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1266 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1267 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1268 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1269 ().getLocalName())) {
1270 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1275 node = findNamedCase(targetNode, caseLocalName);
1277 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1278 if (childNodes != null) {
1279 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1281 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1282 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1287 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1288 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1289 return cases.isEmpty() ? null : cases.get(0);
1292 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1293 // New parser with encapsulated type
1294 if (leaf.getPath().equals(type.getPath())) {
1298 // Embedded type definition with new parser. Also takes care of the old parser with bits
1299 if (leaf.getPath().equals(type.getPath().getParent())) {
1307 * Converts <code>leaf</code> to the getter method which is added to
1308 * <code>typeBuilder</code>.
1310 * @param typeBuilder
1311 * generated type builder to which is added getter method as
1312 * <code>leaf</code> mapping
1314 * leaf schema node which is mapped as getter method which is
1315 * added to <code>typeBuilder</code>
1317 * Module in which type was defined
1318 * @return boolean value
1320 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1322 * <li>true - in other cases</li>
1325 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1326 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1330 final Module parentModule = findParentModule(schemaContext, leaf);
1331 Type returnType = null;
1333 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1334 if (isInnerType(leaf, typeDef)) {
1335 if (typeDef instanceof EnumTypeDefinition) {
1336 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1337 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1338 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1339 typeBuilder, module);
1340 if (enumBuilder != null) {
1341 returnType = enumBuilder.toInstance(typeBuilder);
1343 typeProvider.putReferencedType(leaf.getPath(), returnType);
1344 } else if (typeDef instanceof UnionTypeDefinition) {
1345 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1346 if (genTOBuilder != null) {
1347 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1348 // Store the inner type within the union so that we can find the reference for it
1349 genCtx.get(module).addInnerTypedefType(typeDef.getPath(), returnType);
1351 } else if (typeDef instanceof BitsTypeDefinition) {
1352 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1353 if (genTOBuilder != null) {
1354 returnType = genTOBuilder.toInstance();
1357 // It is constrained version of already declared type (inner declared type exists,
1358 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1359 // In order to get proper class we need to look up closest derived type
1360 // and apply restrictions from leaf type
1361 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1362 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1366 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1367 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1370 if (returnType == null) {
1374 if (typeDef instanceof EnumTypeDefinition) {
1375 typeProvider.putReferencedType(leaf.getPath(), returnType);
1378 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1379 processContextRefExtension(leaf, getter, parentModule);
1383 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1384 // Returns DerivedType in case of new parser.
1385 final TypeDefinition<?> baseType = typeDef.getBaseType();
1386 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1389 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1390 final Module module) {
1391 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1392 final QName nodeType = node.getNodeType();
1393 if ("context-reference".equals(nodeType.getLocalName())) {
1394 final String nodeParam = node.getNodeParameter();
1395 IdentitySchemaNode identity = null;
1396 String basePackageName = null;
1397 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1398 final Iterator<String> iterator = splittedElement.iterator();
1399 final int length = Iterables.size(splittedElement);
1401 identity = findIdentityByName(module.getIdentities(), iterator.next());
1402 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1403 } else if (length == 2) {
1404 final String prefix = iterator.next();
1405 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1406 if (dependentModule == null) {
1407 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1410 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1411 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1413 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1416 if (identity == null) {
1417 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1421 final Class<RoutingContext> clazz = RoutingContext.class;
1422 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1423 clazz.getSimpleName());
1424 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1425 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1426 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1431 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1432 for (final IdentitySchemaNode id : identities) {
1433 if (id.getQName().getLocalName().equals(name)) {
1440 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1441 for (final ModuleImport imp : imports) {
1442 if (imp.getPrefix().equals(prefix)) {
1443 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1449 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1450 final boolean isReadOnly, final Module module) {
1451 if (leaf != null && toBuilder != null) {
1453 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1454 if (typeDef instanceof UnionTypeDefinition) {
1455 // GeneratedType for this type definition should have be already created
1456 final QName qname = typeDef.getQName();
1457 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1458 final ModuleContext mc = genCtx.get(unionModule);
1459 returnType = mc.getTypedefs().get(typeDef.getPath());
1460 if (returnType == null) {
1461 // This may still be an inner type, try to find it
1462 returnType = mc.getInnerType(typeDef.getPath());
1464 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1465 // Annonymous enumeration (already generated, since it is inherited via uses).
1466 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1467 QName qname = originalLeaf.getQName();
1468 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
1469 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1471 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1473 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1479 * Converts <code>leaf</code> schema node to property of generated TO
1483 * generated TO builder to which is <code>leaf</code> added as
1486 * leaf schema node which is added to <code>toBuilder</code> as
1491 * boolean value which says if leaf property is|isn't read only
1492 * @return boolean value
1494 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1495 * name equals null or if leaf is added by <i>uses</i>.</li>
1496 * <li>true - other cases</li>
1499 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1500 final Type returnType, final boolean isReadOnly) {
1501 if (returnType == null) {
1504 final String leafName = leaf.getQName().getLocalName();
1505 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1506 propBuilder.setReadOnly(isReadOnly);
1507 propBuilder.setReturnType(returnType);
1508 addComment(propBuilder, leaf);
1510 toBuilder.addEqualsIdentity(propBuilder);
1511 toBuilder.addHashIdentity(propBuilder);
1512 toBuilder.addToStringProperty(propBuilder);
1517 * Converts <code>node</code> leaf list schema node to getter method of
1518 * <code>typeBuilder</code>.
1520 * @param typeBuilder
1521 * generated type builder to which is <code>node</code> added as
1524 * leaf list schema node which is added to
1525 * <code>typeBuilder</code> as getter method
1526 * @param module module
1527 * @return boolean value
1529 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1530 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1531 * <li>false - other cases</li>
1534 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1535 final Module module) {
1536 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1540 final QName nodeName = node.getQName();
1542 final TypeDefinition<?> typeDef = node.getType();
1543 final Module parentModule = findParentModule(schemaContext, node);
1545 Type returnType = null;
1546 if (typeDef.getBaseType() == null) {
1547 if (typeDef instanceof EnumTypeDefinition) {
1548 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1549 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1550 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1551 typeBuilder, module);
1552 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1553 typeProvider.putReferencedType(node.getPath(), returnType);
1554 } else if (typeDef instanceof UnionTypeDefinition) {
1555 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1556 if (genTOBuilder != null) {
1557 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1559 } else if (typeDef instanceof BitsTypeDefinition) {
1560 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1561 returnType = genTOBuilder.toInstance();
1563 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1564 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1567 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1568 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1571 final ParameterizedType listType = Types.listTypeFor(returnType);
1572 constructGetter(typeBuilder, listType, node);
1576 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1577 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1578 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1579 genTOBuilder.getName());
1581 addCodegenInformation(returnType, parentModule, typeDef);
1582 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1583 returnType.setModuleName(parentModule.getName());
1585 genTOBuilder.setTypedef(true);
1586 genTOBuilder.setIsUnion(true);
1587 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1591 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1594 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1595 method.setReturnType(returnType);
1596 method.addParameter(Types.STRING, "defaultValue");
1597 method.setAccessModifier(AccessModifier.PUBLIC);
1598 method.setStatic(true);
1600 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1601 if (types == null) {
1602 typeProvider.getAdditionalTypes().put(parentModule,
1603 Sets.newHashSet(unionBuilder.toInstance()));
1605 types.add(unionBuilder.toInstance());
1607 return returnType.toInstance();
1610 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1611 final String outerCls = Types.getOuterClassName(genTOBuilder);
1612 final StringBuilder name;
1613 if (outerCls != null) {
1614 name = new StringBuilder(outerCls);
1616 name = new StringBuilder();
1618 name.append(genTOBuilder.getName());
1619 name.append("Builder");
1620 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
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 static 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 = new GeneratedTOBuilderImpl(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");