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.packageNameForAugmentedGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
29 import com.google.common.annotations.VisibleForTesting;
30 import com.google.common.base.Optional;
31 import com.google.common.base.Preconditions;
32 import com.google.common.base.Splitter;
33 import com.google.common.base.Strings;
34 import com.google.common.collect.Iterables;
35 import com.google.common.collect.Sets;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.Iterator;
41 import java.util.List;
44 import java.util.regex.Pattern;
45 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
46 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
47 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
48 import org.opendaylight.yangtools.binding.generator.util.Types;
49 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
50 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
52 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
53 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
54 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
55 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
56 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
57 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
58 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
59 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
60 import org.opendaylight.yangtools.sal.binding.model.api.Type;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
68 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
69 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
70 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
71 import org.opendaylight.yangtools.yang.binding.BindingMapping;
72 import org.opendaylight.yangtools.yang.binding.DataContainer;
73 import org.opendaylight.yangtools.yang.binding.RpcService;
74 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
78 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
85 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
91 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
92 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
96 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.UsesNode;
99 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
103 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
104 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
105 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
106 import org.opendaylight.yangtools.yang.model.util.UnionType;
107 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
108 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
109 import org.slf4j.Logger;
110 import org.slf4j.LoggerFactory;
112 public class BindingGeneratorImpl implements BindingGenerator {
113 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
114 private static final Splitter COLON_SPLITTER = Splitter.on(':');
115 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
116 private static final char NEW_LINE = '\n';
119 * Constant with the concrete name of identifier.
121 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
124 * Constant with the concrete name of namespace.
126 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
128 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
130 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
133 * When set to true, generated classes will include javadoc comments which
134 * are useful for users.
136 private final boolean verboseClassComments;
139 * Outer key represents the package name. Outer value represents map of all
140 * builders in the same package. Inner key represents the schema node name
141 * (in JAVA class/interface name format). Inner value represents instance of
142 * builder for schema node specified in key part.
144 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
147 * Provide methods for converting YANG types to JAVA types.
149 private TypeProvider typeProvider;
152 * Holds reference to schema context to resolve data of augmented element
153 * when creating augmentation builder
155 private SchemaContext schemaContext;
158 * Create a new binding generator.
160 * @param verboseClassComments generate verbose comments
162 public BindingGeneratorImpl(final boolean verboseClassComments) {
163 this.verboseClassComments = verboseClassComments;
167 * Resolves generated types from <code>context</code> schema nodes of all
170 * Generated types are created for modules, groupings, types, containers,
171 * lists, choices, augments, rpcs, notification, identities.
174 * schema context which contains data about all schema nodes
176 * @return list of types (usually <code>GeneratedType</code>
177 * <code>GeneratedTransferObject</code>which are generated from
178 * <code>context</code> data.
179 * @throws IllegalArgumentException
180 * if arg <code>context</code> is null
181 * @throws IllegalStateException
182 * if <code>context</code> contain no modules
185 public List<Type> generateTypes(final SchemaContext context) {
186 checkArgument(context != null, "Schema Context reference cannot be NULL.");
187 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
188 schemaContext = context;
189 typeProvider = new TypeProviderImpl(context);
190 final Set<Module> modules = context.getModules();
191 return generateTypes(context, modules);
195 * Resolves generated types from <code>context</code> schema nodes only for
196 * modules specified in <code>modules</code>
198 * Generated types are created for modules, groupings, types, containers,
199 * lists, choices, augments, rpcs, notification, identities.
202 * schema context which contains data about all schema nodes
205 * set of modules for which schema nodes should be generated
207 * @return list of types (usually <code>GeneratedType</code> or
208 * <code>GeneratedTransferObject</code>) which:
210 * <li>are generated from <code>context</code> schema nodes and</li>
211 * <li>are also part of some of the module in <code>modules</code>
214 * @throws IllegalArgumentException
216 * <li>if arg <code>context</code> is null or</li>
217 * <li>if arg <code>modules</code> is null</li>
219 * @throws IllegalStateException
220 * if <code>context</code> contain no modules
223 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
224 checkArgument(context != null, "Schema Context reference cannot be NULL.");
225 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
226 checkArgument(modules != null, "Set of Modules cannot be NULL.");
228 schemaContext = context;
229 typeProvider = new TypeProviderImpl(context);
230 final Module[] modulesArray = new Module[context.getModules().size()];
231 context.getModules().toArray(modulesArray);
232 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
233 genTypeBuilders = new HashMap<>();
235 for (final Module contextModule : contextModules) {
236 moduleToGenTypes(contextModule, context);
238 for (final Module contextModule : contextModules) {
239 allAugmentsToGenTypes(contextModule);
242 final List<Type> filteredGenTypes = new ArrayList<>();
243 for (final Module m : modules) {
244 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
245 filteredGenTypes.addAll(ctx.getGeneratedTypes());
246 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
247 if (additionalTypes != null) {
248 filteredGenTypes.addAll(additionalTypes);
252 return filteredGenTypes;
255 private void moduleToGenTypes(final Module m, final SchemaContext context) {
256 genCtx.put(m, new ModuleContext());
257 allTypeDefinitionsToGenTypes(m);
258 groupingsToGenTypes(m, m.getGroupings());
259 rpcMethodsToGenType(m);
260 allIdentitiesToGenTypes(m, context);
261 notificationsToGenType(m);
263 if (!m.getChildNodes().isEmpty()) {
264 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
265 genCtx.get(m).addModuleNode(moduleType);
266 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
267 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
272 * Converts all extended type definitions of module to the list of
273 * <code>Type</code> objects.
276 * module from which is obtained set of type definitions
277 * @throws IllegalArgumentException
279 * <li>if module is null</li>
280 * <li>if name of module is null</li>
282 * @throws IllegalStateException
283 * if set of type definitions from module is null
285 private void allTypeDefinitionsToGenTypes(final Module module) {
286 checkArgument(module != null, "Module reference cannot be NULL.");
287 checkArgument(module.getName() != null, "Module name cannot be NULL.");
288 final DataNodeIterator it = new DataNodeIterator(module);
289 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
290 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
292 for (final TypeDefinition<?> typedef : typeDefinitions) {
293 if (typedef != null) {
294 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
297 final ModuleContext ctx = genCtx.get(module);
298 ctx.addTypedefType(typedef.getPath(), type);
299 ctx.addTypeToSchema(type,typedef);
305 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
306 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
307 if (node.isAugmenting() || node.isAddedByUses()) {
310 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
311 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
312 genType.addComment(node.getDescription());
313 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
314 genType.setModuleName(module.getName());
315 genType.setReference(node.getReference());
316 genType.setSchemaPath(node.getPath().getPathFromRoot());
317 if (node instanceof DataNodeContainer) {
318 genCtx.get(module).addChildNodeType(node, genType);
319 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
320 processUsesAugments((DataNodeContainer) node, module);
325 private void containerToGenType(final Module module, final String basePackageName,
326 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
327 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
328 if (genType != null) {
329 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
330 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
334 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
335 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
336 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
337 if (genType != null) {
338 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
340 final List<String> listKeys = listKeys(node);
341 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
342 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
343 if (genTOBuilder != null) {
344 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
345 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
346 genTOBuilder.addImplementsType(identifierMarker);
347 genType.addImplementsType(identifiableMarker);
350 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
351 if (!schemaNode.isAugmenting()) {
352 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
357 if (genTOBuilder != null) {
358 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
359 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
360 genTOBuilder.setSUID(prop);
363 typeBuildersToGenTypes(module, genType, genTOBuilder);
367 private void processUsesAugments(final DataNodeContainer node, final Module module) {
368 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
369 for (final UsesNode usesNode : node.getUses()) {
370 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
371 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
372 processUsesAugments(augment, module);
378 * Converts all <b>augmentation</b> of the module to the list
379 * <code>Type</code> objects.
382 * module from which is obtained list of all augmentation objects
383 * to iterate over them
384 * @throws IllegalArgumentException
386 * <li>if the module is null</li>
387 * <li>if the name of module is null</li>
389 * @throws IllegalStateException
390 * if set of augmentations from module is null
392 private void allAugmentsToGenTypes(final Module module) {
393 checkArgument(module != null, "Module reference cannot be NULL.");
394 checkArgument(module.getName() != null, "Module name cannot be NULL.");
395 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
397 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
398 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
399 for (final AugmentationSchema augment : augmentations) {
400 augmentationToGenTypes(basePackageName, augment, module);
405 * Returns list of <code>AugmentationSchema</code> objects. The objects are
406 * sorted according to the length of their target path from the shortest to
410 * module from which is obtained list of all augmentation objects
411 * @return list of sorted <code>AugmentationSchema</code> objects obtained
412 * from <code>module</code>
413 * @throws IllegalArgumentException
415 * @throws IllegalStateException
416 * if set of module augmentations is null
418 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
419 checkArgument(module != null, "Module reference cannot be NULL.");
420 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
422 final Set<AugmentationSchema> augmentations = module.getAugmentations();
423 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
424 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
426 return sortedAugmentations;
430 * Create GeneratedTypeBuilder object from module argument.
433 * Module object from which builder will be created
434 * @return <code>GeneratedTypeBuilder</code> which is internal
435 * representation of the module
436 * @throws IllegalArgumentException
439 private GeneratedTypeBuilder moduleToDataType(final Module module) {
440 checkArgument(module != null, "Module reference cannot be NULL.");
442 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
443 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
444 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
445 moduleDataTypeBuilder.addComment(module.getDescription());
446 moduleDataTypeBuilder.setDescription(createDescription(module));
447 moduleDataTypeBuilder.setReference(module.getReference());
448 return moduleDataTypeBuilder;
452 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
453 * to the list of <code>Type</code> objects. In addition are to containers
454 * and lists which belong to input or output also part of returning list.
457 * module from which is obtained set of all rpc objects to
459 * @throws IllegalArgumentException
461 * <li>if the module is null</li>
462 * <li>if the name of module is null</li>
464 * @throws IllegalStateException
465 * if set of rpcs from module is null
467 private void rpcMethodsToGenType(final Module module) {
468 checkArgument(module != null, "Module reference cannot be NULL.");
469 checkArgument(module.getName() != null, "Module name cannot be NULL.");
470 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
471 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
472 if (rpcDefinitions.isEmpty()) {
476 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
477 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
478 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
479 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
481 for (final RpcDefinition rpc : rpcDefinitions) {
483 final String rpcName = BindingMapping.getClassName(rpc.getQName());
484 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
485 final String rpcComment = rpc.getDescription();
486 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
487 final ContainerSchemaNode input = rpc.getInput();
488 final ContainerSchemaNode output = rpc.getOutput();
491 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
492 addImplementedInterfaceFromUses(input, inType);
493 inType.addImplementsType(DATA_OBJECT);
494 inType.addImplementsType(augmentable(inType));
495 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
496 genCtx.get(module).addChildNodeType(input, inType);
497 final GeneratedType inTypeInstance = inType.toInstance();
498 method.addParameter(inTypeInstance, "input");
501 Type outTypeInstance = VOID;
502 if (output != null) {
503 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
504 addImplementedInterfaceFromUses(output, outType);
505 outType.addImplementsType(DATA_OBJECT);
506 outType.addImplementsType(augmentable(outType));
507 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
508 genCtx.get(module).addChildNodeType(output, outType);
509 outTypeInstance = outType.toInstance();
512 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
513 method.setComment(rpcComment);
514 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
518 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
522 * Converts all <b>notifications</b> of the module to the list of
523 * <code>Type</code> objects. In addition are to this list added containers
524 * and lists which are part of this notification.
527 * module from which is obtained set of all notification objects
528 * to iterate over them
529 * @throws IllegalArgumentException
531 * <li>if the module equals null</li>
532 * <li>if the name of module equals null</li>
534 * @throws IllegalStateException
535 * if set of notifications from module is null
537 private void notificationsToGenType(final Module module) {
538 checkArgument(module != null, "Module reference cannot be NULL.");
539 checkArgument(module.getName() != null, "Module name cannot be NULL.");
540 final Set<NotificationDefinition> notifications = module.getNotifications();
541 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
542 if (notifications.isEmpty()) {
546 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
547 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
548 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
552 for (final NotificationDefinition notification : notifications) {
553 if (notification != null) {
554 processUsesAugments(notification, module);
556 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
557 notification, null, module);
558 notificationInterface.addImplementsType(NOTIFICATION);
559 genCtx.get(module).addChildNodeType(notification, notificationInterface);
561 // Notification object
562 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
563 notification.getChildNodes());
565 listenerInterface.addMethod("on" + notificationInterface.getName())
566 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
567 .setComment(notification.getDescription()).setReturnType(Types.VOID);
570 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
572 genCtx.get(module).addTopLevelNodeType(listenerInterface);
576 * Converts all <b>identities</b> of the module to the list of
577 * <code>Type</code> objects.
580 * module from which is obtained set of all identity objects to
583 * schema context only used as input parameter for method
584 * {@link identityToGenType}
587 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
588 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
589 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
591 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
592 for (final IdentitySchemaNode identity : schemaIdentities) {
593 identityToGenType(module, basePackageName, identity, context);
599 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
600 * created transport object builder. If identity contains base identity then
601 * reference to base identity is added to superior identity as its extend.
602 * If identity doesn't contain base identity then only reference to abstract
603 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
604 * BaseIdentity} is added
608 * @param basePackageName
609 * string contains the module package name
611 * IdentitySchemaNode which contains data about identity
613 * SchemaContext which is used to get package and name
614 * information about base of identity
617 private void identityToGenType(final Module module, final String basePackageName,
618 final IdentitySchemaNode identity, final SchemaContext context) {
619 if (identity == null) {
622 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
623 final String genTypeName = BindingMapping.getClassName(identity.getQName());
624 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
625 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
626 if (baseIdentity == null) {
627 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
628 BaseIdentity.class.getSimpleName());
629 newType.setExtendsType(gto.toInstance());
631 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
632 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
634 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
635 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
637 newType.setExtendsType(gto);
639 newType.setAbstract(true);
640 newType.addComment(identity.getDescription());
641 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
642 newType.setReference(identity.getReference());
643 newType.setModuleName(module.getName());
644 newType.setSchemaPath(identity.getPath().getPathFromRoot());
646 final QName qname = identity.getQName();
647 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
649 genCtx.get(module).addIdentityType(identity.getQName(), newType);
652 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
654 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
658 * Converts all <b>groupings</b> of the module to the list of
659 * <code>Type</code> objects. Firstly are groupings sorted according mutual
660 * dependencies. At least dependent (independent) groupings are in the list
661 * saved at first positions. For every grouping the record is added to map
662 * {@link BindingGeneratorImpl#allGroupings allGroupings}
667 * of groupings from which types will be generated
670 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
671 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
672 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
674 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
675 groupingToGenType(basePackageName, grouping, module);
680 * Converts individual grouping to GeneratedType. Firstly generated type
681 * builder is created and every child node of grouping is resolved to the
684 * @param basePackageName
685 * string contains the module package name
687 * GroupingDefinition which contains data about grouping
690 * @return GeneratedType which is generated from grouping (object of type
691 * <code>GroupingDefinition</code>)
693 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
694 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
695 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
696 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
697 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
698 groupingsToGenTypes(module, grouping.getGroupings());
699 processUsesAugments(grouping, module);
703 * Adds enumeration builder created from <code>enumTypeDef</code> to
704 * <code>typeBuilder</code>.
706 * Each <code>enumTypeDef</code> item is added to builder with its name and
710 * EnumTypeDefinition contains enum data
712 * string contains name which will be assigned to enumeration
715 * GeneratedTypeBuilder to which will be enum builder assigned
717 * Module in which type should be generated
718 * @return enumeration builder which contains data from
719 * <code>enumTypeDef</code>
721 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
722 final GeneratedTypeBuilder typeBuilder, final Module module) {
723 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
724 && (enumTypeDef.getQName().getLocalName() != null)) {
725 final String enumerationName = BindingMapping.getClassName(enumName);
726 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
727 enumBuilder.setDescription(enumTypeDef.getDescription());
728 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
729 ModuleContext ctx = genCtx.get(module);
730 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
737 * Generates type builder for <code>module</code>.
740 * Module which is source of package name for generated type
743 * string which is added to the module class name representation
745 * @return instance of GeneratedTypeBuilder which represents
746 * <code>module</code>.
747 * @throws IllegalArgumentException
748 * if <code>module</code> is null
750 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
751 checkArgument(module != null, "Module reference cannot be NULL.");
752 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
753 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
755 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
756 moduleBuilder.setDescription(createDescription(module));
757 moduleBuilder.setReference(module.getReference());
758 moduleBuilder.setModuleName(moduleName);
760 return moduleBuilder;
764 * Converts <code>augSchema</code> to list of <code>Type</code> which
765 * contains generated type for augmentation. In addition there are also
766 * generated types for all containers, list and choices which are child of
767 * <code>augSchema</code> node or a generated types for cases are added if
768 * augmented node is choice.
770 * @param augmentPackageName
771 * string with the name of the package to which the augmentation
774 * AugmentationSchema which is contains data about augmentation
775 * (target path, childs...)
778 * @param parentUsesNode
779 * @throws IllegalArgumentException
781 * <li>if <code>augmentPackageName</code> equals null</li>
782 * <li>if <code>augSchema</code> equals null</li>
784 * @throws IllegalStateException
785 * if augment target path is null
787 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
788 final Module module) {
789 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
790 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
791 checkState(augSchema.getTargetPath() != null,
792 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
794 processUsesAugments(augSchema, module);
795 final SchemaPath targetPath = augSchema.getTargetPath();
796 SchemaNode targetSchemaNode = null;
798 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
799 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
800 if (targetSchemaNode instanceof DerivableSchemaNode) {
801 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
803 if (targetSchemaNode == null) {
804 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
805 + " in module " + module.getName());
808 if (targetSchemaNode == null) {
809 throw new IllegalArgumentException("augment target not found: " + targetPath);
812 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
813 if (targetTypeBuilder == null) {
814 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
816 if (targetTypeBuilder == null) {
817 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
820 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
821 final String packageName = augmentPackageName;
822 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
823 targetTypeBuilder.getName());
824 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
827 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
828 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
832 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
833 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
834 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
835 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
836 checkState(augSchema.getTargetPath() != null,
837 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
839 processUsesAugments(augSchema, module);
840 final SchemaPath targetPath = augSchema.getTargetPath();
841 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
842 if (targetSchemaNode == null) {
843 throw new IllegalArgumentException("augment target not found: " + targetPath);
846 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
847 if (targetTypeBuilder == null) {
848 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
850 if (targetTypeBuilder == null) {
851 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
854 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
855 String packageName = augmentPackageName;
856 if (usesNodeParent instanceof SchemaNode) {
857 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
859 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
862 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
863 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
868 * Convenient method to find node added by uses statement.
872 * @param parentUsesNode
873 * parent of uses node
874 * @return node from its original location in grouping
876 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
877 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
879 if (!(targetGrouping instanceof GroupingDefinition)) {
880 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
883 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
884 SchemaNode result = grouping;
885 for (final QName node : targetPath.getPathFromRoot()) {
886 // finding by local name is valid, grouping cannot contain nodes
887 // with same name and different namespace
888 if (result instanceof DataNodeContainer) {
889 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
890 } else if (result instanceof ChoiceSchemaNode) {
891 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
894 if (result == null) {
898 if (result instanceof DerivableSchemaNode) {
899 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
900 Optional<? extends SchemaNode> originalNode = castedResult
902 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
903 result = originalNode.get();
907 if (result instanceof DataSchemaNode) {
908 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
909 if (resultDataSchemaNode.isAddedByUses()) {
910 // The original node is required, but we have only the copy of
911 // the original node.
912 // Maybe this indicates a bug in Yang parser.
913 throw new IllegalStateException(
914 "Failed to generate code for augment in "
917 return resultDataSchemaNode;
920 throw new IllegalStateException(
921 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
927 * Returns a generated type builder for an augmentation.
929 * The name of the type builder is equal to the name of augmented node with
930 * serial number as suffix.
934 * @param augmentPackageName
935 * string with contains the package name to which the augment
937 * @param basePackageName
938 * string with the package name to which the augmented node
940 * @param targetTypeRef
943 * augmentation schema which contains data about the child nodes
944 * and uses of augment
945 * @return generated type builder for augment
947 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
948 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
949 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
950 if (augmentBuilders == null) {
951 augmentBuilders = new HashMap<>();
952 genTypeBuilders.put(augmentPackageName, augmentBuilders);
954 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
957 if (augIdentifier != null) {
958 augTypeName = BindingMapping.getClassName(augIdentifier);
960 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
963 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
965 augTypeBuilder.addImplementsType(DATA_OBJECT);
966 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
967 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
969 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
970 augmentBuilders.put(augTypeName, augTypeBuilder);
972 if(!augSchema.getChildNodes().isEmpty()) {
973 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
974 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
977 genCtx.get(module).addAugmentType(augTypeBuilder);
978 return augTypeBuilder;
983 * @param unknownSchemaNodes
984 * @return nodeParameter of UnknownSchemaNode
986 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
987 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
988 final QName nodeType = unknownSchemaNode.getNodeType();
989 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
990 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
991 return unknownSchemaNode.getNodeParameter();
998 * Returns first unique name for the augment generated type builder. The
999 * generated type builder name for augment consists from name of augmented
1000 * node and serial number of its augmentation.
1003 * map of builders which were created in the package to which the
1004 * augmentation belongs
1005 * @param genTypeName
1006 * string with name of augmented node
1007 * @return string with unique name for augmentation builder
1009 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1011 if (builders != null) {
1012 while (builders.containsKey(genTypeName + index)) {
1016 return genTypeName + index;
1020 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1021 * node for which <code>typeBuilder</code> was created.
1023 * The subnodes aren't mapped to the methods if they are part of grouping or
1024 * augment (in this case are already part of them).
1028 * @param basePackageName
1029 * string contains the module package name
1031 * generated type builder which represents any node. The subnodes
1032 * of this node are added to the <code>typeBuilder</code> as
1033 * methods. The subnode can be of type leaf, leaf-list, list,
1034 * container, choice.
1037 * @param schemaNodes
1038 * set of data schema nodes which are the children of the node
1039 * for which <code>typeBuilder</code> was created
1040 * @return generated type builder which is the same builder as input
1041 * parameter. The getter methods (representing child nodes) could be
1044 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1045 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1046 if (schemaNodes != null && parent != null) {
1047 for (final DataSchemaNode schemaNode : schemaNodes) {
1048 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1049 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1057 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1058 * node for which <code>typeBuilder</code> was created.
1062 * @param basePackageName
1063 * string contains the module package name
1064 * @param typeBuilder
1065 * generated type builder which represents any node. The subnodes
1066 * of this node are added to the <code>typeBuilder</code> as
1067 * methods. The subnode can be of type leaf, leaf-list, list,
1068 * container, choice.
1071 * @param schemaNodes
1072 * set of data schema nodes which are the children of the node
1073 * for which <code>typeBuilder</code> was created
1074 * @return generated type builder which is the same object as the input
1075 * parameter <code>typeBuilder</code>. The getter method could be
1078 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1079 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1080 final Iterable<DataSchemaNode> schemaNodes) {
1081 if ((schemaNodes != null) && (typeBuilder != null)) {
1082 for (final DataSchemaNode schemaNode : schemaNodes) {
1083 if (!schemaNode.isAugmenting()) {
1084 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1092 * Adds to <code>typeBuilder</code> a method which is derived from
1093 * <code>schemaNode</code>.
1095 * @param basePackageName
1096 * string with the module package name
1098 * data schema node which is added to <code>typeBuilder</code> as
1100 * @param typeBuilder
1101 * generated type builder to which is <code>schemaNode</code>
1102 * added as a method.
1108 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1109 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1110 if (node != null && typeBuilder != null) {
1111 if (node instanceof LeafSchemaNode) {
1112 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1113 } else if (node instanceof LeafListSchemaNode) {
1114 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1115 } else if (node instanceof ContainerSchemaNode) {
1116 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1117 } else if (node instanceof ListSchemaNode) {
1118 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1119 } else if (node instanceof ChoiceSchemaNode) {
1120 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1122 // TODO: anyxml not yet supported
1123 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1124 typeBuilder.getFullyQualifiedName());
1130 * Converts <code>choiceNode</code> to the list of generated types for
1131 * choice and its cases.
1133 * The package names for choice and for its cases are created as
1134 * concatenation of the module package (<code>basePackageName</code>) and
1135 * names of all parents node.
1139 * @param basePackageName
1140 * string with the module package name
1144 * choice node which is mapped to generated type. Also child
1145 * nodes - cases are mapped to generated types.
1146 * @throws IllegalArgumentException
1148 * <li>if <code>basePackageName</code> is null</li>
1149 * <li>if <code>choiceNode</code> is null</li>
1152 private void choiceToGeneratedType(final Module module, final String basePackageName,
1153 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1154 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1155 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1157 if (!choiceNode.isAddedByUses()) {
1158 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1159 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1160 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1162 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1163 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1164 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1169 * Converts <code>caseNodes</code> set to list of corresponding generated
1172 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1173 * created generated type builder. The package names for the builder is
1174 * created as concatenation of the module package (
1175 * <code>basePackageName</code>) and names of all parents nodes of the
1176 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1177 * between every case builder and <i>choice</i> type
1181 * @param basePackageName
1182 * string with the module package name
1183 * @param refChoiceType
1184 * type which represents superior <i>case</i>
1186 * choice case node which is mapped to generated type
1187 * @return list of generated types for <code>caseNodes</code>.
1188 * @throws IllegalArgumentException
1190 * <li>if <code>basePackageName</code> equals null</li>
1191 * <li>if <code>refChoiceType</code> equals null</li>
1192 * <li>if <code>caseNodes</code> equals null</li>
1195 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1196 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1197 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1198 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1199 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1201 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1202 if (caseNodes == null) {
1206 for (final ChoiceCaseNode caseNode : caseNodes) {
1207 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1208 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1209 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1210 caseTypeBuilder.addImplementsType(refChoiceType);
1211 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1212 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1213 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1214 if (caseChildNodes != null) {
1215 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1217 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1218 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1220 if (parent instanceof AugmentationSchema) {
1221 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1222 final SchemaPath targetPath = augSchema.getTargetPath();
1223 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1224 if (targetSchemaNode instanceof DataSchemaNode
1225 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1226 if (targetSchemaNode instanceof DerivableSchemaNode) {
1227 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1229 if (targetSchemaNode == null) {
1230 throw new IllegalStateException(
1231 "Failed to find target node from grouping for augmentation " + augSchema
1232 + " in module " + module.getName());
1235 parent = targetSchemaNode;
1238 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1239 choiceNodeParentPath);
1240 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1241 if (childOfType == null) {
1242 childOfType = findGroupingByPath(parent.getPath());
1244 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1246 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1251 processUsesAugments(caseNode, module);
1256 * Generates list of generated types for all the cases of a choice which are
1257 * added to the choice through the augment.
1261 * @param basePackageName
1262 * string contains name of package to which augment belongs. If
1263 * an augmented choice is from an other package (pcg1) than an
1264 * augmenting choice (pcg2) then case's of the augmenting choice
1265 * will belong to pcg2.
1267 * Type which represents target choice
1269 * node which represents target choice
1270 * @param augmentedNodes
1271 * set of choice case nodes for which is checked if are/aren't
1272 * added to choice through augmentation
1273 * @return list of generated types which represents augmented cases of
1274 * choice <code>refChoiceType</code>
1275 * @throws IllegalArgumentException
1277 * <li>if <code>basePackageName</code> is null</li>
1278 * <li>if <code>targetType</code> is null</li>
1279 * <li>if <code>augmentedNodes</code> is null</li>
1282 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1283 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1284 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1285 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1286 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1288 for (final DataSchemaNode caseNode : augmentedNodes) {
1289 if (caseNode != null) {
1290 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1291 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1292 caseTypeBuilder.addImplementsType(targetType);
1294 SchemaNode parent = null;
1295 final SchemaPath nodeSp = targetNode.getPath();
1296 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1298 GeneratedTypeBuilder childOfType = null;
1299 if (parent instanceof Module) {
1300 childOfType = genCtx.get(parent).getModuleNode();
1301 } else if (parent instanceof ChoiceCaseNode) {
1302 childOfType = findCaseByPath(parent.getPath());
1303 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1304 childOfType = findChildNodeByPath(parent.getPath());
1305 } else if (parent instanceof GroupingDefinition) {
1306 childOfType = findGroupingByPath(parent.getPath());
1309 if (childOfType == null) {
1310 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1313 ChoiceCaseNode node = null;
1314 if (caseNode instanceof ChoiceCaseNode) {
1315 node = (ChoiceCaseNode) caseNode;
1317 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1319 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1320 if (childNodes != null) {
1321 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1323 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1324 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1330 * Converts <code>leaf</code> to the getter method which is added to
1331 * <code>typeBuilder</code>.
1333 * @param typeBuilder
1334 * generated type builder to which is added getter method as
1335 * <code>leaf</code> mapping
1337 * leaf schema node which is mapped as getter method which is
1338 * added to <code>typeBuilder</code>
1340 * Module in which type was defined
1341 * @return boolean value
1343 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1345 * <li>true - in other cases</li>
1348 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1349 Type returnType = null;
1350 if ((leaf != null) && (typeBuilder != null)) {
1351 final String leafName = leaf.getQName().getLocalName();
1352 String leafDesc = leaf.getDescription();
1353 if (leafDesc == null) {
1357 final Module parentModule = findParentModule(schemaContext, leaf);
1358 if (leafName != null && !leaf.isAddedByUses()) {
1359 final TypeDefinition<?> typeDef = leaf.getType();
1361 GeneratedTOBuilder genTOBuilder;
1362 if (typeDef instanceof EnumTypeDefinition) {
1363 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1364 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1365 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1366 typeBuilder,module);
1368 if (enumBuilder != null) {
1369 returnType = enumBuilder.toInstance(typeBuilder);
1371 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1372 } else if (typeDef instanceof UnionType) {
1373 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1374 if (genTOBuilder != null) {
1375 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1377 } else if (typeDef instanceof BitsTypeDefinition) {
1378 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1379 if (genTOBuilder != null) {
1380 returnType = genTOBuilder.toInstance();
1383 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1384 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1386 if (returnType != null) {
1387 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1388 processContextRefExtension(leaf, getter, parentModule);
1395 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1396 final Module module) {
1397 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1398 final QName nodeType = node.getNodeType();
1399 if ("context-reference".equals(nodeType.getLocalName())) {
1400 final String nodeParam = node.getNodeParameter();
1401 IdentitySchemaNode identity = null;
1402 String basePackageName = null;
1403 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1404 final Iterator<String> iterator = splittedElement.iterator();
1405 final int length = Iterables.size(splittedElement);
1407 identity = findIdentityByName(module.getIdentities(), iterator.next());
1408 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1409 } else if (length == 2) {
1410 final String prefix = iterator.next();
1411 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1412 if (dependentModule == null) {
1413 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1416 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1417 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1419 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1422 if (identity == null) {
1423 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1427 final Class<RoutingContext> clazz = RoutingContext.class;
1428 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1429 clazz.getSimpleName());
1430 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1431 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1432 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1437 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1438 for (final IdentitySchemaNode id : identities) {
1439 if (id.getQName().getLocalName().equals(name)) {
1446 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1447 for (final ModuleImport imp : imports) {
1448 if (imp.getPrefix().equals(prefix)) {
1449 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1455 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1456 final boolean isReadOnly, final Module module) {
1457 if ((leaf != null) && (toBuilder != null)) {
1458 String leafDesc = leaf.getDescription();
1459 if (leafDesc == null) {
1462 Type returnType = null;
1463 final TypeDefinition<?> typeDef = leaf.getType();
1464 if (typeDef instanceof UnionTypeDefinition) {
1465 // GeneratedType for this type definition should be already
1467 final QName qname = typeDef.getQName();
1468 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1469 qname.getRevision());
1470 final ModuleContext mc = genCtx.get(unionModule);
1471 returnType = mc.getTypedefs().get(typeDef.getPath());
1472 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1473 // Annonymous enumeration (already generated, since it is inherited via uses).
1474 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1475 QName qname = originalLeaf.getQName();
1476 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1477 qname.getRevision());
1478 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1480 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1482 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1488 * Converts <code>leaf</code> schema node to property of generated TO
1492 * generated TO builder to which is <code>leaf</code> added as
1495 * leaf schema node which is added to <code>toBuilder</code> as
1500 * boolean value which says if leaf property is|isn't read only
1501 * @return boolean value
1503 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1504 * name equals null or if leaf is added by <i>uses</i>.</li>
1505 * <li>true - other cases</li>
1508 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1509 final Type returnType, final boolean isReadOnly) {
1510 if (returnType == null) {
1513 final String leafName = leaf.getQName().getLocalName();
1514 final String leafDesc = leaf.getDescription();
1515 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1516 propBuilder.setReadOnly(isReadOnly);
1517 propBuilder.setReturnType(returnType);
1518 propBuilder.setComment(leafDesc);
1519 toBuilder.addEqualsIdentity(propBuilder);
1520 toBuilder.addHashIdentity(propBuilder);
1521 toBuilder.addToStringProperty(propBuilder);
1526 * Converts <code>node</code> leaf list schema node to getter method of
1527 * <code>typeBuilder</code>.
1529 * @param typeBuilder
1530 * generated type builder to which is <code>node</code> added as
1533 * leaf list schema node which is added to
1534 * <code>typeBuilder</code> as getter method
1536 * @return boolean value
1538 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1539 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1540 * <li>false - other cases</li>
1543 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1544 if ((node != null) && (typeBuilder != null)) {
1545 final QName nodeName = node.getQName();
1547 if (nodeName != null && !node.isAddedByUses()) {
1548 final TypeDefinition<?> typeDef = node.getType();
1549 final Module parentModule = findParentModule(schemaContext, node);
1551 Type returnType = null;
1552 if (typeDef instanceof EnumTypeDefinition) {
1553 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1554 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1555 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1556 typeBuilder,module);
1557 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1558 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1559 } else if (typeDef instanceof UnionType) {
1560 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1561 if (genTOBuilder != null) {
1562 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1564 } else if (typeDef instanceof BitsTypeDefinition) {
1565 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1566 returnType = genTOBuilder.toInstance();
1568 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1569 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1572 final ParameterizedType listType = Types.listTypeFor(returnType);
1573 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1580 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1581 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1582 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1583 genTOBuilder.getName());
1585 returnType.setDescription(typeDef.getDescription());
1586 returnType.setReference(typeDef.getReference());
1587 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1588 returnType.setModuleName(parentModule.getName());
1590 genTOBuilder.setTypedef(true);
1591 genTOBuilder.setIsUnion(true);
1592 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1596 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1599 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1600 method.setReturnType(returnType);
1601 method.addParameter(Types.STRING, "defaultValue");
1602 method.setAccessModifier(AccessModifier.PUBLIC);
1603 method.setStatic(true);
1605 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1606 if (types == null) {
1607 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1608 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1610 types.add(unionBuilder.toInstance());
1612 return returnType.toInstance();
1615 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1616 final String outerCls = Types.getOuterClassName(genTOBuilder);
1617 final StringBuilder name;
1618 if (outerCls != null) {
1619 name = new StringBuilder(outerCls);
1621 name = new StringBuilder();
1623 name.append(genTOBuilder.getName());
1624 name.append("Builder");
1625 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1626 unionBuilder.setIsUnionBuilder(true);
1627 return unionBuilder;
1630 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1631 final Module module) {
1632 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1636 * Instantiates generated type builder with <code>packageName</code> and
1637 * <code>schemaNode</code>.
1639 * The new builder always implements
1640 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1641 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1642 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1644 * If <code>schemaNode</code> is instance of
1645 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1646 * DataNodeContainer} it can also implement nodes which are specified in
1649 * @param packageName
1650 * string with the name of the package to which
1651 * <code>schemaNode</code> belongs.
1653 * schema node for which is created generated type builder
1655 * parent type (can be null)
1656 * @return generated type builder <code>schemaNode</code>
1658 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1659 final Type parent, final Module module) {
1660 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1661 if (parent == null) {
1662 it.addImplementsType(DATA_OBJECT);
1664 it.addImplementsType(BindingTypes.childOf(parent));
1666 if (!(schemaNode instanceof GroupingDefinition)) {
1667 it.addImplementsType(augmentable(it));
1670 if (schemaNode instanceof DataNodeContainer) {
1671 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1672 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1679 * Wraps the calling of the same overloaded method.
1681 * @param packageName
1682 * string with the package name to which returning generated type
1685 * schema node which provide data about the schema node name
1686 * @return generated type builder for <code>schemaNode</code>
1688 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1689 return addRawInterfaceDefinition(packageName, schemaNode, "");
1693 * Returns reference to generated type builder for specified
1694 * <code>schemaNode</code> with <code>packageName</code>.
1696 * Firstly the generated type builder is searched in
1697 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1698 * found it is created and added to <code>genTypeBuilders</code>.
1700 * @param packageName
1701 * string with the package name to which returning generated type
1704 * schema node which provide data about the schema node name
1706 * return type name prefix
1707 * @return generated type builder for <code>schemaNode</code>
1708 * @throws IllegalArgumentException
1710 * <li>if <code>schemaNode</code> is null</li>
1711 * <li>if <code>packageName</code> is null</li>
1712 * <li>if QName of schema node is null</li>
1713 * <li>if schemaNode name is null</li>
1717 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1718 final String prefix) {
1719 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1720 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1721 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1722 final String schemaNodeName = schemaNode.getQName().getLocalName();
1723 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1726 if (prefix == null) {
1727 genTypeName = BindingMapping.getClassName(schemaNodeName);
1729 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1732 // FIXME: Validation of name conflict
1733 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1734 final Module module = findParentModule(schemaContext, schemaNode);
1735 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1736 newType.addComment(schemaNode.getDescription());
1737 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1738 newType.setReference(schemaNode.getReference());
1739 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1740 newType.setModuleName(module.getName());
1742 if (!genTypeBuilders.containsKey(packageName)) {
1743 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1744 builders.put(genTypeName, newType);
1745 genTypeBuilders.put(packageName, builders);
1747 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1748 if (!builders.containsKey(genTypeName)) {
1749 builders.put(genTypeName, newType);
1756 * Creates the name of the getter method name from <code>localName</code>.
1759 * string with the name of the getter method
1762 * @return string with the name of the getter method for
1763 * <code>methodName</code> in JAVA method format
1765 public static String getterMethodName(final String localName, final Type returnType) {
1766 final StringBuilder method = new StringBuilder();
1767 if (BOOLEAN.equals(returnType)) {
1768 method.append("is");
1770 method.append("get");
1772 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1773 method.append(name);
1774 return method.toString();
1778 * Created a method signature builder as part of
1779 * <code>interfaceBuilder</code>.
1781 * The method signature builder is created for the getter method of
1782 * <code>schemaNodeName</code>. Also <code>comment</code> and
1783 * <code>returnType</code> information are added to the builder.
1785 * @param interfaceBuilder
1786 * generated type builder for which the getter method should be
1788 * @param schemaNodeName
1789 * string with schema node name. The name will be the part of the
1790 * getter method name.
1792 * string with comment for the getter method
1794 * type which represents the return type of the getter method
1795 * @return method signature builder which represents the getter method of
1796 * <code>interfaceBuilder</code>
1798 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1799 final String schemaNodeName, final String comment, final Type returnType) {
1800 final MethodSignatureBuilder getMethod = interfaceBuilder
1801 .addMethod(getterMethodName(schemaNodeName, returnType));
1802 getMethod.setComment(comment);
1803 getMethod.setReturnType(returnType);
1808 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1809 * or to <code>genTOBuilder</code> as property.
1811 * @param basePackageName
1812 * string contains the module package name
1814 * data schema node which should be added as getter method to
1815 * <code>typeBuilder</code> or as a property to
1816 * <code>genTOBuilder</code> if is part of the list key
1817 * @param typeBuilder
1818 * generated type builder for the list schema node
1819 * @param genTOBuilder
1820 * generated TO builder for the list keys
1822 * list of string which contains names of the list keys
1825 * @throws IllegalArgumentException
1827 * <li>if <code>schemaNode</code> equals null</li>
1828 * <li>if <code>typeBuilder</code> equals null</li>
1831 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1832 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1833 final Module module) {
1834 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1835 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1837 if (schemaNode instanceof LeafSchemaNode) {
1838 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1839 final String leafName = leaf.getQName().getLocalName();
1840 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1841 if (listKeys.contains(leafName)) {
1843 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1845 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1848 } else if (!schemaNode.isAddedByUses()) {
1849 if (schemaNode instanceof LeafListSchemaNode) {
1850 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1851 } else if (schemaNode instanceof ContainerSchemaNode) {
1852 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1853 } else if (schemaNode instanceof ChoiceSchemaNode) {
1854 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1855 } else if (schemaNode instanceof ListSchemaNode) {
1856 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1861 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1862 final GeneratedTOBuilder genTOBuilder) {
1863 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1865 if (genTOBuilder != null) {
1866 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1867 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1868 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1873 * Selects the names of the list keys from <code>list</code> and returns
1874 * them as the list of the strings
1877 * of string with names of the list keys
1878 * @return list of string which represents names of the list keys. If the
1879 * <code>list</code> contains no keys then the empty list is
1882 private static List<String> listKeys(final ListSchemaNode list) {
1883 final List<String> listKeys = new ArrayList<>();
1885 final List<QName> keyDefinition = list.getKeyDefinition();
1886 if (keyDefinition != null) {
1887 for (final QName keyDef : keyDefinition) {
1888 listKeys.add(keyDef.getLocalName());
1895 * Generates for the <code>list</code> which contains any list keys special
1896 * generated TO builder.
1898 * @param packageName
1899 * string with package name to which the list belongs
1901 * list schema node which is source of data about the list name
1902 * @return generated TO builder which represents the keys of the
1903 * <code>list</code> or null if <code>list</code> is null or list of
1904 * key definitions is null or empty.
1906 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1907 GeneratedTOBuilder genTOBuilder = null;
1908 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1909 final String listName = list.getQName().getLocalName() + "Key";
1910 final String genTOName = BindingMapping.getClassName(listName);
1911 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1913 return genTOBuilder;
1917 * Builds generated TO builders for <code>typeDef</code> of type
1918 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1919 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1920 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1921 * enclosing transfer object.
1923 * If more then one generated TO builder is created for enclosing then all
1924 * of the generated TO builders are added to <code>typeBuilder</code> as
1925 * enclosing transfer objects.
1928 * type definition which can be of type <code>UnionType</code> or
1929 * <code>BitsTypeDefinition</code>
1930 * @param typeBuilder
1931 * generated type builder to which is added generated TO created
1932 * from <code>typeDef</code>
1934 * string with name for generated TO builder
1936 * @return generated TO builder for <code>typeDef</code>
1938 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1939 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1940 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1941 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1942 final String packageName = typeBuilder.getFullyQualifiedName();
1943 if (typeDef instanceof UnionTypeDefinition) {
1944 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1945 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1946 classNameFromLeaf, leaf);
1947 genTOBuilders.addAll(types);
1949 GeneratedTOBuilder resultTOBuilder = null;
1950 if (types.isEmpty()) {
1951 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1953 resultTOBuilder = types.remove(0);
1954 for (final GeneratedTOBuilder genTOBuilder : types) {
1955 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1958 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1959 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1960 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1961 resultTOBuilder.addHashIdentity(genPropBuilder);
1962 resultTOBuilder.addToStringProperty(genPropBuilder);
1964 } else if (typeDef instanceof BitsTypeDefinition) {
1965 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1966 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1968 if (!genTOBuilders.isEmpty()) {
1969 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1970 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1972 return genTOBuilders.get(0);
1979 * Adds the implemented types to type builder.
1981 * The method passes through the list of <i>uses</i> in
1982 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1983 * generated type from {@link BindingGeneratorImpl#allGroupings
1984 * allGroupings} which is added as <i>implements type</i> to
1985 * <code>builder</code>
1987 * @param dataNodeContainer
1988 * element which contains the list of used YANG groupings
1990 * builder to which are added implemented types according to
1991 * <code>dataNodeContainer</code>
1992 * @return generated type builder with all implemented types
1994 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1995 final GeneratedTypeBuilder builder) {
1996 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1997 if (usesNode.getGroupingPath() != null) {
1998 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1999 if (genType == null) {
2000 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2001 + builder.getName());
2004 builder.addImplementsType(genType);
2006 builder.addComment(genType.getDescription());
2007 builder.setDescription(genType.getDescription());
2008 builder.setModuleName(genType.getModuleName());
2009 builder.setReference(genType.getReference());
2010 builder.setSchemaPath(genType.getSchemaPath());
2017 private static boolean isNullOrEmpty(final Collection<?> list) {
2018 return list == null || list.isEmpty();
2021 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2022 final StringBuilder sb = new StringBuilder();
2024 if (!isNullOrEmpty(schemaNodes)) {
2025 final SchemaNode node = schemaNodes.iterator().next();
2027 if (node instanceof RpcDefinition) {
2028 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2029 } else if (node instanceof NotificationDefinition) {
2030 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2033 sb.append(NEW_LINE);
2034 sb.append("<br>(Source path: <i>");
2035 sb.append(moduleSourcePath);
2036 sb.append("</i>):");
2037 sb.append(NEW_LINE);
2039 if (verboseClassComments) {
2041 sb.append(NEW_LINE);
2042 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2043 sb.append("</pre>");
2044 sb.append(NEW_LINE);
2047 return replaceAllIllegalChars(sb);
2050 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2051 final StringBuilder sb = new StringBuilder();
2052 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2054 if (!Strings.isNullOrEmpty(formattedDescription)) {
2055 sb.append(formattedDescription);
2056 sb.append(NEW_LINE);
2059 if (verboseClassComments) {
2060 final Module module = findParentModule(schemaContext, schemaNode);
2061 final StringBuilder linkToBuilderClass = new StringBuilder();
2062 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2063 final String className = namespace[namespace.length - 1];
2065 if (hasBuilderClass(schemaNode)) {
2066 linkToBuilderClass.append(className);
2067 linkToBuilderClass.append("Builder");
2071 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2072 sb.append(module.getName());
2074 sb.append(NEW_LINE);
2075 sb.append("<br>(Source path: <i>");
2076 sb.append(module.getModuleSourcePath());
2077 sb.append("</i>):");
2078 sb.append(NEW_LINE);
2080 sb.append(NEW_LINE);
2081 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2082 sb.append("</pre>");
2083 sb.append(NEW_LINE);
2084 sb.append("The schema path to identify an instance is");
2085 sb.append(NEW_LINE);
2087 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2089 sb.append(NEW_LINE);
2091 if (hasBuilderClass(schemaNode)) {
2092 sb.append(NEW_LINE);
2093 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2094 sb.append(NEW_LINE);
2096 sb.append(linkToBuilderClass);
2097 sb.append(NEW_LINE);
2098 if (schemaNode instanceof ListSchemaNode) {
2099 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2100 if (keyDef != null && !keyDef.isEmpty()) {
2102 sb.append(className);
2105 sb.append(NEW_LINE);
2110 return replaceAllIllegalChars(sb);
2113 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2114 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2115 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2121 private String createDescription(final Module module) {
2122 final StringBuilder sb = new StringBuilder();
2123 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2125 if (!Strings.isNullOrEmpty(formattedDescription)) {
2126 sb.append(formattedDescription);
2127 sb.append(NEW_LINE);
2130 if (verboseClassComments) {
2132 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2133 sb.append(module.getName());
2135 sb.append(NEW_LINE);
2136 sb.append("<br>Source path: <i>");
2137 sb.append(module.getModuleSourcePath());
2138 sb.append("</i>):");
2139 sb.append(NEW_LINE);
2141 sb.append(NEW_LINE);
2142 sb.append(YangTemplate.generateYangSnipet(module));
2143 sb.append("</pre>");
2146 return replaceAllIllegalChars(sb);
2149 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2150 for (final ModuleContext ctx : genCtx.values()) {
2151 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2152 if (result != null) {
2159 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2160 for (final ModuleContext ctx : genCtx.values()) {
2161 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2162 if (result != null) {
2169 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2170 for (final ModuleContext ctx : genCtx.values()) {
2171 final GeneratedTypeBuilder result = ctx.getCase(path);
2172 if (result != null) {
2179 public Map<Module, ModuleContext> getModuleContexts() {
2184 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2185 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2186 return ret.isEmpty() ? "" : ret;