2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
26 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Optional;
33 import com.google.common.base.Preconditions;
34 import com.google.common.base.Splitter;
35 import com.google.common.base.Strings;
36 import com.google.common.collect.Iterables;
37 import com.google.common.collect.Sets;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.Comparator;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
47 import java.util.regex.Pattern;
48 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
49 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
50 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
51 import org.opendaylight.yangtools.binding.generator.util.Types;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
53 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
54 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
55 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
56 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
57 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
58 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
59 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
60 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
61 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
62 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
63 import org.opendaylight.yangtools.sal.binding.model.api.Type;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
69 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
70 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
71 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
72 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
73 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
74 import org.opendaylight.yangtools.yang.binding.BindingMapping;
75 import org.opendaylight.yangtools.yang.binding.DataContainer;
76 import org.opendaylight.yangtools.yang.binding.RpcService;
77 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
78 import org.opendaylight.yangtools.yang.common.QName;
79 import org.opendaylight.yangtools.yang.common.RpcResult;
80 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
82 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
88 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.Module;
93 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
94 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
95 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
99 import org.opendaylight.yangtools.yang.model.api.Status;
100 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.UsesNode;
103 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
104 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
105 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
107 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
108 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
109 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
110 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
111 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
112 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
113 import org.slf4j.Logger;
114 import org.slf4j.LoggerFactory;
116 public class BindingGeneratorImpl implements BindingGenerator {
117 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
118 private static final Splitter COLON_SPLITTER = Splitter.on(':');
119 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
120 private static final char NEW_LINE = '\n';
123 * Comparator based on augment target path.
125 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
126 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
127 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
129 while (thisIt.hasNext()) {
130 if (!otherIt.hasNext()) {
134 final int comp = thisIt.next().compareTo(otherIt.next());
140 return otherIt.hasNext() ? -1 : 0;
144 * Constant with the concrete name of identifier.
146 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
149 * Constant with the concrete name of namespace.
151 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
153 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
155 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
158 * When set to true, generated classes will include javadoc comments which
159 * are useful for users.
161 private final boolean verboseClassComments;
164 * Outer key represents the package name. Outer value represents map of all
165 * builders in the same package. Inner key represents the schema node name
166 * (in JAVA class/interface name format). Inner value represents instance of
167 * builder for schema node specified in key part.
169 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
172 * Provide methods for converting YANG types to JAVA types.
174 private TypeProvider typeProvider;
177 * Holds reference to schema context to resolve data of augmented element
178 * when creating augmentation builder
180 private SchemaContext schemaContext;
183 * Create a new binding generator.
185 * @param verboseClassComments generate verbose comments
187 public BindingGeneratorImpl(final boolean verboseClassComments) {
188 this.verboseClassComments = verboseClassComments;
192 * Resolves generated types from <code>context</code> schema nodes of all
195 * Generated types are created for modules, groupings, types, containers,
196 * lists, choices, augments, rpcs, notification, identities.
199 * schema context which contains data about all schema nodes
201 * @return list of types (usually <code>GeneratedType</code>
202 * <code>GeneratedTransferObject</code>which are generated from
203 * <code>context</code> data.
204 * @throws IllegalArgumentException
205 * if arg <code>context</code> is null
206 * @throws IllegalStateException
207 * if <code>context</code> contain no modules
210 public List<Type> generateTypes(final SchemaContext context) {
211 checkArgument(context != null, "Schema Context reference cannot be NULL.");
212 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
213 schemaContext = context;
214 typeProvider = new TypeProviderImpl(context);
215 final Set<Module> modules = context.getModules();
216 return generateTypes(context, modules);
220 * Resolves generated types from <code>context</code> schema nodes only for
221 * modules specified in <code>modules</code>
223 * Generated types are created for modules, groupings, types, containers,
224 * lists, choices, augments, rpcs, notification, identities.
227 * schema context which contains data about all schema nodes
230 * set of modules for which schema nodes should be generated
232 * @return list of types (usually <code>GeneratedType</code> or
233 * <code>GeneratedTransferObject</code>) which:
235 * <li>are generated from <code>context</code> schema nodes and</li>
236 * <li>are also part of some of the module in <code>modules</code>
239 * @throws IllegalArgumentException
241 * <li>if arg <code>context</code> is null or</li>
242 * <li>if arg <code>modules</code> is null</li>
244 * @throws IllegalStateException
245 * if <code>context</code> contain no modules
248 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
249 checkArgument(context != null, "Schema Context reference cannot be NULL.");
250 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
251 checkArgument(modules != null, "Set of Modules cannot be NULL.");
253 schemaContext = context;
254 typeProvider = new TypeProviderImpl(context);
255 final Module[] modulesArray = new Module[context.getModules().size()];
256 context.getModules().toArray(modulesArray);
257 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
258 genTypeBuilders = new HashMap<>();
260 for (final Module contextModule : contextModules) {
261 moduleToGenTypes(contextModule, context);
263 for (final Module contextModule : contextModules) {
264 allAugmentsToGenTypes(contextModule);
267 final List<Type> filteredGenTypes = new ArrayList<>();
268 for (final Module m : modules) {
269 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
270 filteredGenTypes.addAll(ctx.getGeneratedTypes());
271 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
272 if (additionalTypes != null) {
273 filteredGenTypes.addAll(additionalTypes);
277 return filteredGenTypes;
280 private void moduleToGenTypes(final Module m, final SchemaContext context) {
281 genCtx.put(m, new ModuleContext());
282 allTypeDefinitionsToGenTypes(m);
283 groupingsToGenTypes(m, m.getGroupings());
284 rpcMethodsToGenType(m);
285 allIdentitiesToGenTypes(m, context);
286 notificationsToGenType(m);
288 if (!m.getChildNodes().isEmpty()) {
289 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
290 genCtx.get(m).addModuleNode(moduleType);
291 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
292 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
297 * Converts all extended type definitions of module to the list of
298 * <code>Type</code> objects.
301 * module from which is obtained set of type definitions
302 * @throws IllegalArgumentException
304 * <li>if module is null</li>
305 * <li>if name of module is null</li>
307 * @throws IllegalStateException
308 * if set of type definitions from module is null
310 private void allTypeDefinitionsToGenTypes(final Module module) {
311 checkArgument(module != null, "Module reference cannot be NULL.");
312 checkArgument(module.getName() != null, "Module name cannot be NULL.");
313 final DataNodeIterator it = new DataNodeIterator(module);
314 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
315 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
317 for (final TypeDefinition<?> typedef : typeDefinitions) {
318 if (typedef != null) {
319 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
322 final ModuleContext ctx = genCtx.get(module);
323 ctx.addTypedefType(typedef.getPath(), type);
324 ctx.addTypeToSchema(type,typedef);
330 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
331 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
332 if (node.isAugmenting() || node.isAddedByUses()) {
335 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
336 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
337 genType.addComment(node.getDescription());
338 annotateDeprecatedIfNecessary(node.getStatus(), genType);
339 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
340 genType.setModuleName(module.getName());
341 genType.setReference(node.getReference());
342 genType.setSchemaPath(node.getPath().getPathFromRoot());
343 if (node instanceof DataNodeContainer) {
344 genCtx.get(module).addChildNodeType(node, genType);
345 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
346 processUsesAugments((DataNodeContainer) node, module);
351 private void containerToGenType(final Module module, final String basePackageName,
352 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
353 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
354 if (genType != null) {
355 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
356 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
360 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
361 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
362 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
363 if (genType != null) {
364 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
365 Types.listTypeFor(genType), node.getStatus());
367 final List<String> listKeys = listKeys(node);
368 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
369 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
370 if (genTOBuilder != null) {
371 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
372 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
373 genTOBuilder.addImplementsType(identifierMarker);
374 genType.addImplementsType(identifiableMarker);
377 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
378 if (!schemaNode.isAugmenting()) {
379 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
384 if (genTOBuilder != null) {
385 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
386 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
387 genTOBuilder.setSUID(prop);
390 typeBuildersToGenTypes(module, genType, genTOBuilder);
394 private void processUsesAugments(final DataNodeContainer node, final Module module) {
395 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
396 for (final UsesNode usesNode : node.getUses()) {
397 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
398 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
399 processUsesAugments(augment, module);
405 * Converts all <b>augmentation</b> of the module to the list
406 * <code>Type</code> objects.
409 * module from which is obtained list of all augmentation objects
410 * to iterate over them
411 * @throws IllegalArgumentException
413 * <li>if the module is null</li>
414 * <li>if the name of module is null</li>
416 * @throws IllegalStateException
417 * if set of augmentations from module is null
419 private void allAugmentsToGenTypes(final Module module) {
420 checkArgument(module != null, "Module reference cannot be NULL.");
421 checkArgument(module.getName() != null, "Module name cannot be NULL.");
422 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
424 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
425 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
426 for (final AugmentationSchema augment : augmentations) {
427 augmentationToGenTypes(basePackageName, augment, module);
432 * Returns list of <code>AugmentationSchema</code> objects. The objects are
433 * sorted according to the length of their target path from the shortest to
437 * module from which is obtained list of all augmentation objects
438 * @return list of sorted <code>AugmentationSchema</code> objects obtained
439 * from <code>module</code>
440 * @throws IllegalArgumentException
442 * @throws IllegalStateException
443 * if set of module augmentations is null
445 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
446 checkArgument(module != null, "Module reference cannot be NULL.");
447 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
449 final Set<AugmentationSchema> augmentations = module.getAugmentations();
450 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
451 Collections.sort(sortedAugmentations, AUGMENT_COMP);
453 return sortedAugmentations;
457 * Create GeneratedTypeBuilder object from module argument.
460 * Module object from which builder will be created
461 * @return <code>GeneratedTypeBuilder</code> which is internal
462 * representation of the module
463 * @throws IllegalArgumentException
466 private GeneratedTypeBuilder moduleToDataType(final Module module) {
467 checkArgument(module != null, "Module reference cannot be NULL.");
469 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
470 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
471 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
472 moduleDataTypeBuilder.addComment(module.getDescription());
473 moduleDataTypeBuilder.setDescription(createDescription(module));
474 moduleDataTypeBuilder.setReference(module.getReference());
475 return moduleDataTypeBuilder;
479 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
480 * to the list of <code>Type</code> objects. In addition are to containers
481 * and lists which belong to input or output also part of returning list.
484 * module from which is obtained set of all rpc objects to
486 * @throws IllegalArgumentException
488 * <li>if the module is null</li>
489 * <li>if the name of module is null</li>
491 * @throws IllegalStateException
492 * if set of rpcs from module is null
494 private void rpcMethodsToGenType(final Module module) {
495 checkArgument(module != null, "Module reference cannot be NULL.");
496 checkArgument(module.getName() != null, "Module name cannot be NULL.");
497 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
498 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
499 if (rpcDefinitions.isEmpty()) {
503 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
504 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
505 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
506 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
508 for (final RpcDefinition rpc : rpcDefinitions) {
510 final String rpcName = BindingMapping.getClassName(rpc.getQName());
511 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
512 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
513 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
514 final ContainerSchemaNode input = rpc.getInput();
515 final ContainerSchemaNode output = rpc.getOutput();
517 //in case of implicit RPC input (StatementSource.CONTEXT),
518 // stay compatible (no input argument generated)
519 if (input != null && isExplicitStatement(input)) {
520 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
521 addImplementedInterfaceFromUses(input, inType);
522 inType.addImplementsType(DATA_OBJECT);
523 inType.addImplementsType(augmentable(inType));
524 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
525 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
526 genCtx.get(module).addChildNodeType(input, inType);
527 final GeneratedType inTypeInstance = inType.toInstance();
528 method.addParameter(inTypeInstance, "input");
531 Type outTypeInstance = VOID;
532 //in case of implicit RPC output (StatementSource.CONTEXT),
533 //stay compatible (Future<RpcResult<Void>> return type generated)
534 if (output != null && isExplicitStatement(output)) {
535 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
536 addImplementedInterfaceFromUses(output, outType);
537 outType.addImplementsType(DATA_OBJECT);
538 outType.addImplementsType(augmentable(outType));
539 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
540 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
541 genCtx.get(module).addChildNodeType(output, outType);
542 outTypeInstance = outType.toInstance();
545 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
546 method.setComment(rpcComment);
547 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
551 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
554 private static boolean isExplicitStatement(ContainerSchemaNode node) {
555 return node instanceof EffectiveStatement
556 && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
560 * Converts all <b>notifications</b> of the module to the list of
561 * <code>Type</code> objects. In addition are to this list added containers
562 * and lists which are part of this notification.
565 * module from which is obtained set of all notification objects
566 * to iterate over them
567 * @throws IllegalArgumentException
569 * <li>if the module equals null</li>
570 * <li>if the name of module equals null</li>
572 * @throws IllegalStateException
573 * if set of notifications from module is null
575 private void notificationsToGenType(final Module module) {
576 checkArgument(module != null, "Module reference cannot be NULL.");
577 checkArgument(module.getName() != null, "Module name cannot be NULL.");
578 final Set<NotificationDefinition> notifications = module.getNotifications();
579 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
580 if (notifications.isEmpty()) {
584 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
585 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
586 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
590 for (final NotificationDefinition notification : notifications) {
591 if (notification != null) {
592 processUsesAugments(notification, module);
594 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
595 notification, null, module);
596 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
597 notificationInterface.addImplementsType(NOTIFICATION);
598 genCtx.get(module).addChildNodeType(notification, notificationInterface);
600 // Notification object
601 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
602 notification.getChildNodes());
604 listenerInterface.addMethod("on" + notificationInterface.getName())
605 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
606 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
609 listenerInterface.setDescription(createDescription(notifications, module.getName()));
611 genCtx.get(module).addTopLevelNodeType(listenerInterface);
615 * Converts all <b>identities</b> of the module to the list of
616 * <code>Type</code> objects.
619 * module from which is obtained set of all identity objects to
622 * schema context only used as input parameter for method
623 * {@link identityToGenType}
626 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
627 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
628 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
630 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
631 for (final IdentitySchemaNode identity : schemaIdentities) {
632 identityToGenType(module, basePackageName, identity, context);
638 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
639 * created transport object builder. If identity contains base identity then
640 * reference to base identity is added to superior identity as its extend.
641 * If identity doesn't contain base identity then only reference to abstract
642 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
643 * BaseIdentity} is added
647 * @param basePackageName
648 * string contains the module package name
650 * IdentitySchemaNode which contains data about identity
652 * SchemaContext which is used to get package and name
653 * information about base of identity
656 private void identityToGenType(final Module module, final String basePackageName,
657 final IdentitySchemaNode identity, final SchemaContext context) {
658 if (identity == null) {
661 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
662 final String genTypeName = BindingMapping.getClassName(identity.getQName());
663 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
664 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
665 if (baseIdentity == null) {
666 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
667 BaseIdentity.class.getSimpleName());
668 newType.setExtendsType(gto.toInstance());
670 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
671 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
673 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
674 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
676 newType.setExtendsType(gto);
678 newType.setAbstract(true);
679 newType.addComment(identity.getDescription());
680 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
681 newType.setReference(identity.getReference());
682 newType.setModuleName(module.getName());
683 newType.setSchemaPath(identity.getPath().getPathFromRoot());
685 final QName qname = identity.getQName();
686 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
688 genCtx.get(module).addIdentityType(identity.getQName(), newType);
691 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
693 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
697 * Converts all <b>groupings</b> of the module to the list of
698 * <code>Type</code> objects. Firstly are groupings sorted according mutual
699 * dependencies. At least dependent (independent) groupings are in the list
700 * saved at first positions. For every grouping the record is added to map
701 * {@link BindingGeneratorImpl#allGroupings allGroupings}
706 * of groupings from which types will be generated
709 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
710 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
711 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
713 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
714 groupingToGenType(basePackageName, grouping, module);
719 * Converts individual grouping to GeneratedType. Firstly generated type
720 * builder is created and every child node of grouping is resolved to the
723 * @param basePackageName
724 * string contains the module package name
726 * GroupingDefinition which contains data about grouping
729 * @return GeneratedType which is generated from grouping (object of type
730 * <code>GroupingDefinition</code>)
732 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
733 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
734 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
735 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
736 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
737 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
738 groupingsToGenTypes(module, grouping.getGroupings());
739 processUsesAugments(grouping, module);
743 * Adds enumeration builder created from <code>enumTypeDef</code> to
744 * <code>typeBuilder</code>.
746 * Each <code>enumTypeDef</code> item is added to builder with its name and
750 * EnumTypeDefinition contains enum data
752 * string contains name which will be assigned to enumeration
755 * GeneratedTypeBuilder to which will be enum builder assigned
757 * Module in which type should be generated
758 * @return enumeration builder which contains data from
759 * <code>enumTypeDef</code>
761 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
762 final GeneratedTypeBuilder typeBuilder, final Module module) {
763 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
764 && (enumTypeDef.getQName().getLocalName() != null)) {
765 final String enumerationName = BindingMapping.getClassName(enumName);
766 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
767 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
768 enumBuilder.setDescription(enumTypedefDescription);
769 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
770 ModuleContext ctx = genCtx.get(module);
771 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
778 * Generates type builder for <code>module</code>.
781 * Module which is source of package name for generated type
784 * string which is added to the module class name representation
786 * @return instance of GeneratedTypeBuilder which represents
787 * <code>module</code>.
788 * @throws IllegalArgumentException
789 * if <code>module</code> is null
791 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
792 checkArgument(module != null, "Module reference cannot be NULL.");
793 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
794 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
796 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
797 moduleBuilder.setDescription(createDescription(module));
798 moduleBuilder.setReference(module.getReference());
799 moduleBuilder.setModuleName(moduleName);
801 return moduleBuilder;
805 * Converts <code>augSchema</code> to list of <code>Type</code> which
806 * contains generated type for augmentation. In addition there are also
807 * generated types for all containers, list and choices which are child of
808 * <code>augSchema</code> node or a generated types for cases are added if
809 * augmented node is choice.
811 * @param augmentPackageName
812 * string with the name of the package to which the augmentation
815 * AugmentationSchema which is contains data about augmentation
816 * (target path, childs...)
819 * @param parentUsesNode
820 * @throws IllegalArgumentException
822 * <li>if <code>augmentPackageName</code> equals null</li>
823 * <li>if <code>augSchema</code> equals null</li>
825 * @throws IllegalStateException
826 * if augment target path is null
828 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
829 final Module module) {
830 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
831 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
832 checkState(augSchema.getTargetPath() != null,
833 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
835 processUsesAugments(augSchema, module);
836 final SchemaPath targetPath = augSchema.getTargetPath();
837 SchemaNode targetSchemaNode = null;
839 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
840 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
841 if (targetSchemaNode instanceof DerivableSchemaNode) {
842 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
844 if (targetSchemaNode == null) {
845 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
846 + " in module " + module.getName());
849 if (targetSchemaNode == null) {
850 throw new IllegalArgumentException("augment target not found: " + targetPath);
853 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
854 if (targetTypeBuilder == null) {
855 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
857 if (targetTypeBuilder == null) {
858 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
861 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
862 final String packageName = augmentPackageName;
863 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
864 targetTypeBuilder.getName());
865 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
868 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
869 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
873 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
874 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
875 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
876 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
877 checkState(augSchema.getTargetPath() != null,
878 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
880 processUsesAugments(augSchema, module);
881 final SchemaPath targetPath = augSchema.getTargetPath();
882 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
883 if (targetSchemaNode == null) {
884 throw new IllegalArgumentException("augment target not found: " + targetPath);
887 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
888 if (targetTypeBuilder == null) {
889 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
891 if (targetTypeBuilder == null) {
892 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
895 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
896 String packageName = augmentPackageName;
897 if (usesNodeParent instanceof SchemaNode) {
898 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
900 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
903 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
904 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
909 * Convenient method to find node added by uses statement.
913 * @param parentUsesNode
914 * parent of uses node
915 * @return node from its original location in grouping
917 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
918 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
920 if (!(targetGrouping instanceof GroupingDefinition)) {
921 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
924 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
925 SchemaNode result = grouping;
926 for (final QName node : targetPath.getPathFromRoot()) {
927 if (result instanceof DataNodeContainer) {
928 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
929 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
930 } else if (result instanceof ChoiceSchemaNode) {
931 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
934 if (result == null) {
938 if (result instanceof DerivableSchemaNode) {
939 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
940 Optional<? extends SchemaNode> originalNode = castedResult
942 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
943 result = originalNode.get();
947 if (result instanceof DataSchemaNode) {
948 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
949 if (resultDataSchemaNode.isAddedByUses()) {
950 // The original node is required, but we have only the copy of
951 // the original node.
952 // Maybe this indicates a bug in Yang parser.
953 throw new IllegalStateException(
954 "Failed to generate code for augment in "
957 return resultDataSchemaNode;
960 throw new IllegalStateException(
961 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
967 * Returns a generated type builder for an augmentation.
969 * The name of the type builder is equal to the name of augmented node with
970 * serial number as suffix.
974 * @param augmentPackageName
975 * string with contains the package name to which the augment
977 * @param basePackageName
978 * string with the package name to which the augmented node
980 * @param targetTypeRef
983 * augmentation schema which contains data about the child nodes
984 * and uses of augment
985 * @return generated type builder for augment
987 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
988 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
989 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
990 if (augmentBuilders == null) {
991 augmentBuilders = new HashMap<>();
992 genTypeBuilders.put(augmentPackageName, augmentBuilders);
994 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
997 if (augIdentifier != null) {
998 augTypeName = BindingMapping.getClassName(augIdentifier);
1000 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1003 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
1005 augTypeBuilder.addImplementsType(DATA_OBJECT);
1006 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
1007 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
1008 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1010 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1011 augmentBuilders.put(augTypeName, augTypeBuilder);
1013 if (!augSchema.getChildNodes().isEmpty()) {
1014 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1017 genCtx.get(module).addAugmentType(augTypeBuilder);
1018 return augTypeBuilder;
1023 * @param unknownSchemaNodes
1024 * @return nodeParameter of UnknownSchemaNode
1026 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1027 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1028 final QName nodeType = unknownSchemaNode.getNodeType();
1029 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1030 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1031 return unknownSchemaNode.getNodeParameter();
1038 * Returns first unique name for the augment generated type builder. The
1039 * generated type builder name for augment consists from name of augmented
1040 * node and serial number of its augmentation.
1043 * map of builders which were created in the package to which the
1044 * augmentation belongs
1045 * @param genTypeName
1046 * string with name of augmented node
1047 * @return string with unique name for augmentation builder
1049 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1051 if (builders != null) {
1052 while (builders.containsKey(genTypeName + index)) {
1056 return genTypeName + index;
1060 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1061 * node for which <code>typeBuilder</code> was created.
1063 * The subnodes aren't mapped to the methods if they are part of grouping or
1064 * augment (in this case are already part of them).
1068 * @param basePackageName
1069 * string contains the module package name
1071 * generated type builder which represents any node. The subnodes
1072 * of this node are added to the <code>typeBuilder</code> as
1073 * methods. The subnode can be of type leaf, leaf-list, list,
1074 * container, choice.
1077 * @param schemaNodes
1078 * set of data schema nodes which are the children of the node
1079 * for which <code>typeBuilder</code> was created
1080 * @return generated type builder which is the same builder as input
1081 * parameter. The getter methods (representing child nodes) could be
1084 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1085 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1086 if (schemaNodes != null && parent != null) {
1087 for (final DataSchemaNode schemaNode : schemaNodes) {
1088 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1089 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1097 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1098 * node for which <code>typeBuilder</code> was created.
1102 * @param basePackageName
1103 * string contains the module package name
1104 * @param typeBuilder
1105 * generated type builder which represents any node. The subnodes
1106 * of this node are added to the <code>typeBuilder</code> as
1107 * methods. The subnode can be of type leaf, leaf-list, list,
1108 * container, choice.
1111 * @param schemaNodes
1112 * set of data schema nodes which are the children of the node
1113 * for which <code>typeBuilder</code> was created
1114 * @return generated type builder which is the same object as the input
1115 * parameter <code>typeBuilder</code>. The getter method could be
1118 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1119 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1120 final Iterable<DataSchemaNode> schemaNodes) {
1121 if ((schemaNodes != null) && (typeBuilder != null)) {
1122 for (final DataSchemaNode schemaNode : schemaNodes) {
1123 if (!schemaNode.isAugmenting()) {
1124 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1132 * Adds to <code>typeBuilder</code> a method which is derived from
1133 * <code>schemaNode</code>.
1135 * @param basePackageName
1136 * string with the module package name
1138 * data schema node which is added to <code>typeBuilder</code> as
1140 * @param typeBuilder
1141 * generated type builder to which is <code>schemaNode</code>
1142 * added as a method.
1148 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1149 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1150 if (node != null && typeBuilder != null) {
1151 if (node instanceof LeafSchemaNode) {
1152 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1153 } else if (node instanceof LeafListSchemaNode) {
1154 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1155 } else if (node instanceof ContainerSchemaNode) {
1156 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1157 } else if (node instanceof ListSchemaNode) {
1158 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1159 } else if (node instanceof ChoiceSchemaNode) {
1160 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1162 // TODO: anyxml not yet supported
1163 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1164 typeBuilder.getFullyQualifiedName());
1170 * Converts <code>choiceNode</code> to the list of generated types for
1171 * choice and its cases.
1173 * The package names for choice and for its cases are created as
1174 * concatenation of the module package (<code>basePackageName</code>) and
1175 * names of all parents node.
1179 * @param basePackageName
1180 * string with the module package name
1184 * choice node which is mapped to generated type. Also child
1185 * nodes - cases are mapped to generated types.
1186 * @throws IllegalArgumentException
1188 * <li>if <code>basePackageName</code> is null</li>
1189 * <li>if <code>choiceNode</code> is null</li>
1192 private void choiceToGeneratedType(final Module module, final String basePackageName,
1193 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1194 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1195 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1197 if (!choiceNode.isAddedByUses()) {
1198 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1199 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1200 constructGetter(parent, choiceNode.getQName().getLocalName(),
1201 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1202 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1203 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1204 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1205 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1210 * Converts <code>caseNodes</code> set to list of corresponding generated
1213 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1214 * created generated type builder. The package names for the builder is
1215 * created as concatenation of the module package (
1216 * <code>basePackageName</code>) and names of all parents nodes of the
1217 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1218 * between every case builder and <i>choice</i> type
1222 * @param basePackageName
1223 * string with the module package name
1224 * @param refChoiceType
1225 * type which represents superior <i>case</i>
1227 * choice case node which is mapped to generated type
1228 * @return list of generated types for <code>caseNodes</code>.
1229 * @throws IllegalArgumentException
1231 * <li>if <code>basePackageName</code> equals null</li>
1232 * <li>if <code>refChoiceType</code> equals null</li>
1233 * <li>if <code>caseNodes</code> equals null</li>
1236 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1237 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1238 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1239 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1240 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1242 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1243 if (caseNodes == null) {
1247 for (final ChoiceCaseNode caseNode : caseNodes) {
1248 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1249 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1250 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1251 caseTypeBuilder.addImplementsType(refChoiceType);
1252 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1253 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1254 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1255 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1256 if (caseChildNodes != null) {
1257 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1259 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1260 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1262 if (parent instanceof AugmentationSchema) {
1263 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1264 final SchemaPath targetPath = augSchema.getTargetPath();
1265 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1266 if (targetSchemaNode instanceof DataSchemaNode
1267 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1268 if (targetSchemaNode instanceof DerivableSchemaNode) {
1269 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1271 if (targetSchemaNode == null) {
1272 throw new IllegalStateException(
1273 "Failed to find target node from grouping for augmentation " + augSchema
1274 + " in module " + module.getName());
1277 parent = targetSchemaNode;
1280 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1281 choiceNodeParentPath);
1282 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1283 if (childOfType == null) {
1284 childOfType = findGroupingByPath(parent.getPath());
1286 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1288 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1293 processUsesAugments(caseNode, module);
1298 * Generates list of generated types for all the cases of a choice which are
1299 * added to the choice through the augment.
1303 * @param basePackageName
1304 * string contains name of package to which augment belongs. If
1305 * an augmented choice is from an other package (pcg1) than an
1306 * augmenting choice (pcg2) then case's of the augmenting choice
1307 * will belong to pcg2.
1309 * Type which represents target choice
1311 * node which represents target choice
1312 * @param augmentedNodes
1313 * set of choice case nodes for which is checked if are/aren't
1314 * added to choice through augmentation
1315 * @return list of generated types which represents augmented cases of
1316 * choice <code>refChoiceType</code>
1317 * @throws IllegalArgumentException
1319 * <li>if <code>basePackageName</code> is null</li>
1320 * <li>if <code>targetType</code> is null</li>
1321 * <li>if <code>augmentedNodes</code> is null</li>
1324 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1325 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1326 final DataNodeContainer usesNodeParent) {
1327 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1328 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1329 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1331 for (final DataSchemaNode caseNode : augmentedNodes) {
1332 if (caseNode != null) {
1333 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1334 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1335 caseTypeBuilder.addImplementsType(targetType);
1337 SchemaNode parent = null;
1338 final SchemaPath nodeSp = targetNode.getPath();
1339 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1341 GeneratedTypeBuilder childOfType = null;
1342 if (parent instanceof Module) {
1343 childOfType = genCtx.get(parent).getModuleNode();
1344 } else if (parent instanceof ChoiceCaseNode) {
1345 childOfType = findCaseByPath(parent.getPath());
1346 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1347 childOfType = findChildNodeByPath(parent.getPath());
1348 } else if (parent instanceof GroupingDefinition) {
1349 childOfType = findGroupingByPath(parent.getPath());
1352 if (childOfType == null) {
1353 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1356 ChoiceCaseNode node = null;
1357 final String caseLocalName = caseNode.getQName().getLocalName();
1358 if (caseNode instanceof ChoiceCaseNode) {
1359 node = (ChoiceCaseNode) caseNode;
1360 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1361 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1362 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1363 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1364 ().getLocalName())) {
1365 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1370 node = targetNode.getCaseNodeByName(caseLocalName);
1372 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1373 if (childNodes != null) {
1374 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1376 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1377 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1382 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1383 // New parser with encapsulated type
1384 if (leaf.getPath().equals(type.getPath())) {
1388 // Embedded type definition with new parser. Also takes care of the old parser with bits
1389 if (leaf.getPath().equals(type.getPath().getParent())) {
1397 * Converts <code>leaf</code> to the getter method which is added to
1398 * <code>typeBuilder</code>.
1400 * @param typeBuilder
1401 * generated type builder to which is added getter method as
1402 * <code>leaf</code> mapping
1404 * leaf schema node which is mapped as getter method which is
1405 * added to <code>typeBuilder</code>
1407 * Module in which type was defined
1408 * @return boolean value
1410 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1412 * <li>true - in other cases</li>
1415 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1416 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1420 final String leafName = leaf.getQName().getLocalName();
1421 if (leafName == null) {
1425 final Module parentModule = findParentModule(schemaContext, leaf);
1426 Type returnType = null;
1428 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1429 if (isInnerType(leaf, typeDef)) {
1430 if (typeDef instanceof EnumTypeDefinition) {
1431 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1432 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1433 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1434 typeBuilder, module);
1435 if (enumBuilder != null) {
1436 returnType = enumBuilder.toInstance(typeBuilder);
1438 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1439 } else if (typeDef instanceof UnionTypeDefinition) {
1440 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1441 if (genTOBuilder != null) {
1442 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1444 } else if (typeDef instanceof BitsTypeDefinition) {
1445 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1446 if (genTOBuilder != null) {
1447 returnType = genTOBuilder.toInstance();
1450 // It is constrained version of already declared type (inner declared type exists,
1451 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1452 // In order to get proper class we need to look up closest derived type
1453 // and apply restrictions from leaf type
1454 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1455 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1459 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1460 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1463 if (returnType == null) {
1467 if (typeDef instanceof EnumTypeDefinition) {
1468 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1471 String leafDesc = leaf.getDescription();
1472 if (leafDesc == null) {
1476 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1477 processContextRefExtension(leaf, getter, parentModule);
1481 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1482 // Returns DerivedType in case of new parser.
1483 final TypeDefinition<?> baseType = typeDef.getBaseType();
1484 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1487 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1488 final Module module) {
1489 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1490 final QName nodeType = node.getNodeType();
1491 if ("context-reference".equals(nodeType.getLocalName())) {
1492 final String nodeParam = node.getNodeParameter();
1493 IdentitySchemaNode identity = null;
1494 String basePackageName = null;
1495 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1496 final Iterator<String> iterator = splittedElement.iterator();
1497 final int length = Iterables.size(splittedElement);
1499 identity = findIdentityByName(module.getIdentities(), iterator.next());
1500 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1501 } else if (length == 2) {
1502 final String prefix = iterator.next();
1503 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1504 if (dependentModule == null) {
1505 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1508 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1509 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1511 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1514 if (identity == null) {
1515 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1519 final Class<RoutingContext> clazz = RoutingContext.class;
1520 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1521 clazz.getSimpleName());
1522 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1523 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1524 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1529 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1530 for (final IdentitySchemaNode id : identities) {
1531 if (id.getQName().getLocalName().equals(name)) {
1538 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1539 for (final ModuleImport imp : imports) {
1540 if (imp.getPrefix().equals(prefix)) {
1541 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1547 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1548 final boolean isReadOnly, final Module module) {
1549 if ((leaf != null) && (toBuilder != null)) {
1550 String leafDesc = leaf.getDescription();
1551 if (leafDesc == null) {
1554 Type returnType = null;
1555 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1556 if (typeDef instanceof UnionTypeDefinition) {
1557 // GeneratedType for this type definition should be already
1559 final QName qname = typeDef.getQName();
1560 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1561 qname.getRevision());
1562 final ModuleContext mc = genCtx.get(unionModule);
1563 returnType = mc.getTypedefs().get(typeDef.getPath());
1564 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1565 // Annonymous enumeration (already generated, since it is inherited via uses).
1566 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1567 QName qname = originalLeaf.getQName();
1568 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1569 qname.getRevision());
1570 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1572 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1574 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1580 * Converts <code>leaf</code> schema node to property of generated TO
1584 * generated TO builder to which is <code>leaf</code> added as
1587 * leaf schema node which is added to <code>toBuilder</code> as
1592 * boolean value which says if leaf property is|isn't read only
1593 * @return boolean value
1595 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1596 * name equals null or if leaf is added by <i>uses</i>.</li>
1597 * <li>true - other cases</li>
1600 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1601 final Type returnType, final boolean isReadOnly) {
1602 if (returnType == null) {
1605 final String leafName = leaf.getQName().getLocalName();
1606 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1607 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1608 propBuilder.setReadOnly(isReadOnly);
1609 propBuilder.setReturnType(returnType);
1610 propBuilder.setComment(leafDesc);
1611 toBuilder.addEqualsIdentity(propBuilder);
1612 toBuilder.addHashIdentity(propBuilder);
1613 toBuilder.addToStringProperty(propBuilder);
1618 * Converts <code>node</code> leaf list schema node to getter method of
1619 * <code>typeBuilder</code>.
1621 * @param typeBuilder
1622 * generated type builder to which is <code>node</code> added as
1625 * leaf list schema node which is added to
1626 * <code>typeBuilder</code> as getter method
1628 * @return boolean value
1630 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1631 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1632 * <li>false - other cases</li>
1635 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1636 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1640 final QName nodeName = node.getQName();
1641 if (nodeName == null) {
1645 final TypeDefinition<?> typeDef = node.getType();
1646 final Module parentModule = findParentModule(schemaContext, node);
1648 Type returnType = null;
1649 if (typeDef.getBaseType() == null) {
1650 if (typeDef instanceof EnumTypeDefinition) {
1651 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1652 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1653 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1654 typeBuilder,module);
1655 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1656 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1657 } else if (typeDef instanceof UnionTypeDefinition) {
1658 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1659 if (genTOBuilder != null) {
1660 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1662 } else if (typeDef instanceof BitsTypeDefinition) {
1663 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1664 returnType = genTOBuilder.toInstance();
1666 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1667 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1670 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1671 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1674 final ParameterizedType listType = Types.listTypeFor(returnType);
1675 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1679 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1680 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1681 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1682 genTOBuilder.getName());
1683 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1685 returnType.setDescription(typedefDescription);
1686 returnType.setReference(typeDef.getReference());
1687 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1688 returnType.setModuleName(parentModule.getName());
1690 genTOBuilder.setTypedef(true);
1691 genTOBuilder.setIsUnion(true);
1692 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1696 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1699 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1700 method.setReturnType(returnType);
1701 method.addParameter(Types.STRING, "defaultValue");
1702 method.setAccessModifier(AccessModifier.PUBLIC);
1703 method.setStatic(true);
1705 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1706 if (types == null) {
1707 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1708 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1710 types.add(unionBuilder.toInstance());
1712 return returnType.toInstance();
1715 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1716 final String outerCls = Types.getOuterClassName(genTOBuilder);
1717 final StringBuilder name;
1718 if (outerCls != null) {
1719 name = new StringBuilder(outerCls);
1721 name = new StringBuilder();
1723 name.append(genTOBuilder.getName());
1724 name.append("Builder");
1725 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1726 unionBuilder.setIsUnionBuilder(true);
1727 return unionBuilder;
1730 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1731 final Module module) {
1732 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1736 * Instantiates generated type builder with <code>packageName</code> and
1737 * <code>schemaNode</code>.
1739 * The new builder always implements
1740 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1741 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1742 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1744 * If <code>schemaNode</code> is instance of
1745 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1746 * DataNodeContainer} it can also implement nodes which are specified in
1749 * @param packageName
1750 * string with the name of the package to which
1751 * <code>schemaNode</code> belongs.
1753 * schema node for which is created generated type builder
1755 * parent type (can be null)
1756 * @return generated type builder <code>schemaNode</code>
1758 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1759 final Type parent, final Module module) {
1760 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1761 if (parent == null) {
1762 it.addImplementsType(DATA_OBJECT);
1764 it.addImplementsType(BindingTypes.childOf(parent));
1766 if (!(schemaNode instanceof GroupingDefinition)) {
1767 it.addImplementsType(augmentable(it));
1770 if (schemaNode instanceof DataNodeContainer) {
1771 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1772 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1779 * Wraps the calling of the same overloaded method.
1781 * @param packageName
1782 * string with the package name to which returning generated type
1785 * schema node which provide data about the schema node name
1786 * @return generated type builder for <code>schemaNode</code>
1788 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1789 return addRawInterfaceDefinition(packageName, schemaNode, "");
1793 * Returns reference to generated type builder for specified
1794 * <code>schemaNode</code> with <code>packageName</code>.
1796 * Firstly the generated type builder is searched in
1797 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1798 * found it is created and added to <code>genTypeBuilders</code>.
1800 * @param packageName
1801 * string with the package name to which returning generated type
1804 * schema node which provide data about the schema node name
1806 * return type name prefix
1807 * @return generated type builder for <code>schemaNode</code>
1808 * @throws IllegalArgumentException
1810 * <li>if <code>schemaNode</code> is null</li>
1811 * <li>if <code>packageName</code> is null</li>
1812 * <li>if QName of schema node is null</li>
1813 * <li>if schemaNode name is null</li>
1817 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1818 final String prefix) {
1819 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1820 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1821 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1822 final String schemaNodeName = schemaNode.getQName().getLocalName();
1823 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1826 if (prefix == null) {
1827 genTypeName = BindingMapping.getClassName(schemaNodeName);
1829 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1832 // FIXME: Validation of name conflict
1833 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1834 final Module module = findParentModule(schemaContext, schemaNode);
1835 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1836 newType.addComment(schemaNode.getDescription());
1837 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1838 newType.setReference(schemaNode.getReference());
1839 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1840 newType.setModuleName(module.getName());
1842 if (!genTypeBuilders.containsKey(packageName)) {
1843 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1844 builders.put(genTypeName, newType);
1845 genTypeBuilders.put(packageName, builders);
1847 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1848 if (!builders.containsKey(genTypeName)) {
1849 builders.put(genTypeName, newType);
1856 * Creates the name of the getter method name from <code>localName</code>.
1859 * string with the name of the getter method
1862 * @return string with the name of the getter method for
1863 * <code>methodName</code> in JAVA method format
1865 public static String getterMethodName(final String localName, final Type returnType) {
1866 final StringBuilder method = new StringBuilder();
1867 if (BOOLEAN.equals(returnType)) {
1868 method.append("is");
1870 method.append("get");
1872 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1873 method.append(name);
1874 return method.toString();
1878 * Created a method signature builder as part of
1879 * <code>interfaceBuilder</code>.
1881 * The method signature builder is created for the getter method of
1882 * <code>schemaNodeName</code>. Also <code>comment</code> and
1883 * <code>returnType</code> information are added to the builder.
1885 * @param interfaceBuilder
1886 * generated type builder for which the getter method should be
1888 * @param schemaNodeName
1889 * string with schema node name. The name will be the part of the
1890 * getter method name.
1892 * string with comment for the getter method
1894 * type which represents the return type of the getter method
1896 * status from yang file, for deprecated annotation
1897 * @return method signature builder which represents the getter method of
1898 * <code>interfaceBuilder</code>
1900 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1901 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1902 final MethodSignatureBuilder getMethod = interfaceBuilder
1903 .addMethod(getterMethodName(schemaNodeName, returnType));
1904 if (status == Status.DEPRECATED) {
1905 getMethod.addAnnotation("", "Deprecated");
1907 getMethod.setComment(encodeAngleBrackets(comment));
1908 getMethod.setReturnType(returnType);
1913 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1914 * or to <code>genTOBuilder</code> as property.
1916 * @param basePackageName
1917 * string contains the module package name
1919 * data schema node which should be added as getter method to
1920 * <code>typeBuilder</code> or as a property to
1921 * <code>genTOBuilder</code> if is part of the list key
1922 * @param typeBuilder
1923 * generated type builder for the list schema node
1924 * @param genTOBuilder
1925 * generated TO builder for the list keys
1927 * list of string which contains names of the list keys
1930 * @throws IllegalArgumentException
1932 * <li>if <code>schemaNode</code> equals null</li>
1933 * <li>if <code>typeBuilder</code> equals null</li>
1936 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1937 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1938 final Module module) {
1939 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1940 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1942 if (schemaNode instanceof LeafSchemaNode) {
1943 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1944 final String leafName = leaf.getQName().getLocalName();
1945 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1946 if (listKeys.contains(leafName)) {
1948 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1950 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1953 } else if (!schemaNode.isAddedByUses()) {
1954 if (schemaNode instanceof LeafListSchemaNode) {
1955 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1956 } else if (schemaNode instanceof ContainerSchemaNode) {
1957 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1958 } else if (schemaNode instanceof ChoiceSchemaNode) {
1959 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1960 } else if (schemaNode instanceof ListSchemaNode) {
1961 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1966 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1967 final GeneratedTOBuilder genTOBuilder) {
1968 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1970 if (genTOBuilder != null) {
1971 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1972 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1973 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1978 * Selects the names of the list keys from <code>list</code> and returns
1979 * them as the list of the strings
1982 * of string with names of the list keys
1983 * @return list of string which represents names of the list keys. If the
1984 * <code>list</code> contains no keys then the empty list is
1987 private static List<String> listKeys(final ListSchemaNode list) {
1988 final List<String> listKeys = new ArrayList<>();
1990 final List<QName> keyDefinition = list.getKeyDefinition();
1991 if (keyDefinition != null) {
1992 for (final QName keyDef : keyDefinition) {
1993 listKeys.add(keyDef.getLocalName());
2000 * Generates for the <code>list</code> which contains any list keys special
2001 * generated TO builder.
2003 * @param packageName
2004 * string with package name to which the list belongs
2006 * list schema node which is source of data about the list name
2007 * @return generated TO builder which represents the keys of the
2008 * <code>list</code> or null if <code>list</code> is null or list of
2009 * key definitions is null or empty.
2011 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2012 GeneratedTOBuilder genTOBuilder = null;
2013 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2014 final String listName = list.getQName().getLocalName() + "Key";
2015 final String genTOName = BindingMapping.getClassName(listName);
2016 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2018 return genTOBuilder;
2022 * Builds generated TO builders for <code>typeDef</code> of type
2023 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2024 * also added to <code>typeBuilder</code> as enclosing transfer object.
2026 * If more then one generated TO builder is created for enclosing then all
2027 * of the generated TO builders are added to <code>typeBuilder</code> as
2028 * enclosing transfer objects.
2031 * type definition which can be of type <code>UnionType</code> or
2032 * <code>BitsTypeDefinition</code>
2033 * @param typeBuilder
2034 * generated type builder to which is added generated TO created
2035 * from <code>typeDef</code>
2037 * string with name for generated TO builder
2039 * @return generated TO builder for <code>typeDef</code>
2041 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2042 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2043 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2044 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2045 final String packageName = typeBuilder.getFullyQualifiedName();
2046 if (typeDef instanceof UnionTypeDefinition) {
2047 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2048 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2049 classNameFromLeaf, leaf);
2050 genTOBuilders.addAll(types);
2052 GeneratedTOBuilder resultTOBuilder = null;
2053 if (types.isEmpty()) {
2054 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2056 resultTOBuilder = types.remove(0);
2057 for (final GeneratedTOBuilder genTOBuilder : types) {
2058 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2061 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2062 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2063 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2064 resultTOBuilder.addHashIdentity(genPropBuilder);
2065 resultTOBuilder.addToStringProperty(genPropBuilder);
2067 } else if (typeDef instanceof BitsTypeDefinition) {
2068 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2069 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2071 if (!genTOBuilders.isEmpty()) {
2072 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2073 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2075 return genTOBuilders.get(0);
2082 * Adds the implemented types to type builder.
2084 * The method passes through the list of <i>uses</i> in
2085 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2086 * generated type from {@link BindingGeneratorImpl#allGroupings
2087 * allGroupings} which is added as <i>implements type</i> to
2088 * <code>builder</code>
2090 * @param dataNodeContainer
2091 * element which contains the list of used YANG groupings
2093 * builder to which are added implemented types according to
2094 * <code>dataNodeContainer</code>
2095 * @return generated type builder with all implemented types
2097 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2098 final GeneratedTypeBuilder builder) {
2099 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2100 if (usesNode.getGroupingPath() != null) {
2101 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2102 if (genType == null) {
2103 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2104 + builder.getName());
2107 builder.addImplementsType(genType);
2109 builder.addComment(genType.getDescription());
2110 builder.setDescription(genType.getDescription());
2111 builder.setModuleName(genType.getModuleName());
2112 builder.setReference(genType.getReference());
2113 builder.setSchemaPath(genType.getSchemaPath());
2120 private static boolean isNullOrEmpty(final Collection<?> list) {
2121 return list == null || list.isEmpty();
2124 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2125 final StringBuilder sb = new StringBuilder();
2127 if (!isNullOrEmpty(schemaNodes)) {
2128 final SchemaNode node = schemaNodes.iterator().next();
2130 if (node instanceof RpcDefinition) {
2131 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2132 } else if (node instanceof NotificationDefinition) {
2133 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2136 sb.append(NEW_LINE);
2138 if (verboseClassComments) {
2140 sb.append(NEW_LINE);
2141 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2142 sb.append("</pre>");
2143 sb.append(NEW_LINE);
2146 return replaceAllIllegalChars(sb);
2149 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2150 final StringBuilder sb = new StringBuilder();
2151 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2152 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2154 if (!Strings.isNullOrEmpty(formattedDescription)) {
2155 sb.append(formattedDescription);
2156 sb.append(NEW_LINE);
2159 if (verboseClassComments) {
2160 final Module module = findParentModule(schemaContext, schemaNode);
2161 final StringBuilder linkToBuilderClass = new StringBuilder();
2162 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2163 final String className = namespace[namespace.length - 1];
2165 if (hasBuilderClass(schemaNode)) {
2166 linkToBuilderClass.append(className);
2167 linkToBuilderClass.append("Builder");
2171 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2172 sb.append(module.getName());
2174 sb.append(NEW_LINE);
2176 sb.append(NEW_LINE);
2177 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2178 sb.append("</pre>");
2179 sb.append(NEW_LINE);
2180 sb.append("The schema path to identify an instance is");
2181 sb.append(NEW_LINE);
2183 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2185 sb.append(NEW_LINE);
2187 if (hasBuilderClass(schemaNode)) {
2188 sb.append(NEW_LINE);
2189 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2190 sb.append(NEW_LINE);
2192 sb.append(linkToBuilderClass);
2193 sb.append(NEW_LINE);
2194 if (schemaNode instanceof ListSchemaNode) {
2195 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2196 if (keyDef != null && !keyDef.isEmpty()) {
2198 sb.append(className);
2201 sb.append(NEW_LINE);
2206 return replaceAllIllegalChars(sb);
2209 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2210 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2211 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2217 private String createDescription(final Module module) {
2218 final StringBuilder sb = new StringBuilder();
2219 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2220 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2222 if (!Strings.isNullOrEmpty(formattedDescription)) {
2223 sb.append(formattedDescription);
2224 sb.append(NEW_LINE);
2227 if (verboseClassComments) {
2229 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2230 sb.append(module.getName());
2232 sb.append(NEW_LINE);
2234 sb.append(NEW_LINE);
2235 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2236 sb.append("</pre>");
2239 return replaceAllIllegalChars(sb);
2242 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2243 for (final ModuleContext ctx : genCtx.values()) {
2244 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2245 if (result != null) {
2252 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2253 for (final ModuleContext ctx : genCtx.values()) {
2254 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2255 if (result != null) {
2262 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2263 for (final ModuleContext ctx : genCtx.values()) {
2264 final GeneratedTypeBuilder result = ctx.getCase(path);
2265 if (result != null) {
2272 public Map<Module, ModuleContext> getModuleContexts() {
2277 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2278 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2279 return ret.isEmpty() ? "" : ret;
2282 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2283 if (status == Status.DEPRECATED) {
2284 builder.addAnnotation("", "Deprecated");