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.packageNameForGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
21 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
25 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
29 import com.google.common.base.Optional;
31 import com.google.common.annotations.VisibleForTesting;
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.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
45 import java.util.regex.Pattern;
46 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
47 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
48 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
49 import org.opendaylight.yangtools.binding.generator.util.Types;
50 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
53 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
54 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
55 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
56 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
57 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
59 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
61 import org.opendaylight.yangtools.sal.binding.model.api.Type;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
69 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
70 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
71 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
72 import org.opendaylight.yangtools.yang.binding.BindingMapping;
73 import org.opendaylight.yangtools.yang.binding.DataContainer;
74 import org.opendaylight.yangtools.yang.binding.RpcService;
75 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
86 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
94 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
97 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.UsesNode;
100 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
104 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
105 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
106 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
107 import org.opendaylight.yangtools.yang.model.util.UnionType;
108 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
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';
118 private static final String QNAME_FQCN = QName.class.getName();
121 * Constant with the concrete name of identifier.
123 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
126 * Constant with the concrete name of namespace.
128 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
130 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
132 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
135 * When set to true, generated classes will include javadoc comments which
136 * are useful for users.
138 private final boolean verboseClassComments;
141 * Outer key represents the package name. Outer value represents map of all
142 * builders in the same package. Inner key represents the schema node name
143 * (in JAVA class/interface name format). Inner value represents instance of
144 * builder for schema node specified in key part.
146 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
149 * Provide methods for converting YANG types to JAVA types.
151 private TypeProvider typeProvider;
154 * Holds reference to schema context to resolve data of augmented element
155 * when creating augmentation builder
157 private SchemaContext schemaContext;
160 * Create a new binding generator with verboe comments.
162 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
165 public BindingGeneratorImpl() {
170 * Create a new binding generator.
172 * @param verboseClassComments generate verbose comments
174 public BindingGeneratorImpl(final boolean verboseClassComments) {
175 this.verboseClassComments = verboseClassComments;
179 * Resolves generated types from <code>context</code> schema nodes of all
182 * Generated types are created for modules, groupings, types, containers,
183 * lists, choices, augments, rpcs, notification, identities.
186 * schema context which contains data about all schema nodes
188 * @return list of types (usually <code>GeneratedType</code>
189 * <code>GeneratedTransferObject</code>which are generated from
190 * <code>context</code> data.
191 * @throws IllegalArgumentException
192 * if arg <code>context</code> is null
193 * @throws IllegalStateException
194 * if <code>context</code> contain no modules
197 public List<Type> generateTypes(final SchemaContext context) {
198 checkArgument(context != null, "Schema Context reference cannot be NULL.");
199 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
200 schemaContext = context;
201 typeProvider = new TypeProviderImpl(context);
202 final Set<Module> modules = context.getModules();
203 return generateTypes(context, modules);
207 * Resolves generated types from <code>context</code> schema nodes only for
208 * modules specified in <code>modules</code>
210 * Generated types are created for modules, groupings, types, containers,
211 * lists, choices, augments, rpcs, notification, identities.
214 * schema context which contains data about all schema nodes
217 * set of modules for which schema nodes should be generated
219 * @return list of types (usually <code>GeneratedType</code> or
220 * <code>GeneratedTransferObject</code>) which:
222 * <li>are generated from <code>context</code> schema nodes and</li>
223 * <li>are also part of some of the module in <code>modules</code>
226 * @throws IllegalArgumentException
228 * <li>if arg <code>context</code> is null or</li>
229 * <li>if arg <code>modules</code> is null</li>
231 * @throws IllegalStateException
232 * if <code>context</code> contain no modules
235 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
236 checkArgument(context != null, "Schema Context reference cannot be NULL.");
237 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
238 checkArgument(modules != null, "Set of Modules cannot be NULL.");
240 schemaContext = context;
241 typeProvider = new TypeProviderImpl(context);
242 final Module[] modulesArray = new Module[context.getModules().size()];
243 context.getModules().toArray(modulesArray);
244 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
245 genTypeBuilders = new HashMap<>();
247 for (final Module contextModule : contextModules) {
248 moduleToGenTypes(contextModule, context);
250 for (final Module contextModule : contextModules) {
251 allAugmentsToGenTypes(contextModule);
254 final List<Type> filteredGenTypes = new ArrayList<>();
255 for (final Module m : modules) {
256 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
257 filteredGenTypes.addAll(ctx.getGeneratedTypes());
258 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
259 if (additionalTypes != null) {
260 filteredGenTypes.addAll(additionalTypes);
264 return filteredGenTypes;
267 private void moduleToGenTypes(final Module m, final SchemaContext context) {
268 genCtx.put(m, new ModuleContext());
269 allTypeDefinitionsToGenTypes(m);
270 groupingsToGenTypes(m, m.getGroupings());
271 rpcMethodsToGenType(m);
272 allIdentitiesToGenTypes(m, context);
273 notificationsToGenType(m);
275 if (!m.getChildNodes().isEmpty()) {
276 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
277 genCtx.get(m).addModuleNode(moduleType);
278 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
279 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
284 * Converts all extended type definitions of module to the list of
285 * <code>Type</code> objects.
288 * module from which is obtained set of type definitions
289 * @throws IllegalArgumentException
291 * <li>if module is null</li>
292 * <li>if name of module is null</li>
294 * @throws IllegalStateException
295 * if set of type definitions from module is null
297 private void allTypeDefinitionsToGenTypes(final Module module) {
298 checkArgument(module != null, "Module reference cannot be NULL.");
299 checkArgument(module.getName() != null, "Module name cannot be NULL.");
300 final DataNodeIterator it = new DataNodeIterator(module);
301 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
302 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
304 for (final TypeDefinition<?> typedef : typeDefinitions) {
305 if (typedef != null) {
306 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
309 final ModuleContext ctx = genCtx.get(module);
310 ctx.addTypedefType(typedef.getPath(), type);
311 ctx.addTypeToSchema(type,typedef);
317 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
318 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
319 if (node.isAugmenting() || node.isAddedByUses()) {
322 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
323 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
324 genType.addComment(node.getDescription());
325 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
326 genType.setModuleName(module.getName());
327 genType.setReference(node.getReference());
328 genType.setSchemaPath(node.getPath().getPathFromRoot());
329 if (node instanceof DataNodeContainer) {
330 genCtx.get(module).addChildNodeType(node, genType);
331 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
332 processUsesAugments((DataNodeContainer) node, module);
337 private void containerToGenType(final Module module, final String basePackageName,
338 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
339 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
340 if (genType != null) {
341 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
342 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
346 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
347 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
348 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
349 if (genType != null) {
350 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
352 final List<String> listKeys = listKeys(node);
353 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
354 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
355 if (genTOBuilder != null) {
356 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
357 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
358 genTOBuilder.addImplementsType(identifierMarker);
359 genType.addImplementsType(identifiableMarker);
362 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
363 if (!schemaNode.isAugmenting()) {
364 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
369 if (genTOBuilder != null) {
370 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
371 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
372 genTOBuilder.setSUID(prop);
375 typeBuildersToGenTypes(module, genType, genTOBuilder);
379 private void processUsesAugments(final DataNodeContainer node, final Module module) {
380 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
381 for (final UsesNode usesNode : node.getUses()) {
382 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
383 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
384 processUsesAugments(augment, module);
390 * Converts all <b>augmentation</b> of the module to the list
391 * <code>Type</code> objects.
394 * module from which is obtained list of all augmentation objects
395 * to iterate over them
396 * @throws IllegalArgumentException
398 * <li>if the module is null</li>
399 * <li>if the name of module is null</li>
401 * @throws IllegalStateException
402 * if set of augmentations from module is null
404 private void allAugmentsToGenTypes(final Module module) {
405 checkArgument(module != null, "Module reference cannot be NULL.");
406 checkArgument(module.getName() != null, "Module name cannot be NULL.");
407 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
409 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
410 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
411 for (final AugmentationSchema augment : augmentations) {
412 augmentationToGenTypes(basePackageName, augment, module);
417 * Returns list of <code>AugmentationSchema</code> objects. The objects are
418 * sorted according to the length of their target path from the shortest to
422 * module from which is obtained list of all augmentation objects
423 * @return list of sorted <code>AugmentationSchema</code> objects obtained
424 * from <code>module</code>
425 * @throws IllegalArgumentException
427 * @throws IllegalStateException
428 * if set of module augmentations is null
430 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
431 checkArgument(module != null, "Module reference cannot be NULL.");
432 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
434 final Set<AugmentationSchema> augmentations = module.getAugmentations();
435 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
436 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
438 return sortedAugmentations;
442 * Create GeneratedTypeBuilder object from module argument.
445 * Module object from which builder will be created
446 * @return <code>GeneratedTypeBuilder</code> which is internal
447 * representation of the module
448 * @throws IllegalArgumentException
451 private GeneratedTypeBuilder moduleToDataType(final Module module) {
452 checkArgument(module != null, "Module reference cannot be NULL.");
454 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
455 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
456 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
457 moduleDataTypeBuilder.addComment(module.getDescription());
458 moduleDataTypeBuilder.setDescription(createDescription(module));
459 moduleDataTypeBuilder.setReference(module.getReference());
460 return moduleDataTypeBuilder;
464 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
465 * to the list of <code>Type</code> objects. In addition are to containers
466 * and lists which belong to input or output also part of returning list.
469 * module from which is obtained set of all rpc objects to
471 * @throws IllegalArgumentException
473 * <li>if the module is null</li>
474 * <li>if the name of module is null</li>
476 * @throws IllegalStateException
477 * if set of rpcs from module is null
479 private void rpcMethodsToGenType(final Module module) {
480 checkArgument(module != null, "Module reference cannot be NULL.");
481 checkArgument(module.getName() != null, "Module name cannot be NULL.");
482 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
483 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
484 if (rpcDefinitions.isEmpty()) {
488 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
489 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
490 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
491 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
493 for (final RpcDefinition rpc : rpcDefinitions) {
495 final String rpcName = BindingMapping.getClassName(rpc.getQName());
496 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
497 final String rpcComment = rpc.getDescription();
498 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
499 final ContainerSchemaNode input = rpc.getInput();
500 final ContainerSchemaNode output = rpc.getOutput();
503 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
504 addImplementedInterfaceFromUses(input, inType);
505 inType.addImplementsType(DATA_OBJECT);
506 inType.addImplementsType(augmentable(inType));
507 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
508 genCtx.get(module).addChildNodeType(input, inType);
509 final GeneratedType inTypeInstance = inType.toInstance();
510 method.addParameter(inTypeInstance, "input");
513 Type outTypeInstance = VOID;
514 if (output != null) {
515 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
516 addImplementedInterfaceFromUses(output, outType);
517 outType.addImplementsType(DATA_OBJECT);
518 outType.addImplementsType(augmentable(outType));
519 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
520 genCtx.get(module).addChildNodeType(output, outType);
521 outTypeInstance = outType.toInstance();
524 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
525 method.setComment(rpcComment);
526 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
530 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
534 * Converts all <b>notifications</b> of the module to the list of
535 * <code>Type</code> objects. In addition are to this list added containers
536 * and lists which are part of this notification.
539 * module from which is obtained set of all notification objects
540 * to iterate over them
541 * @throws IllegalArgumentException
543 * <li>if the module equals null</li>
544 * <li>if the name of module equals null</li>
546 * @throws IllegalStateException
547 * if set of notifications from module is null
549 private void notificationsToGenType(final Module module) {
550 checkArgument(module != null, "Module reference cannot be NULL.");
551 checkArgument(module.getName() != null, "Module name cannot be NULL.");
552 final Set<NotificationDefinition> notifications = module.getNotifications();
553 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
554 if (notifications.isEmpty()) {
558 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
559 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
560 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
564 for (final NotificationDefinition notification : notifications) {
565 if (notification != null) {
566 processUsesAugments(notification, module);
568 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
569 notification, null, module);
570 notificationInterface.addImplementsType(NOTIFICATION);
571 genCtx.get(module).addChildNodeType(notification, notificationInterface);
573 // Notification object
574 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
575 notification.getChildNodes());
577 listenerInterface.addMethod("on" + notificationInterface.getName())
578 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
579 .setComment(notification.getDescription()).setReturnType(Types.VOID);
582 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
584 genCtx.get(module).addTopLevelNodeType(listenerInterface);
588 * Converts all <b>identities</b> of the module to the list of
589 * <code>Type</code> objects.
592 * module from which is obtained set of all identity objects to
595 * schema context only used as input parameter for method
596 * {@link identityToGenType}
599 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
600 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
601 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
603 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
604 for (final IdentitySchemaNode identity : schemaIdentities) {
605 identityToGenType(module, basePackageName, identity, context);
611 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
612 * created transport object builder. If identity contains base identity then
613 * reference to base identity is added to superior identity as its extend.
614 * If identity doesn't contain base identity then only reference to abstract
615 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
616 * BaseIdentity} is added
620 * @param basePackageName
621 * string contains the module package name
623 * IdentitySchemaNode which contains data about identity
625 * SchemaContext which is used to get package and name
626 * information about base of identity
629 private void identityToGenType(final Module module, final String basePackageName,
630 final IdentitySchemaNode identity, final SchemaContext context) {
631 if (identity == null) {
634 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
635 final String genTypeName = BindingMapping.getClassName(identity.getQName());
636 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
637 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
638 if (baseIdentity == null) {
639 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
640 BaseIdentity.class.getSimpleName());
641 newType.setExtendsType(gto.toInstance());
643 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
644 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
646 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
647 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
649 newType.setExtendsType(gto);
651 newType.setAbstract(true);
652 newType.addComment(identity.getDescription());
653 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
654 newType.setReference(identity.getReference());
655 newType.setModuleName(module.getName());
656 newType.setSchemaPath(identity.getPath().getPathFromRoot());
658 final QName qname = identity.getQName();
659 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
661 genCtx.get(module).addIdentityType(identity.getQName(), newType);
664 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
666 final StringBuilder sb = new StringBuilder(QNAME_FQCN);
667 sb.append(".cachedReference(");
668 sb.append(QNAME_FQCN);
669 sb.append(".create(");
671 sb.append(name.getNamespace());
673 sb.append(name.getFormattedRevision());
675 sb.append(name.getLocalName());
678 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
682 * Converts all <b>groupings</b> of the module to the list of
683 * <code>Type</code> objects. Firstly are groupings sorted according mutual
684 * dependencies. At least dependent (independent) groupings are in the list
685 * saved at first positions. For every grouping the record is added to map
686 * {@link BindingGeneratorImpl#allGroupings allGroupings}
691 * of groupings from which types will be generated
694 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
695 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
696 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
698 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
699 groupingToGenType(basePackageName, grouping, module);
704 * Converts individual grouping to GeneratedType. Firstly generated type
705 * builder is created and every child node of grouping is resolved to the
708 * @param basePackageName
709 * string contains the module package name
711 * GroupingDefinition which contains data about grouping
714 * @return GeneratedType which is generated from grouping (object of type
715 * <code>GroupingDefinition</code>)
717 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
718 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
719 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
720 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
721 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
722 groupingsToGenTypes(module, grouping.getGroupings());
723 processUsesAugments(grouping, module);
727 * Adds enumeration builder created from <code>enumTypeDef</code> to
728 * <code>typeBuilder</code>.
730 * Each <code>enumTypeDef</code> item is added to builder with its name and
734 * EnumTypeDefinition contains enum data
736 * string contains name which will be assigned to enumeration
739 * GeneratedTypeBuilder to which will be enum builder assigned
741 * Module in which type should be generated
742 * @return enumeration builder which contains data from
743 * <code>enumTypeDef</code>
745 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
746 final GeneratedTypeBuilder typeBuilder, final Module module) {
747 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
748 && (enumTypeDef.getQName().getLocalName() != null)) {
749 final String enumerationName = BindingMapping.getClassName(enumName);
750 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
751 enumBuilder.setDescription(enumTypeDef.getDescription());
752 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
753 ModuleContext ctx = genCtx.get(module);
754 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
761 * Generates type builder for <code>module</code>.
764 * Module which is source of package name for generated type
767 * string which is added to the module class name representation
769 * @return instance of GeneratedTypeBuilder which represents
770 * <code>module</code>.
771 * @throws IllegalArgumentException
772 * if <code>module</code> is null
774 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
775 checkArgument(module != null, "Module reference cannot be NULL.");
776 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
777 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
779 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
780 moduleBuilder.setDescription(createDescription(module));
781 moduleBuilder.setReference(module.getReference());
782 moduleBuilder.setModuleName(moduleName);
784 return moduleBuilder;
788 * Converts <code>augSchema</code> to list of <code>Type</code> which
789 * contains generated type for augmentation. In addition there are also
790 * generated types for all containers, list and choices which are child of
791 * <code>augSchema</code> node or a generated types for cases are added if
792 * augmented node is choice.
794 * @param augmentPackageName
795 * string with the name of the package to which the augmentation
798 * AugmentationSchema which is contains data about augmentation
799 * (target path, childs...)
802 * @param parentUsesNode
803 * @throws IllegalArgumentException
805 * <li>if <code>augmentPackageName</code> equals null</li>
806 * <li>if <code>augSchema</code> equals null</li>
808 * @throws IllegalStateException
809 * if augment target path is null
811 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
812 final Module module) {
813 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
814 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
815 checkState(augSchema.getTargetPath() != null,
816 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
818 processUsesAugments(augSchema, module);
819 final SchemaPath targetPath = augSchema.getTargetPath();
820 SchemaNode targetSchemaNode = null;
822 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
823 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
824 if (targetSchemaNode instanceof DerivableSchemaNode) {
825 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
827 if (targetSchemaNode == null) {
828 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
829 + " in module " + module.getName());
832 if (targetSchemaNode == null) {
833 throw new IllegalArgumentException("augment target not found: " + targetPath);
836 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
837 if (targetTypeBuilder == null) {
838 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
840 if (targetTypeBuilder == null) {
841 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
844 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
845 final String packageName = augmentPackageName;
846 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
847 targetTypeBuilder.getName());
848 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
851 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
852 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
856 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
857 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
858 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
859 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
860 checkState(augSchema.getTargetPath() != null,
861 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
863 processUsesAugments(augSchema, module);
864 final SchemaPath targetPath = augSchema.getTargetPath();
865 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
866 if (targetSchemaNode == null) {
867 throw new IllegalArgumentException("augment target not found: " + targetPath);
870 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
871 if (targetTypeBuilder == null) {
872 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
874 if (targetTypeBuilder == null) {
875 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
878 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
879 String packageName = augmentPackageName;
880 if (usesNodeParent instanceof SchemaNode) {
881 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
884 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
887 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
888 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
893 * Convenient method to find node added by uses statement.
897 * @param parentUsesNode
898 * parent of uses node
899 * @return node from its original location in grouping
901 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
902 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
904 if (!(targetGrouping instanceof GroupingDefinition)) {
905 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
908 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
909 SchemaNode result = grouping;
910 for (final QName node : targetPath.getPathFromRoot()) {
911 // finding by local name is valid, grouping cannot contain nodes
912 // with same name and different namespace
913 if (result instanceof DataNodeContainer) {
914 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
915 } else if (result instanceof ChoiceSchemaNode) {
916 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
919 if (result == null) {
923 if (result instanceof DerivableSchemaNode) {
924 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
925 Optional<? extends SchemaNode> originalNode = castedResult
927 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
928 result = originalNode.get();
932 if (result instanceof DataSchemaNode) {
933 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
934 if (resultDataSchemaNode.isAddedByUses()) {
935 // The original node is required, but we have only the copy of
936 // the original node.
937 // Maybe this indicates a bug in Yang parser.
938 throw new IllegalStateException(
939 "Failed to generate code for augment in "
942 return resultDataSchemaNode;
945 throw new IllegalStateException(
946 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
952 * Returns a generated type builder for an augmentation.
954 * The name of the type builder is equal to the name of augmented node with
955 * serial number as suffix.
959 * @param augmentPackageName
960 * string with contains the package name to which the augment
962 * @param basePackageName
963 * string with the package name to which the augmented node
965 * @param targetTypeRef
968 * augmentation schema which contains data about the child nodes
969 * and uses of augment
970 * @return generated type builder for augment
972 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
973 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
974 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
975 if (augmentBuilders == null) {
976 augmentBuilders = new HashMap<>();
977 genTypeBuilders.put(augmentPackageName, augmentBuilders);
979 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
982 if (augIdentifier != null) {
983 augTypeName = BindingMapping.getClassName(augIdentifier);
985 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
988 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
990 augTypeBuilder.addImplementsType(DATA_OBJECT);
991 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
992 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
994 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
995 augmentBuilders.put(augTypeName, augTypeBuilder);
997 if(!augSchema.getChildNodes().isEmpty()) {
998 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
999 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1002 genCtx.get(module).addAugmentType(augTypeBuilder);
1003 return augTypeBuilder;
1008 * @param unknownSchemaNodes
1009 * @return nodeParameter of UnknownSchemaNode
1011 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1012 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1013 final QName nodeType = unknownSchemaNode.getNodeType();
1014 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1015 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1016 return unknownSchemaNode.getNodeParameter();
1023 * Returns first unique name for the augment generated type builder. The
1024 * generated type builder name for augment consists from name of augmented
1025 * node and serial number of its augmentation.
1028 * map of builders which were created in the package to which the
1029 * augmentation belongs
1030 * @param genTypeName
1031 * string with name of augmented node
1032 * @return string with unique name for augmentation builder
1034 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1036 if (builders != null) {
1037 while (builders.containsKey(genTypeName + index)) {
1041 return genTypeName + index;
1045 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1046 * node for which <code>typeBuilder</code> was created.
1048 * The subnodes aren't mapped to the methods if they are part of grouping or
1049 * augment (in this case are already part of them).
1053 * @param basePackageName
1054 * string contains the module package name
1056 * generated type builder which represents any node. The subnodes
1057 * of this node are added to the <code>typeBuilder</code> as
1058 * methods. The subnode can be of type leaf, leaf-list, list,
1059 * container, choice.
1062 * @param schemaNodes
1063 * set of data schema nodes which are the children of the node
1064 * for which <code>typeBuilder</code> was created
1065 * @return generated type builder which is the same builder as input
1066 * parameter. The getter methods (representing child nodes) could be
1069 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1070 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1071 if (schemaNodes != null && parent != null) {
1072 for (final DataSchemaNode schemaNode : schemaNodes) {
1073 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1074 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1082 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1083 * node for which <code>typeBuilder</code> was created.
1087 * @param basePackageName
1088 * string contains the module package name
1089 * @param typeBuilder
1090 * generated type builder which represents any node. The subnodes
1091 * of this node are added to the <code>typeBuilder</code> as
1092 * methods. The subnode can be of type leaf, leaf-list, list,
1093 * container, choice.
1096 * @param schemaNodes
1097 * set of data schema nodes which are the children of the node
1098 * for which <code>typeBuilder</code> was created
1099 * @return generated type builder which is the same object as the input
1100 * parameter <code>typeBuilder</code>. The getter method could be
1103 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1104 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1105 final Iterable<DataSchemaNode> schemaNodes) {
1106 if ((schemaNodes != null) && (typeBuilder != null)) {
1107 for (final DataSchemaNode schemaNode : schemaNodes) {
1108 if (!schemaNode.isAugmenting()) {
1109 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1117 * Adds to <code>typeBuilder</code> a method which is derived from
1118 * <code>schemaNode</code>.
1120 * @param basePackageName
1121 * string with the module package name
1123 * data schema node which is added to <code>typeBuilder</code> as
1125 * @param typeBuilder
1126 * generated type builder to which is <code>schemaNode</code>
1127 * added as a method.
1133 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1134 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1135 if (node != null && typeBuilder != null) {
1136 if (node instanceof LeafSchemaNode) {
1137 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1138 } else if (node instanceof LeafListSchemaNode) {
1139 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1140 } else if (node instanceof ContainerSchemaNode) {
1141 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1142 } else if (node instanceof ListSchemaNode) {
1143 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1144 } else if (node instanceof ChoiceSchemaNode) {
1145 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1147 // TODO: anyxml not yet supported
1148 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1149 typeBuilder.getFullyQualifiedName());
1155 * Converts <code>choiceNode</code> to the list of generated types for
1156 * choice and its cases.
1158 * The package names for choice and for its cases are created as
1159 * concatenation of the module package (<code>basePackageName</code>) and
1160 * names of all parents node.
1164 * @param basePackageName
1165 * string with the module package name
1169 * choice node which is mapped to generated type. Also child
1170 * nodes - cases are mapped to generated types.
1171 * @throws IllegalArgumentException
1173 * <li>if <code>basePackageName</code> is null</li>
1174 * <li>if <code>choiceNode</code> is null</li>
1177 private void choiceToGeneratedType(final Module module, final String basePackageName,
1178 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1179 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1180 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1182 if (!choiceNode.isAddedByUses()) {
1183 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1184 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1185 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1187 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1188 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1189 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1194 * Converts <code>caseNodes</code> set to list of corresponding generated
1197 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1198 * created generated type builder. The package names for the builder is
1199 * created as concatenation of the module package (
1200 * <code>basePackageName</code>) and names of all parents nodes of the
1201 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1202 * between every case builder and <i>choice</i> type
1206 * @param basePackageName
1207 * string with the module package name
1208 * @param refChoiceType
1209 * type which represents superior <i>case</i>
1211 * choice case node which is mapped to generated type
1212 * @return list of generated types for <code>caseNodes</code>.
1213 * @throws IllegalArgumentException
1215 * <li>if <code>basePackageName</code> equals null</li>
1216 * <li>if <code>refChoiceType</code> equals null</li>
1217 * <li>if <code>caseNodes</code> equals null</li>
1220 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1221 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1222 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1223 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1224 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1226 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1227 if (caseNodes == null) {
1231 for (final ChoiceCaseNode caseNode : caseNodes) {
1232 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1233 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1234 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1235 caseTypeBuilder.addImplementsType(refChoiceType);
1236 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1237 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1238 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1239 if (caseChildNodes != null) {
1240 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1242 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1243 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1245 if (parent instanceof AugmentationSchema) {
1246 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1247 final SchemaPath targetPath = augSchema.getTargetPath();
1248 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1249 if (targetSchemaNode instanceof DataSchemaNode
1250 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1251 if (targetSchemaNode instanceof DerivableSchemaNode) {
1252 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1254 if (targetSchemaNode == null) {
1255 throw new IllegalStateException(
1256 "Failed to find target node from grouping for augmentation " + augSchema
1257 + " in module " + module.getName());
1260 parent = targetSchemaNode;
1263 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1264 choiceNodeParentPath);
1265 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1266 if (childOfType == null) {
1267 childOfType = findGroupingByPath(parent.getPath());
1269 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1271 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1276 processUsesAugments(caseNode, module);
1281 * Generates list of generated types for all the cases of a choice which are
1282 * added to the choice through the augment.
1286 * @param basePackageName
1287 * string contains name of package to which augment belongs. If
1288 * an augmented choice is from an other package (pcg1) than an
1289 * augmenting choice (pcg2) then case's of the augmenting choice
1290 * will belong to pcg2.
1292 * Type which represents target choice
1294 * node which represents target choice
1295 * @param augmentedNodes
1296 * set of choice case nodes for which is checked if are/aren't
1297 * added to choice through augmentation
1298 * @return list of generated types which represents augmented cases of
1299 * choice <code>refChoiceType</code>
1300 * @throws IllegalArgumentException
1302 * <li>if <code>basePackageName</code> is null</li>
1303 * <li>if <code>targetType</code> is null</li>
1304 * <li>if <code>augmentedNodes</code> is null</li>
1307 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1308 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1309 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1310 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1311 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1313 for (final DataSchemaNode caseNode : augmentedNodes) {
1314 if (caseNode != null) {
1315 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1316 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1317 caseTypeBuilder.addImplementsType(targetType);
1319 SchemaNode parent = null;
1320 final SchemaPath nodeSp = targetNode.getPath();
1321 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1323 GeneratedTypeBuilder childOfType = null;
1324 if (parent instanceof Module) {
1325 childOfType = genCtx.get(parent).getModuleNode();
1326 } else if (parent instanceof ChoiceCaseNode) {
1327 childOfType = findCaseByPath(parent.getPath());
1328 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1329 childOfType = findChildNodeByPath(parent.getPath());
1330 } else if (parent instanceof GroupingDefinition) {
1331 childOfType = findGroupingByPath(parent.getPath());
1334 if (childOfType == null) {
1335 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1338 ChoiceCaseNode node = null;
1339 if (caseNode instanceof ChoiceCaseNode) {
1340 node = (ChoiceCaseNode) caseNode;
1342 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1344 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1345 if (childNodes != null) {
1346 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1348 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1349 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1355 * Converts <code>leaf</code> to the getter method which is added to
1356 * <code>typeBuilder</code>.
1358 * @param typeBuilder
1359 * generated type builder to which is added getter method as
1360 * <code>leaf</code> mapping
1362 * leaf schema node which is mapped as getter method which is
1363 * added to <code>typeBuilder</code>
1365 * Module in which type was defined
1366 * @return boolean value
1368 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1370 * <li>true - in other cases</li>
1373 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1374 Type returnType = null;
1375 if ((leaf != null) && (typeBuilder != null)) {
1376 final String leafName = leaf.getQName().getLocalName();
1377 String leafDesc = leaf.getDescription();
1378 if (leafDesc == null) {
1382 final Module parentModule = findParentModule(schemaContext, leaf);
1383 if (leafName != null && !leaf.isAddedByUses()) {
1384 final TypeDefinition<?> typeDef = leaf.getType();
1386 GeneratedTOBuilder genTOBuilder;
1387 if (typeDef instanceof EnumTypeDefinition) {
1388 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1389 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1390 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1391 typeBuilder,module);
1393 if (enumBuilder != null) {
1394 returnType = enumBuilder.toInstance(typeBuilder);
1396 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1397 } else if (typeDef instanceof UnionType) {
1398 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1399 if (genTOBuilder != null) {
1400 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1402 } else if (typeDef instanceof BitsTypeDefinition) {
1403 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1404 if (genTOBuilder != null) {
1405 returnType = genTOBuilder.toInstance();
1408 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1409 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1411 if (returnType != null) {
1412 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1413 processContextRefExtension(leaf, getter, parentModule);
1420 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1421 final Module module) {
1422 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1423 final QName nodeType = node.getNodeType();
1424 if ("context-reference".equals(nodeType.getLocalName())) {
1425 final String nodeParam = node.getNodeParameter();
1426 IdentitySchemaNode identity = null;
1427 String basePackageName = null;
1428 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1429 final Iterator<String> iterator = splittedElement.iterator();
1430 final int length = Iterables.size(splittedElement);
1432 identity = findIdentityByName(module.getIdentities(), iterator.next());
1433 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1434 } else if (length == 2) {
1435 final String prefix = iterator.next();
1436 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1437 if (dependentModule == null) {
1438 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1441 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1442 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1444 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1447 if (identity == null) {
1448 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1452 final Class<RoutingContext> clazz = RoutingContext.class;
1453 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1454 clazz.getSimpleName());
1455 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1456 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1457 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1462 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1463 for (final IdentitySchemaNode id : identities) {
1464 if (id.getQName().getLocalName().equals(name)) {
1471 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1472 for (final ModuleImport imp : imports) {
1473 if (imp.getPrefix().equals(prefix)) {
1474 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1480 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1481 final boolean isReadOnly, final Module module) {
1482 if ((leaf != null) && (toBuilder != null)) {
1483 final String leafName = leaf.getQName().getLocalName();
1484 String leafDesc = leaf.getDescription();
1485 if (leafDesc == null) {
1488 Type returnType = null;
1489 final TypeDefinition<?> typeDef = leaf.getType();
1490 if (typeDef instanceof UnionTypeDefinition) {
1491 // GeneratedType for this type definition should be already
1493 final QName qname = typeDef.getQName();
1494 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1495 qname.getRevision());
1496 final ModuleContext mc = genCtx.get(unionModule);
1497 returnType = mc.getTypedefs().get(typeDef.getPath());
1498 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1499 // Annonymous enumeration (already generated, since it is inherited via uses).
1500 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1501 QName qname = originalLeaf.getQName();
1502 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1503 qname.getRevision());
1504 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1506 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1508 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1514 * Converts <code>leaf</code> schema node to property of generated TO
1518 * generated TO builder to which is <code>leaf</code> added as
1521 * leaf schema node which is added to <code>toBuilder</code> as
1526 * boolean value which says if leaf property is|isn't read only
1527 * @return boolean value
1529 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1530 * name equals null or if leaf is added by <i>uses</i>.</li>
1531 * <li>true - other cases</li>
1534 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1535 final Type returnType, final boolean isReadOnly) {
1536 if (returnType == null) {
1539 final String leafName = leaf.getQName().getLocalName();
1540 final String leafDesc = leaf.getDescription();
1541 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1542 propBuilder.setReadOnly(isReadOnly);
1543 propBuilder.setReturnType(returnType);
1544 propBuilder.setComment(leafDesc);
1545 toBuilder.addEqualsIdentity(propBuilder);
1546 toBuilder.addHashIdentity(propBuilder);
1547 toBuilder.addToStringProperty(propBuilder);
1552 * Converts <code>node</code> leaf list schema node to getter method of
1553 * <code>typeBuilder</code>.
1555 * @param typeBuilder
1556 * generated type builder to which is <code>node</code> added as
1559 * leaf list schema node which is added to
1560 * <code>typeBuilder</code> as getter method
1562 * @return boolean value
1564 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1565 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1566 * <li>false - other cases</li>
1569 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1570 if ((node != null) && (typeBuilder != null)) {
1571 final QName nodeName = node.getQName();
1573 if (nodeName != null && !node.isAddedByUses()) {
1574 final TypeDefinition<?> typeDef = node.getType();
1575 final Module parentModule = findParentModule(schemaContext, node);
1577 Type returnType = null;
1578 if (typeDef instanceof EnumTypeDefinition) {
1579 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1580 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1581 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1582 typeBuilder,module);
1583 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1584 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1585 } else if (typeDef instanceof UnionType) {
1586 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1587 if (genTOBuilder != null) {
1588 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1590 } else if (typeDef instanceof BitsTypeDefinition) {
1591 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1592 returnType = genTOBuilder.toInstance();
1594 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1595 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1598 final ParameterizedType listType = Types.listTypeFor(returnType);
1599 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1606 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1607 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1608 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1609 genTOBuilder.getName());
1611 returnType.setDescription(typeDef.getDescription());
1612 returnType.setReference(typeDef.getReference());
1613 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1614 returnType.setModuleName(parentModule.getName());
1616 genTOBuilder.setTypedef(true);
1617 genTOBuilder.setIsUnion(true);
1618 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1622 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1625 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1626 method.setReturnType(returnType);
1627 method.addParameter(Types.STRING, "defaultValue");
1628 method.setAccessModifier(AccessModifier.PUBLIC);
1629 method.setStatic(true);
1631 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1632 if (types == null) {
1633 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1634 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1636 types.add(unionBuilder.toInstance());
1638 return returnType.toInstance();
1641 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1642 final String outerCls = Types.getOuterClassName(genTOBuilder);
1643 final StringBuilder name;
1644 if (outerCls != null) {
1645 name = new StringBuilder(outerCls);
1647 name = new StringBuilder();
1649 name.append(genTOBuilder.getName());
1650 name.append("Builder");
1651 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1652 unionBuilder.setIsUnionBuilder(true);
1653 return unionBuilder;
1656 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1657 final Module module) {
1658 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1662 * Instantiates generated type builder with <code>packageName</code> and
1663 * <code>schemaNode</code>.
1665 * The new builder always implements
1666 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1667 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1668 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1670 * If <code>schemaNode</code> is instance of
1671 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1672 * DataNodeContainer} it can also implement nodes which are specified in
1675 * @param packageName
1676 * string with the name of the package to which
1677 * <code>schemaNode</code> belongs.
1679 * schema node for which is created generated type builder
1681 * parent type (can be null)
1682 * @return generated type builder <code>schemaNode</code>
1684 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1685 final Type parent, final Module module) {
1686 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1687 if (parent == null) {
1688 it.addImplementsType(DATA_OBJECT);
1690 it.addImplementsType(BindingTypes.childOf(parent));
1692 if (!(schemaNode instanceof GroupingDefinition)) {
1693 it.addImplementsType(augmentable(it));
1696 if (schemaNode instanceof DataNodeContainer) {
1697 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1698 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1705 * Wraps the calling of the same overloaded method.
1707 * @param packageName
1708 * string with the package name to which returning generated type
1711 * schema node which provide data about the schema node name
1712 * @return generated type builder for <code>schemaNode</code>
1714 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1715 return addRawInterfaceDefinition(packageName, schemaNode, "");
1719 * Returns reference to generated type builder for specified
1720 * <code>schemaNode</code> with <code>packageName</code>.
1722 * Firstly the generated type builder is searched in
1723 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1724 * found it is created and added to <code>genTypeBuilders</code>.
1726 * @param packageName
1727 * string with the package name to which returning generated type
1730 * schema node which provide data about the schema node name
1732 * return type name prefix
1733 * @return generated type builder for <code>schemaNode</code>
1734 * @throws IllegalArgumentException
1736 * <li>if <code>schemaNode</code> is null</li>
1737 * <li>if <code>packageName</code> is null</li>
1738 * <li>if QName of schema node is null</li>
1739 * <li>if schemaNode name is null</li>
1743 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1744 final String prefix) {
1745 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1746 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1747 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1748 final String schemaNodeName = schemaNode.getQName().getLocalName();
1749 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1752 if (prefix == null) {
1753 genTypeName = BindingMapping.getClassName(schemaNodeName);
1755 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1758 // FIXME: Validation of name conflict
1759 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1760 final Module module = findParentModule(schemaContext, schemaNode);
1761 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1762 newType.addComment(schemaNode.getDescription());
1763 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1764 newType.setReference(schemaNode.getReference());
1765 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1766 newType.setModuleName(module.getName());
1768 if (!genTypeBuilders.containsKey(packageName)) {
1769 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1770 builders.put(genTypeName, newType);
1771 genTypeBuilders.put(packageName, builders);
1773 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1774 if (!builders.containsKey(genTypeName)) {
1775 builders.put(genTypeName, newType);
1782 * Creates the name of the getter method name from <code>localName</code>.
1785 * string with the name of the getter method
1788 * @return string with the name of the getter method for
1789 * <code>methodName</code> in JAVA method format
1791 public static String getterMethodName(final String localName, final Type returnType) {
1792 final StringBuilder method = new StringBuilder();
1793 if (BOOLEAN.equals(returnType)) {
1794 method.append("is");
1796 method.append("get");
1798 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1799 method.append(name);
1800 return method.toString();
1804 * Created a method signature builder as part of
1805 * <code>interfaceBuilder</code>.
1807 * The method signature builder is created for the getter method of
1808 * <code>schemaNodeName</code>. Also <code>comment</code> and
1809 * <code>returnType</code> information are added to the builder.
1811 * @param interfaceBuilder
1812 * generated type builder for which the getter method should be
1814 * @param schemaNodeName
1815 * string with schema node name. The name will be the part of the
1816 * getter method name.
1818 * string with comment for the getter method
1820 * type which represents the return type of the getter method
1821 * @return method signature builder which represents the getter method of
1822 * <code>interfaceBuilder</code>
1824 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1825 final String schemaNodeName, final String comment, final Type returnType) {
1826 final MethodSignatureBuilder getMethod = interfaceBuilder
1827 .addMethod(getterMethodName(schemaNodeName, returnType));
1828 getMethod.setComment(comment);
1829 getMethod.setReturnType(returnType);
1834 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1835 * or to <code>genTOBuilder</code> as property.
1837 * @param basePackageName
1838 * string contains the module package name
1840 * data schema node which should be added as getter method to
1841 * <code>typeBuilder</code> or as a property to
1842 * <code>genTOBuilder</code> if is part of the list key
1843 * @param typeBuilder
1844 * generated type builder for the list schema node
1845 * @param genTOBuilder
1846 * generated TO builder for the list keys
1848 * list of string which contains names of the list keys
1851 * @throws IllegalArgumentException
1853 * <li>if <code>schemaNode</code> equals null</li>
1854 * <li>if <code>typeBuilder</code> equals null</li>
1857 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1858 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1859 final Module module) {
1860 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1861 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1863 if (schemaNode instanceof LeafSchemaNode) {
1864 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1865 final String leafName = leaf.getQName().getLocalName();
1866 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1867 if (listKeys.contains(leafName)) {
1869 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1871 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1874 } else if (!schemaNode.isAddedByUses()) {
1875 if (schemaNode instanceof LeafListSchemaNode) {
1876 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1877 } else if (schemaNode instanceof ContainerSchemaNode) {
1878 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1879 } else if (schemaNode instanceof ChoiceSchemaNode) {
1880 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1881 } else if (schemaNode instanceof ListSchemaNode) {
1882 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1887 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1888 final GeneratedTOBuilder genTOBuilder) {
1889 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1891 if (genTOBuilder != null) {
1892 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1893 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1894 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1899 * Selects the names of the list keys from <code>list</code> and returns
1900 * them as the list of the strings
1903 * of string with names of the list keys
1904 * @return list of string which represents names of the list keys. If the
1905 * <code>list</code> contains no keys then the empty list is
1908 private static List<String> listKeys(final ListSchemaNode list) {
1909 final List<String> listKeys = new ArrayList<>();
1911 final List<QName> keyDefinition = list.getKeyDefinition();
1912 if (keyDefinition != null) {
1913 for (final QName keyDef : keyDefinition) {
1914 listKeys.add(keyDef.getLocalName());
1921 * Generates for the <code>list</code> which contains any list keys special
1922 * generated TO builder.
1924 * @param packageName
1925 * string with package name to which the list belongs
1927 * list schema node which is source of data about the list name
1928 * @return generated TO builder which represents the keys of the
1929 * <code>list</code> or null if <code>list</code> is null or list of
1930 * key definitions is null or empty.
1932 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1933 GeneratedTOBuilder genTOBuilder = null;
1934 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1935 final String listName = list.getQName().getLocalName() + "Key";
1936 final String genTOName = BindingMapping.getClassName(listName);
1937 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1939 return genTOBuilder;
1943 * Builds generated TO builders for <code>typeDef</code> of type
1944 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1945 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1946 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1947 * enclosing transfer object.
1949 * If more then one generated TO builder is created for enclosing then all
1950 * of the generated TO builders are added to <code>typeBuilder</code> as
1951 * enclosing transfer objects.
1954 * type definition which can be of type <code>UnionType</code> or
1955 * <code>BitsTypeDefinition</code>
1956 * @param typeBuilder
1957 * generated type builder to which is added generated TO created
1958 * from <code>typeDef</code>
1960 * string with name for generated TO builder
1962 * @return generated TO builder for <code>typeDef</code>
1964 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1965 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1966 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1967 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1968 final String packageName = typeBuilder.getFullyQualifiedName();
1969 if (typeDef instanceof UnionTypeDefinition) {
1970 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1971 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1972 classNameFromLeaf, leaf);
1973 genTOBuilders.addAll(types);
1975 GeneratedTOBuilder resultTOBuilder = null;
1976 if (types.isEmpty()) {
1977 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1979 resultTOBuilder = types.remove(0);
1980 for (final GeneratedTOBuilder genTOBuilder : types) {
1981 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1984 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1985 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1986 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1987 resultTOBuilder.addHashIdentity(genPropBuilder);
1988 resultTOBuilder.addToStringProperty(genPropBuilder);
1990 } else if (typeDef instanceof BitsTypeDefinition) {
1991 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1992 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1994 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1995 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1996 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1998 return genTOBuilders.get(0);
2005 * Adds the implemented types to type builder.
2007 * The method passes through the list of <i>uses</i> in
2008 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2009 * generated type from {@link BindingGeneratorImpl#allGroupings
2010 * allGroupings} which is added as <i>implements type</i> to
2011 * <code>builder</code>
2013 * @param dataNodeContainer
2014 * element which contains the list of used YANG groupings
2016 * builder to which are added implemented types according to
2017 * <code>dataNodeContainer</code>
2018 * @return generated type builder with all implemented types
2020 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2021 final GeneratedTypeBuilder builder) {
2022 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2023 if (usesNode.getGroupingPath() != null) {
2024 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2025 if (genType == null) {
2026 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2027 + builder.getName());
2030 builder.addImplementsType(genType);
2032 builder.addComment(genType.getDescription());
2033 builder.setDescription(genType.getDescription());
2034 builder.setModuleName(genType.getModuleName());
2035 builder.setReference(genType.getReference());
2036 builder.setSchemaPath(genType.getSchemaPath());
2043 private static boolean isNullOrEmpty(final Collection<?> list) {
2044 return list == null || list.isEmpty();
2047 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2048 final StringBuilder sb = new StringBuilder();
2050 if (!isNullOrEmpty(schemaNodes)) {
2051 final SchemaNode node = schemaNodes.iterator().next();
2053 if (node instanceof RpcDefinition) {
2054 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2055 } else if (node instanceof NotificationDefinition) {
2056 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2059 sb.append(NEW_LINE);
2060 sb.append("<br>(Source path: <i>");
2061 sb.append(moduleSourcePath);
2062 sb.append("</i>):");
2063 sb.append(NEW_LINE);
2065 if (verboseClassComments) {
2067 sb.append(NEW_LINE);
2068 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2069 sb.append("</pre>");
2070 sb.append(NEW_LINE);
2073 return replaceAllIllegalChars(sb);
2076 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2077 final StringBuilder sb = new StringBuilder();
2078 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2080 if (!Strings.isNullOrEmpty(formattedDescription)) {
2081 sb.append(formattedDescription);
2082 sb.append(NEW_LINE);
2085 if (verboseClassComments) {
2086 final Module module = findParentModule(schemaContext, schemaNode);
2087 final StringBuilder linkToBuilderClass = new StringBuilder();
2088 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2089 final String className = namespace[namespace.length - 1];
2091 if (hasBuilderClass(schemaNode)) {
2092 linkToBuilderClass.append(className);
2093 linkToBuilderClass.append("Builder");
2097 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2098 sb.append(module.getName());
2100 sb.append(NEW_LINE);
2101 sb.append("<br>(Source path: <i>");
2102 sb.append(module.getModuleSourcePath());
2103 sb.append("</i>):");
2104 sb.append(NEW_LINE);
2106 sb.append(NEW_LINE);
2107 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2108 sb.append("</pre>");
2109 sb.append(NEW_LINE);
2110 sb.append("The schema path to identify an instance is");
2111 sb.append(NEW_LINE);
2113 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2115 sb.append(NEW_LINE);
2117 if (hasBuilderClass(schemaNode)) {
2118 sb.append(NEW_LINE);
2119 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2120 sb.append(NEW_LINE);
2122 sb.append(linkToBuilderClass);
2123 sb.append(NEW_LINE);
2124 if (schemaNode instanceof ListSchemaNode) {
2125 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2126 if (keyDef != null && !keyDef.isEmpty()) {
2128 sb.append(className);
2131 sb.append(NEW_LINE);
2136 return replaceAllIllegalChars(sb);
2139 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2140 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2141 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2147 private String createDescription(final Module module) {
2148 final StringBuilder sb = new StringBuilder();
2149 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2151 if (!Strings.isNullOrEmpty(formattedDescription)) {
2152 sb.append(formattedDescription);
2153 sb.append(NEW_LINE);
2156 if (verboseClassComments) {
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);
2162 sb.append("<br>Source path: <i>");
2163 sb.append(module.getModuleSourcePath());
2164 sb.append("</i>):");
2165 sb.append(NEW_LINE);
2167 sb.append(NEW_LINE);
2168 sb.append(YangTemplate.generateYangSnipet(module));
2169 sb.append("</pre>");
2172 return replaceAllIllegalChars(sb);
2175 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2176 for (final ModuleContext ctx : genCtx.values()) {
2177 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2178 if (result != null) {
2185 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2186 for (final ModuleContext ctx : genCtx.values()) {
2187 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2188 if (result != null) {
2195 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2196 for (final ModuleContext ctx : genCtx.values()) {
2197 final GeneratedTypeBuilder result = ctx.getCase(path);
2198 if (result != null) {
2205 public Map<Module, ModuleContext> getModuleContexts() {
2210 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2211 return UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");