2 * Copyright (c) 2013 Cisco Systems, Inc. and others. 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.yangtools.sal.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 org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
26 import static org.opendaylight.yangtools.binding.generator.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;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Splitter;
34 import com.google.common.base.Strings;
35 import com.google.common.collect.Iterables;
36 import com.google.common.collect.Sets;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Comparator;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.regex.Pattern;
47 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
48 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
49 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
50 import org.opendaylight.yangtools.binding.generator.util.Types;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
53 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
54 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
55 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
56 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
57 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
61 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
62 import org.opendaylight.yangtools.sal.binding.model.api.Type;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
69 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
70 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
71 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
72 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
73 import org.opendaylight.yangtools.yang.binding.BindingMapping;
74 import org.opendaylight.yangtools.yang.binding.DataContainer;
75 import org.opendaylight.yangtools.yang.binding.RpcService;
76 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
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.SchemaContextUtil;
107 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
108 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
109 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
113 public class BindingGeneratorImpl implements BindingGenerator {
114 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
115 private static final Splitter COLON_SPLITTER = Splitter.on(':');
116 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
117 private static final char NEW_LINE = '\n';
120 * Comparator based on augment target path.
122 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
123 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
124 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
126 while (thisIt.hasNext()) {
127 if (!otherIt.hasNext()) {
131 final int comp = thisIt.next().compareTo(otherIt.next());
137 return otherIt.hasNext() ? -1 : 0;
141 * Constant with the concrete name of identifier.
143 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
146 * Constant with the concrete name of namespace.
148 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
150 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
152 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
155 * When set to true, generated classes will include javadoc comments which
156 * are useful for users.
158 private final boolean verboseClassComments;
161 * Outer key represents the package name. Outer value represents map of all
162 * builders in the same package. Inner key represents the schema node name
163 * (in JAVA class/interface name format). Inner value represents instance of
164 * builder for schema node specified in key part.
166 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
169 * Provide methods for converting YANG types to JAVA types.
171 private TypeProvider typeProvider;
174 * Holds reference to schema context to resolve data of augmented element
175 * when creating augmentation builder
177 private SchemaContext schemaContext;
180 * Create a new binding generator.
182 * @param verboseClassComments generate verbose comments
184 public BindingGeneratorImpl(final boolean verboseClassComments) {
185 this.verboseClassComments = verboseClassComments;
189 * Resolves generated types from <code>context</code> schema nodes of all
192 * Generated types are created for modules, groupings, types, containers,
193 * lists, choices, augments, rpcs, notification, identities.
196 * schema context which contains data about all schema nodes
198 * @return list of types (usually <code>GeneratedType</code>
199 * <code>GeneratedTransferObject</code>which are generated from
200 * <code>context</code> data.
201 * @throws IllegalArgumentException
202 * if arg <code>context</code> is null
203 * @throws IllegalStateException
204 * if <code>context</code> contain no modules
207 public List<Type> generateTypes(final SchemaContext context) {
208 checkArgument(context != null, "Schema Context reference cannot be NULL.");
209 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
210 schemaContext = context;
211 typeProvider = new TypeProviderImpl(context);
212 final Set<Module> modules = context.getModules();
213 return generateTypes(context, modules);
217 * Resolves generated types from <code>context</code> schema nodes only for
218 * modules specified in <code>modules</code>
220 * Generated types are created for modules, groupings, types, containers,
221 * lists, choices, augments, rpcs, notification, identities.
224 * schema context which contains data about all schema nodes
227 * set of modules for which schema nodes should be generated
229 * @return list of types (usually <code>GeneratedType</code> or
230 * <code>GeneratedTransferObject</code>) which:
232 * <li>are generated from <code>context</code> schema nodes and</li>
233 * <li>are also part of some of the module in <code>modules</code>
236 * @throws IllegalArgumentException
238 * <li>if arg <code>context</code> is null or</li>
239 * <li>if arg <code>modules</code> is null</li>
241 * @throws IllegalStateException
242 * if <code>context</code> contain no modules
245 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
246 checkArgument(context != null, "Schema Context reference cannot be NULL.");
247 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
248 checkArgument(modules != null, "Set of Modules cannot be NULL.");
250 schemaContext = context;
251 typeProvider = new TypeProviderImpl(context);
252 final Module[] modulesArray = new Module[context.getModules().size()];
253 context.getModules().toArray(modulesArray);
254 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
255 genTypeBuilders = new HashMap<>();
257 for (final Module contextModule : contextModules) {
258 moduleToGenTypes(contextModule, context);
260 for (final Module contextModule : contextModules) {
261 allAugmentsToGenTypes(contextModule);
264 final List<Type> filteredGenTypes = new ArrayList<>();
265 for (final Module m : modules) {
266 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
267 filteredGenTypes.addAll(ctx.getGeneratedTypes());
268 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
269 if (additionalTypes != null) {
270 filteredGenTypes.addAll(additionalTypes);
274 return filteredGenTypes;
277 private void moduleToGenTypes(final Module m, final SchemaContext context) {
278 genCtx.put(m, new ModuleContext());
279 allTypeDefinitionsToGenTypes(m);
280 groupingsToGenTypes(m, m.getGroupings());
281 rpcMethodsToGenType(m);
282 allIdentitiesToGenTypes(m, context);
283 notificationsToGenType(m);
285 if (!m.getChildNodes().isEmpty()) {
286 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
287 genCtx.get(m).addModuleNode(moduleType);
288 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
289 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
294 * Converts all extended type definitions of module to the list of
295 * <code>Type</code> objects.
298 * module from which is obtained set of type definitions
299 * @throws IllegalArgumentException
301 * <li>if module is null</li>
302 * <li>if name of module is null</li>
304 * @throws IllegalStateException
305 * if set of type definitions from module is null
307 private void allTypeDefinitionsToGenTypes(final Module module) {
308 checkArgument(module != null, "Module reference cannot be NULL.");
309 checkArgument(module.getName() != null, "Module name cannot be NULL.");
310 final DataNodeIterator it = new DataNodeIterator(module);
311 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
312 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
314 for (final TypeDefinition<?> typedef : typeDefinitions) {
315 if (typedef != null) {
316 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
319 final ModuleContext ctx = genCtx.get(module);
320 ctx.addTypedefType(typedef.getPath(), type);
321 ctx.addTypeToSchema(type,typedef);
327 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
328 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
329 if (node.isAugmenting() || node.isAddedByUses()) {
332 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
333 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
334 genType.addComment(node.getDescription());
335 annotateDeprecatedIfNecessary(node.getStatus(), genType);
336 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
337 genType.setModuleName(module.getName());
338 genType.setReference(node.getReference());
339 genType.setSchemaPath(node.getPath().getPathFromRoot());
340 if (node instanceof DataNodeContainer) {
341 genCtx.get(module).addChildNodeType(node, genType);
342 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
343 processUsesAugments((DataNodeContainer) node, module);
348 private void containerToGenType(final Module module, final String basePackageName,
349 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
350 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
351 if (genType != null) {
352 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
353 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
357 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
358 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
359 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
360 if (genType != null) {
361 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
362 Types.listTypeFor(genType), node.getStatus());
364 final List<String> listKeys = listKeys(node);
365 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
366 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
367 if (genTOBuilder != null) {
368 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
369 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
370 genTOBuilder.addImplementsType(identifierMarker);
371 genType.addImplementsType(identifiableMarker);
374 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
375 if (!schemaNode.isAugmenting()) {
376 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
381 if (genTOBuilder != null) {
382 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
383 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
384 genTOBuilder.setSUID(prop);
387 typeBuildersToGenTypes(module, genType, genTOBuilder);
391 private void processUsesAugments(final DataNodeContainer node, final Module module) {
392 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
393 for (final UsesNode usesNode : node.getUses()) {
394 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
395 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
396 processUsesAugments(augment, module);
402 * Converts all <b>augmentation</b> of the module to the list
403 * <code>Type</code> objects.
406 * module from which is obtained list of all augmentation objects
407 * to iterate over them
408 * @throws IllegalArgumentException
410 * <li>if the module is null</li>
411 * <li>if the name of module is null</li>
413 * @throws IllegalStateException
414 * if set of augmentations from module is null
416 private void allAugmentsToGenTypes(final Module module) {
417 checkArgument(module != null, "Module reference cannot be NULL.");
418 checkArgument(module.getName() != null, "Module name cannot be NULL.");
419 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
421 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
422 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
423 for (final AugmentationSchema augment : augmentations) {
424 augmentationToGenTypes(basePackageName, augment, module);
429 * Returns list of <code>AugmentationSchema</code> objects. The objects are
430 * sorted according to the length of their target path from the shortest to
434 * module from which is obtained list of all augmentation objects
435 * @return list of sorted <code>AugmentationSchema</code> objects obtained
436 * from <code>module</code>
437 * @throws IllegalArgumentException
439 * @throws IllegalStateException
440 * if set of module augmentations is null
442 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
443 checkArgument(module != null, "Module reference cannot be NULL.");
444 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
446 final Set<AugmentationSchema> augmentations = module.getAugmentations();
447 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
448 Collections.sort(sortedAugmentations, AUGMENT_COMP);
450 return sortedAugmentations;
454 * Create GeneratedTypeBuilder object from module argument.
457 * Module object from which builder will be created
458 * @return <code>GeneratedTypeBuilder</code> which is internal
459 * representation of the module
460 * @throws IllegalArgumentException
463 private GeneratedTypeBuilder moduleToDataType(final Module module) {
464 checkArgument(module != null, "Module reference cannot be NULL.");
466 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
467 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
468 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
469 moduleDataTypeBuilder.addComment(module.getDescription());
470 moduleDataTypeBuilder.setDescription(createDescription(module));
471 moduleDataTypeBuilder.setReference(module.getReference());
472 return moduleDataTypeBuilder;
476 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
477 * to the list of <code>Type</code> objects. In addition are to containers
478 * and lists which belong to input or output also part of returning list.
481 * module from which is obtained set of all rpc objects to
483 * @throws IllegalArgumentException
485 * <li>if the module is null</li>
486 * <li>if the name of module is null</li>
488 * @throws IllegalStateException
489 * if set of rpcs from module is null
491 private void rpcMethodsToGenType(final Module module) {
492 checkArgument(module != null, "Module reference cannot be NULL.");
493 checkArgument(module.getName() != null, "Module name cannot be NULL.");
494 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
495 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
496 if (rpcDefinitions.isEmpty()) {
500 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
501 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
502 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
503 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
505 for (final RpcDefinition rpc : rpcDefinitions) {
507 final String rpcName = BindingMapping.getClassName(rpc.getQName());
508 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
509 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
510 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
511 final ContainerSchemaNode input = rpc.getInput();
512 final ContainerSchemaNode output = rpc.getOutput();
515 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
516 addImplementedInterfaceFromUses(input, inType);
517 inType.addImplementsType(DATA_OBJECT);
518 inType.addImplementsType(augmentable(inType));
519 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
520 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
521 genCtx.get(module).addChildNodeType(input, inType);
522 final GeneratedType inTypeInstance = inType.toInstance();
523 method.addParameter(inTypeInstance, "input");
526 Type outTypeInstance = VOID;
527 if (output != null) {
528 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
529 addImplementedInterfaceFromUses(output, outType);
530 outType.addImplementsType(DATA_OBJECT);
531 outType.addImplementsType(augmentable(outType));
532 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
533 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
534 genCtx.get(module).addChildNodeType(output, outType);
535 outTypeInstance = outType.toInstance();
538 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
539 method.setComment(rpcComment);
540 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
544 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
548 * Converts all <b>notifications</b> of the module to the list of
549 * <code>Type</code> objects. In addition are to this list added containers
550 * and lists which are part of this notification.
553 * module from which is obtained set of all notification objects
554 * to iterate over them
555 * @throws IllegalArgumentException
557 * <li>if the module equals null</li>
558 * <li>if the name of module equals null</li>
560 * @throws IllegalStateException
561 * if set of notifications from module is null
563 private void notificationsToGenType(final Module module) {
564 checkArgument(module != null, "Module reference cannot be NULL.");
565 checkArgument(module.getName() != null, "Module name cannot be NULL.");
566 final Set<NotificationDefinition> notifications = module.getNotifications();
567 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
568 if (notifications.isEmpty()) {
572 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
573 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
574 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
578 for (final NotificationDefinition notification : notifications) {
579 if (notification != null) {
580 processUsesAugments(notification, module);
582 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
583 notification, null, module);
584 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
585 notificationInterface.addImplementsType(NOTIFICATION);
586 genCtx.get(module).addChildNodeType(notification, notificationInterface);
588 // Notification object
589 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
590 notification.getChildNodes());
592 listenerInterface.addMethod("on" + notificationInterface.getName())
593 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
594 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
597 listenerInterface.setDescription(createDescription(notifications, module.getName()));
599 genCtx.get(module).addTopLevelNodeType(listenerInterface);
603 * Converts all <b>identities</b> of the module to the list of
604 * <code>Type</code> objects.
607 * module from which is obtained set of all identity objects to
610 * schema context only used as input parameter for method
611 * {@link identityToGenType}
614 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
615 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
616 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
618 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
619 for (final IdentitySchemaNode identity : schemaIdentities) {
620 identityToGenType(module, basePackageName, identity, context);
626 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
627 * created transport object builder. If identity contains base identity then
628 * reference to base identity is added to superior identity as its extend.
629 * If identity doesn't contain base identity then only reference to abstract
630 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
631 * BaseIdentity} is added
635 * @param basePackageName
636 * string contains the module package name
638 * IdentitySchemaNode which contains data about identity
640 * SchemaContext which is used to get package and name
641 * information about base of identity
644 private void identityToGenType(final Module module, final String basePackageName,
645 final IdentitySchemaNode identity, final SchemaContext context) {
646 if (identity == null) {
649 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
650 final String genTypeName = BindingMapping.getClassName(identity.getQName());
651 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
652 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
653 if (baseIdentity == null) {
654 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
655 BaseIdentity.class.getSimpleName());
656 newType.setExtendsType(gto.toInstance());
658 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
659 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
661 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
662 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
664 newType.setExtendsType(gto);
666 newType.setAbstract(true);
667 newType.addComment(identity.getDescription());
668 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
669 newType.setReference(identity.getReference());
670 newType.setModuleName(module.getName());
671 newType.setSchemaPath(identity.getPath().getPathFromRoot());
673 final QName qname = identity.getQName();
674 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
676 genCtx.get(module).addIdentityType(identity.getQName(), newType);
679 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
681 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
685 * Converts all <b>groupings</b> of the module to the list of
686 * <code>Type</code> objects. Firstly are groupings sorted according mutual
687 * dependencies. At least dependent (independent) groupings are in the list
688 * saved at first positions. For every grouping the record is added to map
689 * {@link BindingGeneratorImpl#allGroupings allGroupings}
694 * of groupings from which types will be generated
697 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
698 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
699 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
701 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
702 groupingToGenType(basePackageName, grouping, module);
707 * Converts individual grouping to GeneratedType. Firstly generated type
708 * builder is created and every child node of grouping is resolved to the
711 * @param basePackageName
712 * string contains the module package name
714 * GroupingDefinition which contains data about grouping
717 * @return GeneratedType which is generated from grouping (object of type
718 * <code>GroupingDefinition</code>)
720 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
721 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
722 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
723 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
724 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
725 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
726 groupingsToGenTypes(module, grouping.getGroupings());
727 processUsesAugments(grouping, module);
731 * Adds enumeration builder created from <code>enumTypeDef</code> to
732 * <code>typeBuilder</code>.
734 * Each <code>enumTypeDef</code> item is added to builder with its name and
738 * EnumTypeDefinition contains enum data
740 * string contains name which will be assigned to enumeration
743 * GeneratedTypeBuilder to which will be enum builder assigned
745 * Module in which type should be generated
746 * @return enumeration builder which contains data from
747 * <code>enumTypeDef</code>
749 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
750 final GeneratedTypeBuilder typeBuilder, final Module module) {
751 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
752 && (enumTypeDef.getQName().getLocalName() != null)) {
753 final String enumerationName = BindingMapping.getClassName(enumName);
754 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
755 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
756 enumBuilder.setDescription(enumTypedefDescription);
757 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
758 ModuleContext ctx = genCtx.get(module);
759 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
766 * Generates type builder for <code>module</code>.
769 * Module which is source of package name for generated type
772 * string which is added to the module class name representation
774 * @return instance of GeneratedTypeBuilder which represents
775 * <code>module</code>.
776 * @throws IllegalArgumentException
777 * if <code>module</code> is null
779 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
780 checkArgument(module != null, "Module reference cannot be NULL.");
781 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
782 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
784 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
785 moduleBuilder.setDescription(createDescription(module));
786 moduleBuilder.setReference(module.getReference());
787 moduleBuilder.setModuleName(moduleName);
789 return moduleBuilder;
793 * Converts <code>augSchema</code> to list of <code>Type</code> which
794 * contains generated type for augmentation. In addition there are also
795 * generated types for all containers, list and choices which are child of
796 * <code>augSchema</code> node or a generated types for cases are added if
797 * augmented node is choice.
799 * @param augmentPackageName
800 * string with the name of the package to which the augmentation
803 * AugmentationSchema which is contains data about augmentation
804 * (target path, childs...)
807 * @param parentUsesNode
808 * @throws IllegalArgumentException
810 * <li>if <code>augmentPackageName</code> equals null</li>
811 * <li>if <code>augSchema</code> equals null</li>
813 * @throws IllegalStateException
814 * if augment target path is null
816 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
817 final Module module) {
818 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
819 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
820 checkState(augSchema.getTargetPath() != null,
821 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
823 processUsesAugments(augSchema, module);
824 final SchemaPath targetPath = augSchema.getTargetPath();
825 SchemaNode targetSchemaNode = null;
827 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
828 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
829 if (targetSchemaNode instanceof DerivableSchemaNode) {
830 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
832 if (targetSchemaNode == null) {
833 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
834 + " in module " + module.getName());
837 if (targetSchemaNode == null) {
838 throw new IllegalArgumentException("augment target not found: " + targetPath);
841 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
842 if (targetTypeBuilder == null) {
843 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
845 if (targetTypeBuilder == null) {
846 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
849 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
850 final String packageName = augmentPackageName;
851 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
852 targetTypeBuilder.getName());
853 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
856 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
857 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
861 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
862 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
863 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
864 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
865 checkState(augSchema.getTargetPath() != null,
866 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
868 processUsesAugments(augSchema, module);
869 final SchemaPath targetPath = augSchema.getTargetPath();
870 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
871 if (targetSchemaNode == null) {
872 throw new IllegalArgumentException("augment target not found: " + targetPath);
875 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
876 if (targetTypeBuilder == null) {
877 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
879 if (targetTypeBuilder == null) {
880 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
883 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
884 String packageName = augmentPackageName;
885 if (usesNodeParent instanceof SchemaNode) {
886 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
888 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
891 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
892 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
897 * Convenient method to find node added by uses statement.
901 * @param parentUsesNode
902 * parent of uses node
903 * @return node from its original location in grouping
905 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
906 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
908 if (!(targetGrouping instanceof GroupingDefinition)) {
909 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
912 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
913 SchemaNode result = grouping;
914 for (final QName node : targetPath.getPathFromRoot()) {
915 if (result instanceof DataNodeContainer) {
916 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
917 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
918 } else if (result instanceof ChoiceSchemaNode) {
919 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
922 if (result == null) {
926 if (result instanceof DerivableSchemaNode) {
927 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
928 Optional<? extends SchemaNode> originalNode = castedResult
930 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
931 result = originalNode.get();
935 if (result instanceof DataSchemaNode) {
936 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
937 if (resultDataSchemaNode.isAddedByUses()) {
938 // The original node is required, but we have only the copy of
939 // the original node.
940 // Maybe this indicates a bug in Yang parser.
941 throw new IllegalStateException(
942 "Failed to generate code for augment in "
945 return resultDataSchemaNode;
948 throw new IllegalStateException(
949 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
955 * Returns a generated type builder for an augmentation.
957 * The name of the type builder is equal to the name of augmented node with
958 * serial number as suffix.
962 * @param augmentPackageName
963 * string with contains the package name to which the augment
965 * @param basePackageName
966 * string with the package name to which the augmented node
968 * @param targetTypeRef
971 * augmentation schema which contains data about the child nodes
972 * and uses of augment
973 * @return generated type builder for augment
975 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
976 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
977 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
978 if (augmentBuilders == null) {
979 augmentBuilders = new HashMap<>();
980 genTypeBuilders.put(augmentPackageName, augmentBuilders);
982 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
985 if (augIdentifier != null) {
986 augTypeName = BindingMapping.getClassName(augIdentifier);
988 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
991 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
993 augTypeBuilder.addImplementsType(DATA_OBJECT);
994 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
995 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
996 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
998 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
999 augmentBuilders.put(augTypeName, augTypeBuilder);
1001 if(!augSchema.getChildNodes().isEmpty()) {
1002 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
1003 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1006 genCtx.get(module).addAugmentType(augTypeBuilder);
1007 return augTypeBuilder;
1012 * @param unknownSchemaNodes
1013 * @return nodeParameter of UnknownSchemaNode
1015 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1016 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1017 final QName nodeType = unknownSchemaNode.getNodeType();
1018 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1019 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1020 return unknownSchemaNode.getNodeParameter();
1027 * Returns first unique name for the augment generated type builder. The
1028 * generated type builder name for augment consists from name of augmented
1029 * node and serial number of its augmentation.
1032 * map of builders which were created in the package to which the
1033 * augmentation belongs
1034 * @param genTypeName
1035 * string with name of augmented node
1036 * @return string with unique name for augmentation builder
1038 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1040 if (builders != null) {
1041 while (builders.containsKey(genTypeName + index)) {
1045 return genTypeName + index;
1049 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1050 * node for which <code>typeBuilder</code> was created.
1052 * The subnodes aren't mapped to the methods if they are part of grouping or
1053 * augment (in this case are already part of them).
1057 * @param basePackageName
1058 * string contains the module package name
1060 * generated type builder which represents any node. The subnodes
1061 * of this node are added to the <code>typeBuilder</code> as
1062 * methods. The subnode can be of type leaf, leaf-list, list,
1063 * container, choice.
1066 * @param schemaNodes
1067 * set of data schema nodes which are the children of the node
1068 * for which <code>typeBuilder</code> was created
1069 * @return generated type builder which is the same builder as input
1070 * parameter. The getter methods (representing child nodes) could be
1073 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1074 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1075 if (schemaNodes != null && parent != null) {
1076 for (final DataSchemaNode schemaNode : schemaNodes) {
1077 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1078 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1086 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1087 * node for which <code>typeBuilder</code> was created.
1091 * @param basePackageName
1092 * string contains the module package name
1093 * @param typeBuilder
1094 * generated type builder which represents any node. The subnodes
1095 * of this node are added to the <code>typeBuilder</code> as
1096 * methods. The subnode can be of type leaf, leaf-list, list,
1097 * container, choice.
1100 * @param schemaNodes
1101 * set of data schema nodes which are the children of the node
1102 * for which <code>typeBuilder</code> was created
1103 * @return generated type builder which is the same object as the input
1104 * parameter <code>typeBuilder</code>. The getter method could be
1107 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1108 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1109 final Iterable<DataSchemaNode> schemaNodes) {
1110 if ((schemaNodes != null) && (typeBuilder != null)) {
1111 for (final DataSchemaNode schemaNode : schemaNodes) {
1112 if (!schemaNode.isAugmenting()) {
1113 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1121 * Adds to <code>typeBuilder</code> a method which is derived from
1122 * <code>schemaNode</code>.
1124 * @param basePackageName
1125 * string with the module package name
1127 * data schema node which is added to <code>typeBuilder</code> as
1129 * @param typeBuilder
1130 * generated type builder to which is <code>schemaNode</code>
1131 * added as a method.
1137 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1138 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1139 if (node != null && typeBuilder != null) {
1140 if (node instanceof LeafSchemaNode) {
1141 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1142 } else if (node instanceof LeafListSchemaNode) {
1143 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1144 } else if (node instanceof ContainerSchemaNode) {
1145 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1146 } else if (node instanceof ListSchemaNode) {
1147 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1148 } else if (node instanceof ChoiceSchemaNode) {
1149 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1151 // TODO: anyxml not yet supported
1152 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1153 typeBuilder.getFullyQualifiedName());
1159 * Converts <code>choiceNode</code> to the list of generated types for
1160 * choice and its cases.
1162 * The package names for choice and for its cases are created as
1163 * concatenation of the module package (<code>basePackageName</code>) and
1164 * names of all parents node.
1168 * @param basePackageName
1169 * string with the module package name
1173 * choice node which is mapped to generated type. Also child
1174 * nodes - cases are mapped to generated types.
1175 * @throws IllegalArgumentException
1177 * <li>if <code>basePackageName</code> is null</li>
1178 * <li>if <code>choiceNode</code> is null</li>
1181 private void choiceToGeneratedType(final Module module, final String basePackageName,
1182 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1183 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1184 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1186 if (!choiceNode.isAddedByUses()) {
1187 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1188 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1189 constructGetter(parent, choiceNode.getQName().getLocalName(),
1190 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1191 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1192 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1193 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1194 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1199 * Converts <code>caseNodes</code> set to list of corresponding generated
1202 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1203 * created generated type builder. The package names for the builder is
1204 * created as concatenation of the module package (
1205 * <code>basePackageName</code>) and names of all parents nodes of the
1206 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1207 * between every case builder and <i>choice</i> type
1211 * @param basePackageName
1212 * string with the module package name
1213 * @param refChoiceType
1214 * type which represents superior <i>case</i>
1216 * choice case node which is mapped to generated type
1217 * @return list of generated types for <code>caseNodes</code>.
1218 * @throws IllegalArgumentException
1220 * <li>if <code>basePackageName</code> equals null</li>
1221 * <li>if <code>refChoiceType</code> equals null</li>
1222 * <li>if <code>caseNodes</code> equals null</li>
1225 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1226 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1227 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1228 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1229 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1231 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1232 if (caseNodes == null) {
1236 for (final ChoiceCaseNode caseNode : caseNodes) {
1237 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1238 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1239 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1240 caseTypeBuilder.addImplementsType(refChoiceType);
1241 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1242 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1243 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1244 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1245 if (caseChildNodes != null) {
1246 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1248 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1249 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1251 if (parent instanceof AugmentationSchema) {
1252 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1253 final SchemaPath targetPath = augSchema.getTargetPath();
1254 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1255 if (targetSchemaNode instanceof DataSchemaNode
1256 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1260 if (targetSchemaNode == null) {
1261 throw new IllegalStateException(
1262 "Failed to find target node from grouping for augmentation " + augSchema
1263 + " in module " + module.getName());
1266 parent = targetSchemaNode;
1269 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1270 choiceNodeParentPath);
1271 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1272 if (childOfType == null) {
1273 childOfType = findGroupingByPath(parent.getPath());
1275 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1277 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1282 processUsesAugments(caseNode, module);
1287 * Generates list of generated types for all the cases of a choice which are
1288 * added to the choice through the augment.
1292 * @param basePackageName
1293 * string contains name of package to which augment belongs. If
1294 * an augmented choice is from an other package (pcg1) than an
1295 * augmenting choice (pcg2) then case's of the augmenting choice
1296 * will belong to pcg2.
1298 * Type which represents target choice
1300 * node which represents target choice
1301 * @param augmentedNodes
1302 * set of choice case nodes for which is checked if are/aren't
1303 * added to choice through augmentation
1304 * @return list of generated types which represents augmented cases of
1305 * choice <code>refChoiceType</code>
1306 * @throws IllegalArgumentException
1308 * <li>if <code>basePackageName</code> is null</li>
1309 * <li>if <code>targetType</code> is null</li>
1310 * <li>if <code>augmentedNodes</code> is null</li>
1313 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1314 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1315 final DataNodeContainer usesNodeParent) {
1316 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1317 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1318 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1320 for (final DataSchemaNode caseNode : augmentedNodes) {
1321 if (caseNode != null) {
1322 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1323 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1324 caseTypeBuilder.addImplementsType(targetType);
1326 SchemaNode parent = null;
1327 final SchemaPath nodeSp = targetNode.getPath();
1328 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1330 GeneratedTypeBuilder childOfType = null;
1331 if (parent instanceof Module) {
1332 childOfType = genCtx.get(parent).getModuleNode();
1333 } else if (parent instanceof ChoiceCaseNode) {
1334 childOfType = findCaseByPath(parent.getPath());
1335 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1336 childOfType = findChildNodeByPath(parent.getPath());
1337 } else if (parent instanceof GroupingDefinition) {
1338 childOfType = findGroupingByPath(parent.getPath());
1341 if (childOfType == null) {
1342 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1345 ChoiceCaseNode node = null;
1346 final String caseLocalName = caseNode.getQName().getLocalName();
1347 if (caseNode instanceof ChoiceCaseNode) {
1348 node = (ChoiceCaseNode) caseNode;
1349 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1350 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1351 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1352 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1353 ().getLocalName())) {
1354 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1359 node = targetNode.getCaseNodeByName(caseLocalName);
1361 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1362 if (childNodes != null) {
1363 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1365 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1366 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1371 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1372 // New parser with encapsulated type
1373 if (leaf.getPath().equals(type.getPath())) {
1377 // Embedded type definition with new parser. Also takes care of the old parser with bits
1378 if (leaf.getPath().equals(type.getPath().getParent())) {
1386 * Converts <code>leaf</code> to the getter method which is added to
1387 * <code>typeBuilder</code>.
1389 * @param typeBuilder
1390 * generated type builder to which is added getter method as
1391 * <code>leaf</code> mapping
1393 * leaf schema node which is mapped as getter method which is
1394 * added to <code>typeBuilder</code>
1396 * Module in which type was defined
1397 * @return boolean value
1399 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1401 * <li>true - in other cases</li>
1404 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1405 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1409 final String leafName = leaf.getQName().getLocalName();
1410 if (leafName == null) {
1414 final Module parentModule = findParentModule(schemaContext, leaf);
1415 Type returnType = null;
1417 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1418 if (isInnerType(leaf, typeDef)) {
1419 if (typeDef instanceof EnumTypeDefinition) {
1420 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1421 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1422 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1423 typeBuilder, module);
1425 if (enumBuilder != null) {
1426 returnType = enumBuilder.toInstance(typeBuilder);
1428 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1429 } else if (typeDef instanceof UnionTypeDefinition) {
1430 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1431 if (genTOBuilder != null) {
1432 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1434 } else if (typeDef instanceof BitsTypeDefinition) {
1435 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1436 if (genTOBuilder != null) {
1437 returnType = genTOBuilder.toInstance();
1440 // It is constrained version of already declared type (inner declared type exists,
1441 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1442 // In order to get proper class we need to look up closest derived type
1443 // and apply restrictions from leaf type
1444 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1445 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1449 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1450 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1453 if (returnType == null) {
1457 String leafDesc = leaf.getDescription();
1458 if (leafDesc == null) {
1462 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1463 processContextRefExtension(leaf, getter, parentModule);
1467 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1468 // Returns DerivedType in case of new parser.
1469 final TypeDefinition<?> baseType = typeDef.getBaseType();
1470 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1473 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1474 final Module module) {
1475 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1476 final QName nodeType = node.getNodeType();
1477 if ("context-reference".equals(nodeType.getLocalName())) {
1478 final String nodeParam = node.getNodeParameter();
1479 IdentitySchemaNode identity = null;
1480 String basePackageName = null;
1481 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1482 final Iterator<String> iterator = splittedElement.iterator();
1483 final int length = Iterables.size(splittedElement);
1485 identity = findIdentityByName(module.getIdentities(), iterator.next());
1486 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1487 } else if (length == 2) {
1488 final String prefix = iterator.next();
1489 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1490 if (dependentModule == null) {
1491 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1494 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1495 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1497 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1500 if (identity == null) {
1501 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1505 final Class<RoutingContext> clazz = RoutingContext.class;
1506 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1507 clazz.getSimpleName());
1508 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1509 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1510 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1515 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1516 for (final IdentitySchemaNode id : identities) {
1517 if (id.getQName().getLocalName().equals(name)) {
1524 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1525 for (final ModuleImport imp : imports) {
1526 if (imp.getPrefix().equals(prefix)) {
1527 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1533 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1534 final boolean isReadOnly, final Module module) {
1535 if ((leaf != null) && (toBuilder != null)) {
1536 String leafDesc = leaf.getDescription();
1537 if (leafDesc == null) {
1540 Type returnType = null;
1541 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1542 if (typeDef instanceof UnionTypeDefinition) {
1543 // GeneratedType for this type definition should be already
1545 final QName qname = typeDef.getQName();
1546 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1547 qname.getRevision());
1548 final ModuleContext mc = genCtx.get(unionModule);
1549 returnType = mc.getTypedefs().get(typeDef.getPath());
1550 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1551 // Annonymous enumeration (already generated, since it is inherited via uses).
1552 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1553 QName qname = originalLeaf.getQName();
1554 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1555 qname.getRevision());
1556 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1558 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1560 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1566 * Converts <code>leaf</code> schema node to property of generated TO
1570 * generated TO builder to which is <code>leaf</code> added as
1573 * leaf schema node which is added to <code>toBuilder</code> as
1578 * boolean value which says if leaf property is|isn't read only
1579 * @return boolean value
1581 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1582 * name equals null or if leaf is added by <i>uses</i>.</li>
1583 * <li>true - other cases</li>
1586 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1587 final Type returnType, final boolean isReadOnly) {
1588 if (returnType == null) {
1591 final String leafName = leaf.getQName().getLocalName();
1592 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1593 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1594 propBuilder.setReadOnly(isReadOnly);
1595 propBuilder.setReturnType(returnType);
1596 propBuilder.setComment(leafDesc);
1597 toBuilder.addEqualsIdentity(propBuilder);
1598 toBuilder.addHashIdentity(propBuilder);
1599 toBuilder.addToStringProperty(propBuilder);
1604 * Converts <code>node</code> leaf list schema node to getter method of
1605 * <code>typeBuilder</code>.
1607 * @param typeBuilder
1608 * generated type builder to which is <code>node</code> added as
1611 * leaf list schema node which is added to
1612 * <code>typeBuilder</code> as getter method
1614 * @return boolean value
1616 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1617 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1618 * <li>false - other cases</li>
1621 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1622 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1626 final QName nodeName = node.getQName();
1627 if (nodeName == null) {
1631 final TypeDefinition<?> typeDef = node.getType();
1632 final Module parentModule = findParentModule(schemaContext, node);
1634 Type returnType = null;
1635 if (typeDef.getBaseType() == null) {
1636 if (typeDef instanceof EnumTypeDefinition) {
1637 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1638 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1639 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1640 typeBuilder,module);
1641 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1642 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1643 } else if (typeDef instanceof UnionTypeDefinition) {
1644 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1645 if (genTOBuilder != null) {
1646 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1648 } else if (typeDef instanceof BitsTypeDefinition) {
1649 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1650 returnType = genTOBuilder.toInstance();
1652 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1653 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1656 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1657 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1660 final ParameterizedType listType = Types.listTypeFor(returnType);
1661 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1665 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1666 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1667 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1668 genTOBuilder.getName());
1669 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1671 returnType.setDescription(typedefDescription);
1672 returnType.setReference(typeDef.getReference());
1673 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1674 returnType.setModuleName(parentModule.getName());
1676 genTOBuilder.setTypedef(true);
1677 genTOBuilder.setIsUnion(true);
1678 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1682 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1685 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1686 method.setReturnType(returnType);
1687 method.addParameter(Types.STRING, "defaultValue");
1688 method.setAccessModifier(AccessModifier.PUBLIC);
1689 method.setStatic(true);
1691 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1692 if (types == null) {
1693 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1694 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1696 types.add(unionBuilder.toInstance());
1698 return returnType.toInstance();
1701 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1702 final String outerCls = Types.getOuterClassName(genTOBuilder);
1703 final StringBuilder name;
1704 if (outerCls != null) {
1705 name = new StringBuilder(outerCls);
1707 name = new StringBuilder();
1709 name.append(genTOBuilder.getName());
1710 name.append("Builder");
1711 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1712 unionBuilder.setIsUnionBuilder(true);
1713 return unionBuilder;
1716 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1717 final Module module) {
1718 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1722 * Instantiates generated type builder with <code>packageName</code> and
1723 * <code>schemaNode</code>.
1725 * The new builder always implements
1726 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1727 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1728 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1730 * If <code>schemaNode</code> is instance of
1731 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1732 * DataNodeContainer} it can also implement nodes which are specified in
1735 * @param packageName
1736 * string with the name of the package to which
1737 * <code>schemaNode</code> belongs.
1739 * schema node for which is created generated type builder
1741 * parent type (can be null)
1742 * @return generated type builder <code>schemaNode</code>
1744 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1745 final Type parent, final Module module) {
1746 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1747 if (parent == null) {
1748 it.addImplementsType(DATA_OBJECT);
1750 it.addImplementsType(BindingTypes.childOf(parent));
1752 if (!(schemaNode instanceof GroupingDefinition)) {
1753 it.addImplementsType(augmentable(it));
1756 if (schemaNode instanceof DataNodeContainer) {
1757 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1758 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1765 * Wraps the calling of the same overloaded method.
1767 * @param packageName
1768 * string with the package name to which returning generated type
1771 * schema node which provide data about the schema node name
1772 * @return generated type builder for <code>schemaNode</code>
1774 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1775 return addRawInterfaceDefinition(packageName, schemaNode, "");
1779 * Returns reference to generated type builder for specified
1780 * <code>schemaNode</code> with <code>packageName</code>.
1782 * Firstly the generated type builder is searched in
1783 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1784 * found it is created and added to <code>genTypeBuilders</code>.
1786 * @param packageName
1787 * string with the package name to which returning generated type
1790 * schema node which provide data about the schema node name
1792 * return type name prefix
1793 * @return generated type builder for <code>schemaNode</code>
1794 * @throws IllegalArgumentException
1796 * <li>if <code>schemaNode</code> is null</li>
1797 * <li>if <code>packageName</code> is null</li>
1798 * <li>if QName of schema node is null</li>
1799 * <li>if schemaNode name is null</li>
1803 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1804 final String prefix) {
1805 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1806 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1807 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1808 final String schemaNodeName = schemaNode.getQName().getLocalName();
1809 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1812 if (prefix == null) {
1813 genTypeName = BindingMapping.getClassName(schemaNodeName);
1815 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1818 // FIXME: Validation of name conflict
1819 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1820 final Module module = findParentModule(schemaContext, schemaNode);
1821 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1822 newType.addComment(schemaNode.getDescription());
1823 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1824 newType.setReference(schemaNode.getReference());
1825 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1826 newType.setModuleName(module.getName());
1828 if (!genTypeBuilders.containsKey(packageName)) {
1829 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1830 builders.put(genTypeName, newType);
1831 genTypeBuilders.put(packageName, builders);
1833 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1834 if (!builders.containsKey(genTypeName)) {
1835 builders.put(genTypeName, newType);
1842 * Creates the name of the getter method name from <code>localName</code>.
1845 * string with the name of the getter method
1848 * @return string with the name of the getter method for
1849 * <code>methodName</code> in JAVA method format
1851 public static String getterMethodName(final String localName, final Type returnType) {
1852 final StringBuilder method = new StringBuilder();
1853 if (BOOLEAN.equals(returnType)) {
1854 method.append("is");
1856 method.append("get");
1858 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1859 method.append(name);
1860 return method.toString();
1864 * Created a method signature builder as part of
1865 * <code>interfaceBuilder</code>.
1867 * The method signature builder is created for the getter method of
1868 * <code>schemaNodeName</code>. Also <code>comment</code> and
1869 * <code>returnType</code> information are added to the builder.
1871 * @param interfaceBuilder
1872 * generated type builder for which the getter method should be
1874 * @param schemaNodeName
1875 * string with schema node name. The name will be the part of the
1876 * getter method name.
1878 * string with comment for the getter method
1880 * type which represents the return type of the getter method
1882 * status from yang file, for deprecated annotation
1883 * @return method signature builder which represents the getter method of
1884 * <code>interfaceBuilder</code>
1886 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1887 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1888 final MethodSignatureBuilder getMethod = interfaceBuilder
1889 .addMethod(getterMethodName(schemaNodeName, returnType));
1890 if (status == Status.DEPRECATED) {
1891 getMethod.addAnnotation("", "Deprecated");
1893 getMethod.setComment(encodeAngleBrackets(comment));
1894 getMethod.setReturnType(returnType);
1899 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1900 * or to <code>genTOBuilder</code> as property.
1902 * @param basePackageName
1903 * string contains the module package name
1905 * data schema node which should be added as getter method to
1906 * <code>typeBuilder</code> or as a property to
1907 * <code>genTOBuilder</code> if is part of the list key
1908 * @param typeBuilder
1909 * generated type builder for the list schema node
1910 * @param genTOBuilder
1911 * generated TO builder for the list keys
1913 * list of string which contains names of the list keys
1916 * @throws IllegalArgumentException
1918 * <li>if <code>schemaNode</code> equals null</li>
1919 * <li>if <code>typeBuilder</code> equals null</li>
1922 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1923 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1924 final Module module) {
1925 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1926 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1928 if (schemaNode instanceof LeafSchemaNode) {
1929 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1930 final String leafName = leaf.getQName().getLocalName();
1931 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1932 if (listKeys.contains(leafName)) {
1934 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1936 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1939 } else if (!schemaNode.isAddedByUses()) {
1940 if (schemaNode instanceof LeafListSchemaNode) {
1941 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1942 } else if (schemaNode instanceof ContainerSchemaNode) {
1943 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1944 } else if (schemaNode instanceof ChoiceSchemaNode) {
1945 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1946 } else if (schemaNode instanceof ListSchemaNode) {
1947 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1952 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1953 final GeneratedTOBuilder genTOBuilder) {
1954 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1956 if (genTOBuilder != null) {
1957 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1958 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1959 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1964 * Selects the names of the list keys from <code>list</code> and returns
1965 * them as the list of the strings
1968 * of string with names of the list keys
1969 * @return list of string which represents names of the list keys. If the
1970 * <code>list</code> contains no keys then the empty list is
1973 private static List<String> listKeys(final ListSchemaNode list) {
1974 final List<String> listKeys = new ArrayList<>();
1976 final List<QName> keyDefinition = list.getKeyDefinition();
1977 if (keyDefinition != null) {
1978 for (final QName keyDef : keyDefinition) {
1979 listKeys.add(keyDef.getLocalName());
1986 * Generates for the <code>list</code> which contains any list keys special
1987 * generated TO builder.
1989 * @param packageName
1990 * string with package name to which the list belongs
1992 * list schema node which is source of data about the list name
1993 * @return generated TO builder which represents the keys of the
1994 * <code>list</code> or null if <code>list</code> is null or list of
1995 * key definitions is null or empty.
1997 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1998 GeneratedTOBuilder genTOBuilder = null;
1999 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2000 final String listName = list.getQName().getLocalName() + "Key";
2001 final String genTOName = BindingMapping.getClassName(listName);
2002 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2004 return genTOBuilder;
2008 * Builds generated TO builders for <code>typeDef</code> of type
2009 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2010 * also added to <code>typeBuilder</code> as enclosing transfer object.
2012 * If more then one generated TO builder is created for enclosing then all
2013 * of the generated TO builders are added to <code>typeBuilder</code> as
2014 * enclosing transfer objects.
2017 * type definition which can be of type <code>UnionType</code> or
2018 * <code>BitsTypeDefinition</code>
2019 * @param typeBuilder
2020 * generated type builder to which is added generated TO created
2021 * from <code>typeDef</code>
2023 * string with name for generated TO builder
2025 * @return generated TO builder for <code>typeDef</code>
2027 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2028 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2029 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2030 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2031 final String packageName = typeBuilder.getFullyQualifiedName();
2032 if (typeDef instanceof UnionTypeDefinition) {
2033 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2034 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2035 classNameFromLeaf, leaf);
2036 genTOBuilders.addAll(types);
2038 GeneratedTOBuilder resultTOBuilder = null;
2039 if (types.isEmpty()) {
2040 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2042 resultTOBuilder = types.remove(0);
2043 for (final GeneratedTOBuilder genTOBuilder : types) {
2044 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2047 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2048 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2049 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2050 resultTOBuilder.addHashIdentity(genPropBuilder);
2051 resultTOBuilder.addToStringProperty(genPropBuilder);
2053 } else if (typeDef instanceof BitsTypeDefinition) {
2054 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2055 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2057 if (!genTOBuilders.isEmpty()) {
2058 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2059 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2061 return genTOBuilders.get(0);
2068 * Adds the implemented types to type builder.
2070 * The method passes through the list of <i>uses</i> in
2071 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2072 * generated type from {@link BindingGeneratorImpl#allGroupings
2073 * allGroupings} which is added as <i>implements type</i> to
2074 * <code>builder</code>
2076 * @param dataNodeContainer
2077 * element which contains the list of used YANG groupings
2079 * builder to which are added implemented types according to
2080 * <code>dataNodeContainer</code>
2081 * @return generated type builder with all implemented types
2083 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2084 final GeneratedTypeBuilder builder) {
2085 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2086 if (usesNode.getGroupingPath() != null) {
2087 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2088 if (genType == null) {
2089 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2090 + builder.getName());
2093 builder.addImplementsType(genType);
2095 builder.addComment(genType.getDescription());
2096 builder.setDescription(genType.getDescription());
2097 builder.setModuleName(genType.getModuleName());
2098 builder.setReference(genType.getReference());
2099 builder.setSchemaPath(genType.getSchemaPath());
2106 private static boolean isNullOrEmpty(final Collection<?> list) {
2107 return list == null || list.isEmpty();
2110 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2111 final StringBuilder sb = new StringBuilder();
2113 if (!isNullOrEmpty(schemaNodes)) {
2114 final SchemaNode node = schemaNodes.iterator().next();
2116 if (node instanceof RpcDefinition) {
2117 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2118 } else if (node instanceof NotificationDefinition) {
2119 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2122 sb.append(NEW_LINE);
2124 if (verboseClassComments) {
2126 sb.append(NEW_LINE);
2127 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2128 sb.append("</pre>");
2129 sb.append(NEW_LINE);
2132 return replaceAllIllegalChars(sb);
2135 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2136 final StringBuilder sb = new StringBuilder();
2137 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2138 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2140 if (!Strings.isNullOrEmpty(formattedDescription)) {
2141 sb.append(formattedDescription);
2142 sb.append(NEW_LINE);
2145 if (verboseClassComments) {
2146 final Module module = findParentModule(schemaContext, schemaNode);
2147 final StringBuilder linkToBuilderClass = new StringBuilder();
2148 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2149 final String className = namespace[namespace.length - 1];
2151 if (hasBuilderClass(schemaNode)) {
2152 linkToBuilderClass.append(className);
2153 linkToBuilderClass.append("Builder");
2157 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2158 sb.append(module.getName());
2160 sb.append(NEW_LINE);
2162 sb.append(NEW_LINE);
2163 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2164 sb.append("</pre>");
2165 sb.append(NEW_LINE);
2166 sb.append("The schema path to identify an instance is");
2167 sb.append(NEW_LINE);
2169 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2171 sb.append(NEW_LINE);
2173 if (hasBuilderClass(schemaNode)) {
2174 sb.append(NEW_LINE);
2175 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2176 sb.append(NEW_LINE);
2178 sb.append(linkToBuilderClass);
2179 sb.append(NEW_LINE);
2180 if (schemaNode instanceof ListSchemaNode) {
2181 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2182 if (keyDef != null && !keyDef.isEmpty()) {
2184 sb.append(className);
2187 sb.append(NEW_LINE);
2192 return replaceAllIllegalChars(sb);
2195 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2196 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2197 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2203 private String createDescription(final Module module) {
2204 final StringBuilder sb = new StringBuilder();
2205 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2206 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2208 if (!Strings.isNullOrEmpty(formattedDescription)) {
2209 sb.append(formattedDescription);
2210 sb.append(NEW_LINE);
2213 if (verboseClassComments) {
2215 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2216 sb.append(module.getName());
2218 sb.append(NEW_LINE);
2220 sb.append(NEW_LINE);
2221 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2222 sb.append("</pre>");
2225 return replaceAllIllegalChars(sb);
2228 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2229 for (final ModuleContext ctx : genCtx.values()) {
2230 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2231 if (result != null) {
2238 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2239 for (final ModuleContext ctx : genCtx.values()) {
2240 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2241 if (result != null) {
2248 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2249 for (final ModuleContext ctx : genCtx.values()) {
2250 final GeneratedTypeBuilder result = ctx.getCase(path);
2251 if (result != null) {
2258 public Map<Module, ModuleContext> getModuleContexts() {
2263 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2264 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2265 return ret.isEmpty() ? "" : ret;
2268 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2269 if (status == Status.DEPRECATED) {
2270 builder.addAnnotation("", "Deprecated");