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 // finding by local name is valid, grouping cannot contain nodes
916 // with same name and different namespace
917 if (result instanceof DataNodeContainer) {
918 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
919 } else if (result instanceof ChoiceSchemaNode) {
920 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
923 if (result == null) {
927 if (result instanceof DerivableSchemaNode) {
928 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
929 Optional<? extends SchemaNode> originalNode = castedResult
931 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
932 result = originalNode.get();
936 if (result instanceof DataSchemaNode) {
937 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
938 if (resultDataSchemaNode.isAddedByUses()) {
939 // The original node is required, but we have only the copy of
940 // the original node.
941 // Maybe this indicates a bug in Yang parser.
942 throw new IllegalStateException(
943 "Failed to generate code for augment in "
946 return resultDataSchemaNode;
949 throw new IllegalStateException(
950 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
956 * Returns a generated type builder for an augmentation.
958 * The name of the type builder is equal to the name of augmented node with
959 * serial number as suffix.
963 * @param augmentPackageName
964 * string with contains the package name to which the augment
966 * @param basePackageName
967 * string with the package name to which the augmented node
969 * @param targetTypeRef
972 * augmentation schema which contains data about the child nodes
973 * and uses of augment
974 * @return generated type builder for augment
976 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
977 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
978 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
979 if (augmentBuilders == null) {
980 augmentBuilders = new HashMap<>();
981 genTypeBuilders.put(augmentPackageName, augmentBuilders);
983 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
986 if (augIdentifier != null) {
987 augTypeName = BindingMapping.getClassName(augIdentifier);
989 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
992 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
994 augTypeBuilder.addImplementsType(DATA_OBJECT);
995 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
996 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
997 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
999 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1000 augmentBuilders.put(augTypeName, augTypeBuilder);
1002 if(!augSchema.getChildNodes().isEmpty()) {
1003 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
1004 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1007 genCtx.get(module).addAugmentType(augTypeBuilder);
1008 return augTypeBuilder;
1013 * @param unknownSchemaNodes
1014 * @return nodeParameter of UnknownSchemaNode
1016 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1017 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1018 final QName nodeType = unknownSchemaNode.getNodeType();
1019 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1020 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1021 return unknownSchemaNode.getNodeParameter();
1028 * Returns first unique name for the augment generated type builder. The
1029 * generated type builder name for augment consists from name of augmented
1030 * node and serial number of its augmentation.
1033 * map of builders which were created in the package to which the
1034 * augmentation belongs
1035 * @param genTypeName
1036 * string with name of augmented node
1037 * @return string with unique name for augmentation builder
1039 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1041 if (builders != null) {
1042 while (builders.containsKey(genTypeName + index)) {
1046 return genTypeName + index;
1050 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1051 * node for which <code>typeBuilder</code> was created.
1053 * The subnodes aren't mapped to the methods if they are part of grouping or
1054 * augment (in this case are already part of them).
1058 * @param basePackageName
1059 * string contains the module package name
1061 * generated type builder which represents any node. The subnodes
1062 * of this node are added to the <code>typeBuilder</code> as
1063 * methods. The subnode can be of type leaf, leaf-list, list,
1064 * container, choice.
1067 * @param schemaNodes
1068 * set of data schema nodes which are the children of the node
1069 * for which <code>typeBuilder</code> was created
1070 * @return generated type builder which is the same builder as input
1071 * parameter. The getter methods (representing child nodes) could be
1074 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1075 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1076 if (schemaNodes != null && parent != null) {
1077 for (final DataSchemaNode schemaNode : schemaNodes) {
1078 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1079 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1087 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1088 * node for which <code>typeBuilder</code> was created.
1092 * @param basePackageName
1093 * string contains the module package name
1094 * @param typeBuilder
1095 * generated type builder which represents any node. The subnodes
1096 * of this node are added to the <code>typeBuilder</code> as
1097 * methods. The subnode can be of type leaf, leaf-list, list,
1098 * container, choice.
1101 * @param schemaNodes
1102 * set of data schema nodes which are the children of the node
1103 * for which <code>typeBuilder</code> was created
1104 * @return generated type builder which is the same object as the input
1105 * parameter <code>typeBuilder</code>. The getter method could be
1108 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1109 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1110 final Iterable<DataSchemaNode> schemaNodes) {
1111 if ((schemaNodes != null) && (typeBuilder != null)) {
1112 for (final DataSchemaNode schemaNode : schemaNodes) {
1113 if (!schemaNode.isAugmenting()) {
1114 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1122 * Adds to <code>typeBuilder</code> a method which is derived from
1123 * <code>schemaNode</code>.
1125 * @param basePackageName
1126 * string with the module package name
1128 * data schema node which is added to <code>typeBuilder</code> as
1130 * @param typeBuilder
1131 * generated type builder to which is <code>schemaNode</code>
1132 * added as a method.
1138 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1139 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1140 if (node != null && typeBuilder != null) {
1141 if (node instanceof LeafSchemaNode) {
1142 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1143 } else if (node instanceof LeafListSchemaNode) {
1144 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1145 } else if (node instanceof ContainerSchemaNode) {
1146 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1147 } else if (node instanceof ListSchemaNode) {
1148 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1149 } else if (node instanceof ChoiceSchemaNode) {
1150 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1152 // TODO: anyxml not yet supported
1153 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1154 typeBuilder.getFullyQualifiedName());
1160 * Converts <code>choiceNode</code> to the list of generated types for
1161 * choice and its cases.
1163 * The package names for choice and for its cases are created as
1164 * concatenation of the module package (<code>basePackageName</code>) and
1165 * names of all parents node.
1169 * @param basePackageName
1170 * string with the module package name
1174 * choice node which is mapped to generated type. Also child
1175 * nodes - cases are mapped to generated types.
1176 * @throws IllegalArgumentException
1178 * <li>if <code>basePackageName</code> is null</li>
1179 * <li>if <code>choiceNode</code> is null</li>
1182 private void choiceToGeneratedType(final Module module, final String basePackageName,
1183 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1184 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1185 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1187 if (!choiceNode.isAddedByUses()) {
1188 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1189 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1190 constructGetter(parent, choiceNode.getQName().getLocalName(),
1191 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1192 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1193 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1194 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1195 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1200 * Converts <code>caseNodes</code> set to list of corresponding generated
1203 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1204 * created generated type builder. The package names for the builder is
1205 * created as concatenation of the module package (
1206 * <code>basePackageName</code>) and names of all parents nodes of the
1207 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1208 * between every case builder and <i>choice</i> type
1212 * @param basePackageName
1213 * string with the module package name
1214 * @param refChoiceType
1215 * type which represents superior <i>case</i>
1217 * choice case node which is mapped to generated type
1218 * @return list of generated types for <code>caseNodes</code>.
1219 * @throws IllegalArgumentException
1221 * <li>if <code>basePackageName</code> equals null</li>
1222 * <li>if <code>refChoiceType</code> equals null</li>
1223 * <li>if <code>caseNodes</code> equals null</li>
1226 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1227 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1228 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1229 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1230 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1232 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1233 if (caseNodes == null) {
1237 for (final ChoiceCaseNode caseNode : caseNodes) {
1238 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1239 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1240 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1241 caseTypeBuilder.addImplementsType(refChoiceType);
1242 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1243 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1244 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1245 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1246 if (caseChildNodes != null) {
1247 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1249 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1250 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1252 if (parent instanceof AugmentationSchema) {
1253 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1254 final SchemaPath targetPath = augSchema.getTargetPath();
1255 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1256 if (targetSchemaNode instanceof DataSchemaNode
1257 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1258 if (targetSchemaNode instanceof DerivableSchemaNode) {
1259 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1261 if (targetSchemaNode == null) {
1262 throw new IllegalStateException(
1263 "Failed to find target node from grouping for augmentation " + augSchema
1264 + " in module " + module.getName());
1267 parent = targetSchemaNode;
1270 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1271 choiceNodeParentPath);
1272 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1273 if (childOfType == null) {
1274 childOfType = findGroupingByPath(parent.getPath());
1276 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1278 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1283 processUsesAugments(caseNode, module);
1288 * Generates list of generated types for all the cases of a choice which are
1289 * added to the choice through the augment.
1293 * @param basePackageName
1294 * string contains name of package to which augment belongs. If
1295 * an augmented choice is from an other package (pcg1) than an
1296 * augmenting choice (pcg2) then case's of the augmenting choice
1297 * will belong to pcg2.
1299 * Type which represents target choice
1301 * node which represents target choice
1302 * @param augmentedNodes
1303 * set of choice case nodes for which is checked if are/aren't
1304 * added to choice through augmentation
1305 * @return list of generated types which represents augmented cases of
1306 * choice <code>refChoiceType</code>
1307 * @throws IllegalArgumentException
1309 * <li>if <code>basePackageName</code> is null</li>
1310 * <li>if <code>targetType</code> is null</li>
1311 * <li>if <code>augmentedNodes</code> is null</li>
1314 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1315 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1316 final DataNodeContainer usesNodeParent) {
1317 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1318 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1319 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1321 for (final DataSchemaNode caseNode : augmentedNodes) {
1322 if (caseNode != null) {
1323 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1324 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1325 caseTypeBuilder.addImplementsType(targetType);
1327 SchemaNode parent = null;
1328 final SchemaPath nodeSp = targetNode.getPath();
1329 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1331 GeneratedTypeBuilder childOfType = null;
1332 if (parent instanceof Module) {
1333 childOfType = genCtx.get(parent).getModuleNode();
1334 } else if (parent instanceof ChoiceCaseNode) {
1335 childOfType = findCaseByPath(parent.getPath());
1336 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1337 childOfType = findChildNodeByPath(parent.getPath());
1338 } else if (parent instanceof GroupingDefinition) {
1339 childOfType = findGroupingByPath(parent.getPath());
1342 if (childOfType == null) {
1343 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1346 ChoiceCaseNode node = null;
1347 final String caseLocalName = caseNode.getQName().getLocalName();
1348 if (caseNode instanceof ChoiceCaseNode) {
1349 node = (ChoiceCaseNode) caseNode;
1350 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1351 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1352 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1353 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1354 ().getLocalName())) {
1355 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1360 node = targetNode.getCaseNodeByName(caseLocalName);
1362 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1363 if (childNodes != null) {
1364 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1366 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1367 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1372 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1373 // New parser with encapsulated type
1374 if (leaf.getPath().equals(type.getPath())) {
1378 // Embedded type definition with new parser. Also takes care of the old parser with bits
1379 if (leaf.getPath().equals(type.getPath().getParent())) {
1387 * Converts <code>leaf</code> to the getter method which is added to
1388 * <code>typeBuilder</code>.
1390 * @param typeBuilder
1391 * generated type builder to which is added getter method as
1392 * <code>leaf</code> mapping
1394 * leaf schema node which is mapped as getter method which is
1395 * added to <code>typeBuilder</code>
1397 * Module in which type was defined
1398 * @return boolean value
1400 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1402 * <li>true - in other cases</li>
1405 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1406 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1410 final String leafName = leaf.getQName().getLocalName();
1411 if (leafName == null) {
1415 final Module parentModule = findParentModule(schemaContext, leaf);
1416 Type returnType = null;
1418 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1419 if (isInnerType(leaf, typeDef)) {
1420 if (typeDef instanceof EnumTypeDefinition) {
1421 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1422 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1423 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1424 typeBuilder, module);
1426 if (enumBuilder != null) {
1427 returnType = enumBuilder.toInstance(typeBuilder);
1429 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1430 } else if (typeDef instanceof UnionTypeDefinition) {
1431 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1432 if (genTOBuilder != null) {
1433 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1435 } else if (typeDef instanceof BitsTypeDefinition) {
1436 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1437 if (genTOBuilder != null) {
1438 returnType = genTOBuilder.toInstance();
1441 // It is constrained version of already declared type (inner declared type exists,
1442 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1443 // In order to get proper class we need to look up closest derived type
1444 // and apply restrictions from leaf type
1445 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1446 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1450 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1451 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1454 if (returnType == null) {
1458 String leafDesc = leaf.getDescription();
1459 if (leafDesc == null) {
1463 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1464 processContextRefExtension(leaf, getter, parentModule);
1468 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1469 // Returns DerivedType in case of new parser.
1470 final TypeDefinition<?> baseType = typeDef.getBaseType();
1471 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1474 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1475 final Module module) {
1476 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1477 final QName nodeType = node.getNodeType();
1478 if ("context-reference".equals(nodeType.getLocalName())) {
1479 final String nodeParam = node.getNodeParameter();
1480 IdentitySchemaNode identity = null;
1481 String basePackageName = null;
1482 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1483 final Iterator<String> iterator = splittedElement.iterator();
1484 final int length = Iterables.size(splittedElement);
1486 identity = findIdentityByName(module.getIdentities(), iterator.next());
1487 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1488 } else if (length == 2) {
1489 final String prefix = iterator.next();
1490 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1491 if (dependentModule == null) {
1492 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1495 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1496 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1498 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1501 if (identity == null) {
1502 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1506 final Class<RoutingContext> clazz = RoutingContext.class;
1507 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1508 clazz.getSimpleName());
1509 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1510 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1511 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1516 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1517 for (final IdentitySchemaNode id : identities) {
1518 if (id.getQName().getLocalName().equals(name)) {
1525 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1526 for (final ModuleImport imp : imports) {
1527 if (imp.getPrefix().equals(prefix)) {
1528 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1534 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1535 final boolean isReadOnly, final Module module) {
1536 if ((leaf != null) && (toBuilder != null)) {
1537 String leafDesc = leaf.getDescription();
1538 if (leafDesc == null) {
1541 Type returnType = null;
1542 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1543 if (typeDef instanceof UnionTypeDefinition) {
1544 // GeneratedType for this type definition should be already
1546 final QName qname = typeDef.getQName();
1547 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1548 qname.getRevision());
1549 final ModuleContext mc = genCtx.get(unionModule);
1550 returnType = mc.getTypedefs().get(typeDef.getPath());
1551 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1552 // Annonymous enumeration (already generated, since it is inherited via uses).
1553 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1554 QName qname = originalLeaf.getQName();
1555 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1556 qname.getRevision());
1557 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1559 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1561 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1567 * Converts <code>leaf</code> schema node to property of generated TO
1571 * generated TO builder to which is <code>leaf</code> added as
1574 * leaf schema node which is added to <code>toBuilder</code> as
1579 * boolean value which says if leaf property is|isn't read only
1580 * @return boolean value
1582 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1583 * name equals null or if leaf is added by <i>uses</i>.</li>
1584 * <li>true - other cases</li>
1587 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1588 final Type returnType, final boolean isReadOnly) {
1589 if (returnType == null) {
1592 final String leafName = leaf.getQName().getLocalName();
1593 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1594 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1595 propBuilder.setReadOnly(isReadOnly);
1596 propBuilder.setReturnType(returnType);
1597 propBuilder.setComment(leafDesc);
1598 toBuilder.addEqualsIdentity(propBuilder);
1599 toBuilder.addHashIdentity(propBuilder);
1600 toBuilder.addToStringProperty(propBuilder);
1605 * Converts <code>node</code> leaf list schema node to getter method of
1606 * <code>typeBuilder</code>.
1608 * @param typeBuilder
1609 * generated type builder to which is <code>node</code> added as
1612 * leaf list schema node which is added to
1613 * <code>typeBuilder</code> as getter method
1615 * @return boolean value
1617 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1618 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1619 * <li>false - other cases</li>
1622 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1623 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1627 final QName nodeName = node.getQName();
1628 if (nodeName == null) {
1632 final TypeDefinition<?> typeDef = node.getType();
1633 final Module parentModule = findParentModule(schemaContext, node);
1635 Type returnType = null;
1636 if (typeDef.getBaseType() == null) {
1637 if (typeDef instanceof EnumTypeDefinition) {
1638 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1639 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1640 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1641 typeBuilder,module);
1642 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1643 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1644 } else if (typeDef instanceof UnionTypeDefinition) {
1645 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1646 if (genTOBuilder != null) {
1647 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1649 } else if (typeDef instanceof BitsTypeDefinition) {
1650 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1651 returnType = genTOBuilder.toInstance();
1653 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1654 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1657 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1658 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1661 final ParameterizedType listType = Types.listTypeFor(returnType);
1662 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1666 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1667 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1668 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1669 genTOBuilder.getName());
1670 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1672 returnType.setDescription(typedefDescription);
1673 returnType.setReference(typeDef.getReference());
1674 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1675 returnType.setModuleName(parentModule.getName());
1677 genTOBuilder.setTypedef(true);
1678 genTOBuilder.setIsUnion(true);
1679 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1683 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1686 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1687 method.setReturnType(returnType);
1688 method.addParameter(Types.STRING, "defaultValue");
1689 method.setAccessModifier(AccessModifier.PUBLIC);
1690 method.setStatic(true);
1692 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1693 if (types == null) {
1694 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1695 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1697 types.add(unionBuilder.toInstance());
1699 return returnType.toInstance();
1702 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1703 final String outerCls = Types.getOuterClassName(genTOBuilder);
1704 final StringBuilder name;
1705 if (outerCls != null) {
1706 name = new StringBuilder(outerCls);
1708 name = new StringBuilder();
1710 name.append(genTOBuilder.getName());
1711 name.append("Builder");
1712 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1713 unionBuilder.setIsUnionBuilder(true);
1714 return unionBuilder;
1717 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1718 final Module module) {
1719 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1723 * Instantiates generated type builder with <code>packageName</code> and
1724 * <code>schemaNode</code>.
1726 * The new builder always implements
1727 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1728 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1729 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1731 * If <code>schemaNode</code> is instance of
1732 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1733 * DataNodeContainer} it can also implement nodes which are specified in
1736 * @param packageName
1737 * string with the name of the package to which
1738 * <code>schemaNode</code> belongs.
1740 * schema node for which is created generated type builder
1742 * parent type (can be null)
1743 * @return generated type builder <code>schemaNode</code>
1745 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1746 final Type parent, final Module module) {
1747 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1748 if (parent == null) {
1749 it.addImplementsType(DATA_OBJECT);
1751 it.addImplementsType(BindingTypes.childOf(parent));
1753 if (!(schemaNode instanceof GroupingDefinition)) {
1754 it.addImplementsType(augmentable(it));
1757 if (schemaNode instanceof DataNodeContainer) {
1758 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1759 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1766 * Wraps the calling of the same overloaded method.
1768 * @param packageName
1769 * string with the package name to which returning generated type
1772 * schema node which provide data about the schema node name
1773 * @return generated type builder for <code>schemaNode</code>
1775 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1776 return addRawInterfaceDefinition(packageName, schemaNode, "");
1780 * Returns reference to generated type builder for specified
1781 * <code>schemaNode</code> with <code>packageName</code>.
1783 * Firstly the generated type builder is searched in
1784 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1785 * found it is created and added to <code>genTypeBuilders</code>.
1787 * @param packageName
1788 * string with the package name to which returning generated type
1791 * schema node which provide data about the schema node name
1793 * return type name prefix
1794 * @return generated type builder for <code>schemaNode</code>
1795 * @throws IllegalArgumentException
1797 * <li>if <code>schemaNode</code> is null</li>
1798 * <li>if <code>packageName</code> is null</li>
1799 * <li>if QName of schema node is null</li>
1800 * <li>if schemaNode name is null</li>
1804 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1805 final String prefix) {
1806 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1807 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1808 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1809 final String schemaNodeName = schemaNode.getQName().getLocalName();
1810 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1813 if (prefix == null) {
1814 genTypeName = BindingMapping.getClassName(schemaNodeName);
1816 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1819 // FIXME: Validation of name conflict
1820 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1821 final Module module = findParentModule(schemaContext, schemaNode);
1822 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1823 newType.addComment(schemaNode.getDescription());
1824 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1825 newType.setReference(schemaNode.getReference());
1826 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1827 newType.setModuleName(module.getName());
1829 if (!genTypeBuilders.containsKey(packageName)) {
1830 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1831 builders.put(genTypeName, newType);
1832 genTypeBuilders.put(packageName, builders);
1834 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1835 if (!builders.containsKey(genTypeName)) {
1836 builders.put(genTypeName, newType);
1843 * Creates the name of the getter method name from <code>localName</code>.
1846 * string with the name of the getter method
1849 * @return string with the name of the getter method for
1850 * <code>methodName</code> in JAVA method format
1852 public static String getterMethodName(final String localName, final Type returnType) {
1853 final StringBuilder method = new StringBuilder();
1854 if (BOOLEAN.equals(returnType)) {
1855 method.append("is");
1857 method.append("get");
1859 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1860 method.append(name);
1861 return method.toString();
1865 * Created a method signature builder as part of
1866 * <code>interfaceBuilder</code>.
1868 * The method signature builder is created for the getter method of
1869 * <code>schemaNodeName</code>. Also <code>comment</code> and
1870 * <code>returnType</code> information are added to the builder.
1872 * @param interfaceBuilder
1873 * generated type builder for which the getter method should be
1875 * @param schemaNodeName
1876 * string with schema node name. The name will be the part of the
1877 * getter method name.
1879 * string with comment for the getter method
1881 * type which represents the return type of the getter method
1883 * status from yang file, for deprecated annotation
1884 * @return method signature builder which represents the getter method of
1885 * <code>interfaceBuilder</code>
1887 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1888 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1889 final MethodSignatureBuilder getMethod = interfaceBuilder
1890 .addMethod(getterMethodName(schemaNodeName, returnType));
1891 if (status == Status.DEPRECATED) {
1892 getMethod.addAnnotation("", "Deprecated");
1894 getMethod.setComment(encodeAngleBrackets(comment));
1895 getMethod.setReturnType(returnType);
1900 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1901 * or to <code>genTOBuilder</code> as property.
1903 * @param basePackageName
1904 * string contains the module package name
1906 * data schema node which should be added as getter method to
1907 * <code>typeBuilder</code> or as a property to
1908 * <code>genTOBuilder</code> if is part of the list key
1909 * @param typeBuilder
1910 * generated type builder for the list schema node
1911 * @param genTOBuilder
1912 * generated TO builder for the list keys
1914 * list of string which contains names of the list keys
1917 * @throws IllegalArgumentException
1919 * <li>if <code>schemaNode</code> equals null</li>
1920 * <li>if <code>typeBuilder</code> equals null</li>
1923 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1924 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1925 final Module module) {
1926 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1927 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1929 if (schemaNode instanceof LeafSchemaNode) {
1930 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1931 final String leafName = leaf.getQName().getLocalName();
1932 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1933 if (listKeys.contains(leafName)) {
1935 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1937 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1940 } else if (!schemaNode.isAddedByUses()) {
1941 if (schemaNode instanceof LeafListSchemaNode) {
1942 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1943 } else if (schemaNode instanceof ContainerSchemaNode) {
1944 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1945 } else if (schemaNode instanceof ChoiceSchemaNode) {
1946 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1947 } else if (schemaNode instanceof ListSchemaNode) {
1948 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1953 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1954 final GeneratedTOBuilder genTOBuilder) {
1955 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1957 if (genTOBuilder != null) {
1958 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1959 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1960 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1965 * Selects the names of the list keys from <code>list</code> and returns
1966 * them as the list of the strings
1969 * of string with names of the list keys
1970 * @return list of string which represents names of the list keys. If the
1971 * <code>list</code> contains no keys then the empty list is
1974 private static List<String> listKeys(final ListSchemaNode list) {
1975 final List<String> listKeys = new ArrayList<>();
1977 final List<QName> keyDefinition = list.getKeyDefinition();
1978 if (keyDefinition != null) {
1979 for (final QName keyDef : keyDefinition) {
1980 listKeys.add(keyDef.getLocalName());
1987 * Generates for the <code>list</code> which contains any list keys special
1988 * generated TO builder.
1990 * @param packageName
1991 * string with package name to which the list belongs
1993 * list schema node which is source of data about the list name
1994 * @return generated TO builder which represents the keys of the
1995 * <code>list</code> or null if <code>list</code> is null or list of
1996 * key definitions is null or empty.
1998 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1999 GeneratedTOBuilder genTOBuilder = null;
2000 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2001 final String listName = list.getQName().getLocalName() + "Key";
2002 final String genTOName = BindingMapping.getClassName(listName);
2003 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2005 return genTOBuilder;
2009 * Builds generated TO builders for <code>typeDef</code> of type
2010 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2011 * also added to <code>typeBuilder</code> as enclosing transfer object.
2013 * If more then one generated TO builder is created for enclosing then all
2014 * of the generated TO builders are added to <code>typeBuilder</code> as
2015 * enclosing transfer objects.
2018 * type definition which can be of type <code>UnionType</code> or
2019 * <code>BitsTypeDefinition</code>
2020 * @param typeBuilder
2021 * generated type builder to which is added generated TO created
2022 * from <code>typeDef</code>
2024 * string with name for generated TO builder
2026 * @return generated TO builder for <code>typeDef</code>
2028 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2029 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2030 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2031 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2032 final String packageName = typeBuilder.getFullyQualifiedName();
2033 if (typeDef instanceof UnionTypeDefinition) {
2034 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2035 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2036 classNameFromLeaf, leaf);
2037 genTOBuilders.addAll(types);
2039 GeneratedTOBuilder resultTOBuilder = null;
2040 if (types.isEmpty()) {
2041 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2043 resultTOBuilder = types.remove(0);
2044 for (final GeneratedTOBuilder genTOBuilder : types) {
2045 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2048 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2049 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2050 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2051 resultTOBuilder.addHashIdentity(genPropBuilder);
2052 resultTOBuilder.addToStringProperty(genPropBuilder);
2054 } else if (typeDef instanceof BitsTypeDefinition) {
2055 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2056 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2058 if (!genTOBuilders.isEmpty()) {
2059 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2060 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2062 return genTOBuilders.get(0);
2069 * Adds the implemented types to type builder.
2071 * The method passes through the list of <i>uses</i> in
2072 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2073 * generated type from {@link BindingGeneratorImpl#allGroupings
2074 * allGroupings} which is added as <i>implements type</i> to
2075 * <code>builder</code>
2077 * @param dataNodeContainer
2078 * element which contains the list of used YANG groupings
2080 * builder to which are added implemented types according to
2081 * <code>dataNodeContainer</code>
2082 * @return generated type builder with all implemented types
2084 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2085 final GeneratedTypeBuilder builder) {
2086 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2087 if (usesNode.getGroupingPath() != null) {
2088 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2089 if (genType == null) {
2090 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2091 + builder.getName());
2094 builder.addImplementsType(genType);
2096 builder.addComment(genType.getDescription());
2097 builder.setDescription(genType.getDescription());
2098 builder.setModuleName(genType.getModuleName());
2099 builder.setReference(genType.getReference());
2100 builder.setSchemaPath(genType.getSchemaPath());
2107 private static boolean isNullOrEmpty(final Collection<?> list) {
2108 return list == null || list.isEmpty();
2111 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2112 final StringBuilder sb = new StringBuilder();
2114 if (!isNullOrEmpty(schemaNodes)) {
2115 final SchemaNode node = schemaNodes.iterator().next();
2117 if (node instanceof RpcDefinition) {
2118 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2119 } else if (node instanceof NotificationDefinition) {
2120 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2123 sb.append(NEW_LINE);
2125 if (verboseClassComments) {
2127 sb.append(NEW_LINE);
2128 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2129 sb.append("</pre>");
2130 sb.append(NEW_LINE);
2133 return replaceAllIllegalChars(sb);
2136 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2137 final StringBuilder sb = new StringBuilder();
2138 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2139 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2141 if (!Strings.isNullOrEmpty(formattedDescription)) {
2142 sb.append(formattedDescription);
2143 sb.append(NEW_LINE);
2146 if (verboseClassComments) {
2147 final Module module = findParentModule(schemaContext, schemaNode);
2148 final StringBuilder linkToBuilderClass = new StringBuilder();
2149 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2150 final String className = namespace[namespace.length - 1];
2152 if (hasBuilderClass(schemaNode)) {
2153 linkToBuilderClass.append(className);
2154 linkToBuilderClass.append("Builder");
2158 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2159 sb.append(module.getName());
2161 sb.append(NEW_LINE);
2163 sb.append(NEW_LINE);
2164 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2165 sb.append("</pre>");
2166 sb.append(NEW_LINE);
2167 sb.append("The schema path to identify an instance is");
2168 sb.append(NEW_LINE);
2170 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2172 sb.append(NEW_LINE);
2174 if (hasBuilderClass(schemaNode)) {
2175 sb.append(NEW_LINE);
2176 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2177 sb.append(NEW_LINE);
2179 sb.append(linkToBuilderClass);
2180 sb.append(NEW_LINE);
2181 if (schemaNode instanceof ListSchemaNode) {
2182 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2183 if (keyDef != null && !keyDef.isEmpty()) {
2185 sb.append(className);
2188 sb.append(NEW_LINE);
2193 return replaceAllIllegalChars(sb);
2196 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2197 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2198 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2204 private String createDescription(final Module module) {
2205 final StringBuilder sb = new StringBuilder();
2206 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2207 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2209 if (!Strings.isNullOrEmpty(formattedDescription)) {
2210 sb.append(formattedDescription);
2211 sb.append(NEW_LINE);
2214 if (verboseClassComments) {
2216 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2217 sb.append(module.getName());
2219 sb.append(NEW_LINE);
2221 sb.append(NEW_LINE);
2222 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2223 sb.append("</pre>");
2226 return replaceAllIllegalChars(sb);
2229 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2230 for (final ModuleContext ctx : genCtx.values()) {
2231 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2232 if (result != null) {
2239 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2240 for (final ModuleContext ctx : genCtx.values()) {
2241 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2242 if (result != null) {
2249 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2250 for (final ModuleContext ctx : genCtx.values()) {
2251 final GeneratedTypeBuilder result = ctx.getCase(path);
2252 if (result != null) {
2259 public Map<Module, ModuleContext> getModuleContexts() {
2264 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2265 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2266 return ret.isEmpty() ? "" : ret;
2269 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2270 if (status == Status.DEPRECATED) {
2271 builder.addAnnotation("", "Deprecated");