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.type.BitsTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
107 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
114 public class BindingGeneratorImpl implements BindingGenerator {
115 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
116 private static final Splitter COLON_SPLITTER = Splitter.on(':');
117 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
118 private static final char NEW_LINE = '\n';
121 * Comparator based on augment target path.
123 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
124 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
125 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
127 while (thisIt.hasNext()) {
128 if (!otherIt.hasNext()) {
132 final int comp = thisIt.next().compareTo(otherIt.next());
138 return otherIt.hasNext() ? -1 : 0;
142 * Constant with the concrete name of identifier.
144 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
147 * Constant with the concrete name of namespace.
149 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
151 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
153 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
156 * When set to true, generated classes will include javadoc comments which
157 * are useful for users.
159 private final boolean verboseClassComments;
162 * Outer key represents the package name. Outer value represents map of all
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder for schema node specified in key part.
167 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
170 * Provide methods for converting YANG types to JAVA types.
172 private TypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element
176 * when creating augmentation builder
178 private SchemaContext schemaContext;
181 * Create a new binding generator.
183 * @param verboseClassComments generate verbose comments
185 public BindingGeneratorImpl(final boolean verboseClassComments) {
186 this.verboseClassComments = verboseClassComments;
190 * Resolves generated types from <code>context</code> schema nodes of all
193 * Generated types are created for modules, groupings, types, containers,
194 * lists, choices, augments, rpcs, notification, identities.
197 * schema context which contains data about all schema nodes
199 * @return list of types (usually <code>GeneratedType</code>
200 * <code>GeneratedTransferObject</code>which are generated from
201 * <code>context</code> data.
202 * @throws IllegalArgumentException
203 * if arg <code>context</code> is null
204 * @throws IllegalStateException
205 * if <code>context</code> contain no modules
208 public List<Type> generateTypes(final SchemaContext context) {
209 checkArgument(context != null, "Schema Context reference cannot be NULL.");
210 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
211 schemaContext = context;
212 typeProvider = new TypeProviderImpl(context);
213 final Set<Module> modules = context.getModules();
214 return generateTypes(context, modules);
218 * Resolves generated types from <code>context</code> schema nodes only for
219 * modules specified in <code>modules</code>
221 * Generated types are created for modules, groupings, types, containers,
222 * lists, choices, augments, rpcs, notification, identities.
225 * schema context which contains data about all schema nodes
228 * set of modules for which schema nodes should be generated
230 * @return list of types (usually <code>GeneratedType</code> or
231 * <code>GeneratedTransferObject</code>) which:
233 * <li>are generated from <code>context</code> schema nodes and</li>
234 * <li>are also part of some of the module in <code>modules</code>
237 * @throws IllegalArgumentException
239 * <li>if arg <code>context</code> is null or</li>
240 * <li>if arg <code>modules</code> is null</li>
242 * @throws IllegalStateException
243 * if <code>context</code> contain no modules
246 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
247 checkArgument(context != null, "Schema Context reference cannot be NULL.");
248 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
249 checkArgument(modules != null, "Set of Modules cannot be NULL.");
251 schemaContext = context;
252 typeProvider = new TypeProviderImpl(context);
253 final Module[] modulesArray = new Module[context.getModules().size()];
254 context.getModules().toArray(modulesArray);
255 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
256 genTypeBuilders = new HashMap<>();
258 for (final Module contextModule : contextModules) {
259 moduleToGenTypes(contextModule, context);
261 for (final Module contextModule : contextModules) {
262 allAugmentsToGenTypes(contextModule);
265 final List<Type> filteredGenTypes = new ArrayList<>();
266 for (final Module m : modules) {
267 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
268 filteredGenTypes.addAll(ctx.getGeneratedTypes());
269 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
270 if (additionalTypes != null) {
271 filteredGenTypes.addAll(additionalTypes);
275 return filteredGenTypes;
278 private void moduleToGenTypes(final Module m, final SchemaContext context) {
279 genCtx.put(m, new ModuleContext());
280 allTypeDefinitionsToGenTypes(m);
281 groupingsToGenTypes(m, m.getGroupings());
282 rpcMethodsToGenType(m);
283 allIdentitiesToGenTypes(m, context);
284 notificationsToGenType(m);
286 if (!m.getChildNodes().isEmpty()) {
287 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
288 genCtx.get(m).addModuleNode(moduleType);
289 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
290 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
295 * Converts all extended type definitions of module to the list of
296 * <code>Type</code> objects.
299 * module from which is obtained set of type definitions
300 * @throws IllegalArgumentException
302 * <li>if module is null</li>
303 * <li>if name of module is null</li>
305 * @throws IllegalStateException
306 * if set of type definitions from module is null
308 private void allTypeDefinitionsToGenTypes(final Module module) {
309 checkArgument(module != null, "Module reference cannot be NULL.");
310 checkArgument(module.getName() != null, "Module name cannot be NULL.");
311 final DataNodeIterator it = new DataNodeIterator(module);
312 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
313 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
315 for (final TypeDefinition<?> typedef : typeDefinitions) {
316 if (typedef != null) {
317 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
320 final ModuleContext ctx = genCtx.get(module);
321 ctx.addTypedefType(typedef.getPath(), type);
322 ctx.addTypeToSchema(type,typedef);
328 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
329 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
330 if (node.isAugmenting() || node.isAddedByUses()) {
333 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
334 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
335 genType.addComment(node.getDescription());
336 annotateDeprecatedIfNecessary(node.getStatus(), genType);
337 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
338 genType.setModuleName(module.getName());
339 genType.setReference(node.getReference());
340 genType.setSchemaPath(node.getPath().getPathFromRoot());
341 if (node instanceof DataNodeContainer) {
342 genCtx.get(module).addChildNodeType(node, genType);
343 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
344 processUsesAugments((DataNodeContainer) node, module);
349 private void containerToGenType(final Module module, final String basePackageName,
350 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
351 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
352 if (genType != null) {
353 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
354 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
358 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
359 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
360 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
361 if (genType != null) {
362 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
363 Types.listTypeFor(genType), node.getStatus());
365 final List<String> listKeys = listKeys(node);
366 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
367 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
368 if (genTOBuilder != null) {
369 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
370 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
371 genTOBuilder.addImplementsType(identifierMarker);
372 genType.addImplementsType(identifiableMarker);
375 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
376 if (!schemaNode.isAugmenting()) {
377 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
382 if (genTOBuilder != null) {
383 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
384 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
385 genTOBuilder.setSUID(prop);
388 typeBuildersToGenTypes(module, genType, genTOBuilder);
392 private void processUsesAugments(final DataNodeContainer node, final Module module) {
393 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
394 for (final UsesNode usesNode : node.getUses()) {
395 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
396 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
397 processUsesAugments(augment, module);
403 * Converts all <b>augmentation</b> of the module to the list
404 * <code>Type</code> objects.
407 * module from which is obtained list of all augmentation objects
408 * to iterate over them
409 * @throws IllegalArgumentException
411 * <li>if the module is null</li>
412 * <li>if the name of module is null</li>
414 * @throws IllegalStateException
415 * if set of augmentations from module is null
417 private void allAugmentsToGenTypes(final Module module) {
418 checkArgument(module != null, "Module reference cannot be NULL.");
419 checkArgument(module.getName() != null, "Module name cannot be NULL.");
420 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
422 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
423 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
424 for (final AugmentationSchema augment : augmentations) {
425 augmentationToGenTypes(basePackageName, augment, module);
430 * Returns list of <code>AugmentationSchema</code> objects. The objects are
431 * sorted according to the length of their target path from the shortest to
435 * module from which is obtained list of all augmentation objects
436 * @return list of sorted <code>AugmentationSchema</code> objects obtained
437 * from <code>module</code>
438 * @throws IllegalArgumentException
440 * @throws IllegalStateException
441 * if set of module augmentations is null
443 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
444 checkArgument(module != null, "Module reference cannot be NULL.");
445 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
447 final Set<AugmentationSchema> augmentations = module.getAugmentations();
448 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
449 Collections.sort(sortedAugmentations, AUGMENT_COMP);
451 return sortedAugmentations;
455 * Create GeneratedTypeBuilder object from module argument.
458 * Module object from which builder will be created
459 * @return <code>GeneratedTypeBuilder</code> which is internal
460 * representation of the module
461 * @throws IllegalArgumentException
464 private GeneratedTypeBuilder moduleToDataType(final Module module) {
465 checkArgument(module != null, "Module reference cannot be NULL.");
467 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
468 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
469 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
470 moduleDataTypeBuilder.addComment(module.getDescription());
471 moduleDataTypeBuilder.setDescription(createDescription(module));
472 moduleDataTypeBuilder.setReference(module.getReference());
473 return moduleDataTypeBuilder;
477 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
478 * to the list of <code>Type</code> objects. In addition are to containers
479 * and lists which belong to input or output also part of returning list.
482 * module from which is obtained set of all rpc objects to
484 * @throws IllegalArgumentException
486 * <li>if the module is null</li>
487 * <li>if the name of module is null</li>
489 * @throws IllegalStateException
490 * if set of rpcs from module is null
492 private void rpcMethodsToGenType(final Module module) {
493 checkArgument(module != null, "Module reference cannot be NULL.");
494 checkArgument(module.getName() != null, "Module name cannot be NULL.");
495 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
496 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
497 if (rpcDefinitions.isEmpty()) {
501 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
502 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
503 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
504 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
506 for (final RpcDefinition rpc : rpcDefinitions) {
508 final String rpcName = BindingMapping.getClassName(rpc.getQName());
509 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
510 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
511 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
512 final ContainerSchemaNode input = rpc.getInput();
513 final ContainerSchemaNode output = rpc.getOutput();
516 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
517 addImplementedInterfaceFromUses(input, inType);
518 inType.addImplementsType(DATA_OBJECT);
519 inType.addImplementsType(augmentable(inType));
520 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
521 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
522 genCtx.get(module).addChildNodeType(input, inType);
523 final GeneratedType inTypeInstance = inType.toInstance();
524 method.addParameter(inTypeInstance, "input");
527 Type outTypeInstance = VOID;
528 if (output != null) {
529 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
530 addImplementedInterfaceFromUses(output, outType);
531 outType.addImplementsType(DATA_OBJECT);
532 outType.addImplementsType(augmentable(outType));
533 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
534 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
535 genCtx.get(module).addChildNodeType(output, outType);
536 outTypeInstance = outType.toInstance();
539 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
540 method.setComment(rpcComment);
541 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
545 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
549 * Converts all <b>notifications</b> of the module to the list of
550 * <code>Type</code> objects. In addition are to this list added containers
551 * and lists which are part of this notification.
554 * module from which is obtained set of all notification objects
555 * to iterate over them
556 * @throws IllegalArgumentException
558 * <li>if the module equals null</li>
559 * <li>if the name of module equals null</li>
561 * @throws IllegalStateException
562 * if set of notifications from module is null
564 private void notificationsToGenType(final Module module) {
565 checkArgument(module != null, "Module reference cannot be NULL.");
566 checkArgument(module.getName() != null, "Module name cannot be NULL.");
567 final Set<NotificationDefinition> notifications = module.getNotifications();
568 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
569 if (notifications.isEmpty()) {
573 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
574 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
575 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
579 for (final NotificationDefinition notification : notifications) {
580 if (notification != null) {
581 processUsesAugments(notification, module);
583 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
584 notification, null, module);
585 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
586 notificationInterface.addImplementsType(NOTIFICATION);
587 genCtx.get(module).addChildNodeType(notification, notificationInterface);
589 // Notification object
590 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
591 notification.getChildNodes());
593 listenerInterface.addMethod("on" + notificationInterface.getName())
594 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
595 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
598 listenerInterface.setDescription(createDescription(notifications, module.getName()));
600 genCtx.get(module).addTopLevelNodeType(listenerInterface);
604 * Converts all <b>identities</b> of the module to the list of
605 * <code>Type</code> objects.
608 * module from which is obtained set of all identity objects to
611 * schema context only used as input parameter for method
612 * {@link identityToGenType}
615 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
616 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
617 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
619 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
620 for (final IdentitySchemaNode identity : schemaIdentities) {
621 identityToGenType(module, basePackageName, identity, context);
627 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
628 * created transport object builder. If identity contains base identity then
629 * reference to base identity is added to superior identity as its extend.
630 * If identity doesn't contain base identity then only reference to abstract
631 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
632 * BaseIdentity} is added
636 * @param basePackageName
637 * string contains the module package name
639 * IdentitySchemaNode which contains data about identity
641 * SchemaContext which is used to get package and name
642 * information about base of identity
645 private void identityToGenType(final Module module, final String basePackageName,
646 final IdentitySchemaNode identity, final SchemaContext context) {
647 if (identity == null) {
650 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
651 final String genTypeName = BindingMapping.getClassName(identity.getQName());
652 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
653 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
654 if (baseIdentity == null) {
655 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
656 BaseIdentity.class.getSimpleName());
657 newType.setExtendsType(gto.toInstance());
659 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
660 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
662 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
663 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
665 newType.setExtendsType(gto);
667 newType.setAbstract(true);
668 newType.addComment(identity.getDescription());
669 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
670 newType.setReference(identity.getReference());
671 newType.setModuleName(module.getName());
672 newType.setSchemaPath(identity.getPath().getPathFromRoot());
674 final QName qname = identity.getQName();
675 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
677 genCtx.get(module).addIdentityType(identity.getQName(), newType);
680 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
682 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
686 * Converts all <b>groupings</b> of the module to the list of
687 * <code>Type</code> objects. Firstly are groupings sorted according mutual
688 * dependencies. At least dependent (independent) groupings are in the list
689 * saved at first positions. For every grouping the record is added to map
690 * {@link BindingGeneratorImpl#allGroupings allGroupings}
695 * of groupings from which types will be generated
698 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
699 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
700 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
702 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
703 groupingToGenType(basePackageName, grouping, module);
708 * Converts individual grouping to GeneratedType. Firstly generated type
709 * builder is created and every child node of grouping is resolved to the
712 * @param basePackageName
713 * string contains the module package name
715 * GroupingDefinition which contains data about grouping
718 * @return GeneratedType which is generated from grouping (object of type
719 * <code>GroupingDefinition</code>)
721 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
722 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
723 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
724 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
725 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
726 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
727 groupingsToGenTypes(module, grouping.getGroupings());
728 processUsesAugments(grouping, module);
732 * Adds enumeration builder created from <code>enumTypeDef</code> to
733 * <code>typeBuilder</code>.
735 * Each <code>enumTypeDef</code> item is added to builder with its name and
739 * EnumTypeDefinition contains enum data
741 * string contains name which will be assigned to enumeration
744 * GeneratedTypeBuilder to which will be enum builder assigned
746 * Module in which type should be generated
747 * @return enumeration builder which contains data from
748 * <code>enumTypeDef</code>
750 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
751 final GeneratedTypeBuilder typeBuilder, final Module module) {
752 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
753 && (enumTypeDef.getQName().getLocalName() != null)) {
754 final String enumerationName = BindingMapping.getClassName(enumName);
755 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
756 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
757 enumBuilder.setDescription(enumTypedefDescription);
758 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
759 ModuleContext ctx = genCtx.get(module);
760 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
767 * Generates type builder for <code>module</code>.
770 * Module which is source of package name for generated type
773 * string which is added to the module class name representation
775 * @return instance of GeneratedTypeBuilder which represents
776 * <code>module</code>.
777 * @throws IllegalArgumentException
778 * if <code>module</code> is null
780 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
781 checkArgument(module != null, "Module reference cannot be NULL.");
782 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
783 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
785 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
786 moduleBuilder.setDescription(createDescription(module));
787 moduleBuilder.setReference(module.getReference());
788 moduleBuilder.setModuleName(moduleName);
790 return moduleBuilder;
794 * Converts <code>augSchema</code> to list of <code>Type</code> which
795 * contains generated type for augmentation. In addition there are also
796 * generated types for all containers, list and choices which are child of
797 * <code>augSchema</code> node or a generated types for cases are added if
798 * augmented node is choice.
800 * @param augmentPackageName
801 * string with the name of the package to which the augmentation
804 * AugmentationSchema which is contains data about augmentation
805 * (target path, childs...)
808 * @param parentUsesNode
809 * @throws IllegalArgumentException
811 * <li>if <code>augmentPackageName</code> equals null</li>
812 * <li>if <code>augSchema</code> equals null</li>
814 * @throws IllegalStateException
815 * if augment target path is null
817 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
818 final Module module) {
819 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
820 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
821 checkState(augSchema.getTargetPath() != null,
822 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
824 processUsesAugments(augSchema, module);
825 final SchemaPath targetPath = augSchema.getTargetPath();
826 SchemaNode targetSchemaNode = null;
828 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
829 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
830 if (targetSchemaNode instanceof DerivableSchemaNode) {
831 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
833 if (targetSchemaNode == null) {
834 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
835 + " in module " + module.getName());
838 if (targetSchemaNode == null) {
839 throw new IllegalArgumentException("augment target not found: " + targetPath);
842 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
843 if (targetTypeBuilder == null) {
844 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
846 if (targetTypeBuilder == null) {
847 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
850 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
851 final String packageName = augmentPackageName;
852 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
853 targetTypeBuilder.getName());
854 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
857 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
858 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
862 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
863 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
864 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
865 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
866 checkState(augSchema.getTargetPath() != null,
867 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
869 processUsesAugments(augSchema, module);
870 final SchemaPath targetPath = augSchema.getTargetPath();
871 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
872 if (targetSchemaNode == null) {
873 throw new IllegalArgumentException("augment target not found: " + targetPath);
876 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
877 if (targetTypeBuilder == null) {
878 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
880 if (targetTypeBuilder == null) {
881 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
884 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
885 String packageName = augmentPackageName;
886 if (usesNodeParent instanceof SchemaNode) {
887 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
889 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
892 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
893 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
898 * Convenient method to find node added by uses statement.
902 * @param parentUsesNode
903 * parent of uses node
904 * @return node from its original location in grouping
906 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
907 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
909 if (!(targetGrouping instanceof GroupingDefinition)) {
910 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
913 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
914 SchemaNode result = grouping;
915 for (final QName node : targetPath.getPathFromRoot()) {
916 if (result instanceof DataNodeContainer) {
917 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
918 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
919 } else if (result instanceof ChoiceSchemaNode) {
920 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
923 if (result == null) {
927 if (result instanceof DerivableSchemaNode) {
928 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
929 Optional<? extends SchemaNode> originalNode = castedResult
931 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
932 result = originalNode.get();
936 if (result instanceof DataSchemaNode) {
937 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
938 if (resultDataSchemaNode.isAddedByUses()) {
939 // The original node is required, but we have only the copy of
940 // the original node.
941 // Maybe this indicates a bug in Yang parser.
942 throw new IllegalStateException(
943 "Failed to generate code for augment in "
946 return resultDataSchemaNode;
949 throw new IllegalStateException(
950 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
956 * Returns a generated type builder for an augmentation.
958 * The name of the type builder is equal to the name of augmented node with
959 * serial number as suffix.
963 * @param augmentPackageName
964 * string with contains the package name to which the augment
966 * @param basePackageName
967 * string with the package name to which the augmented node
969 * @param targetTypeRef
972 * augmentation schema which contains data about the child nodes
973 * and uses of augment
974 * @return generated type builder for augment
976 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
977 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
978 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
979 if (augmentBuilders == null) {
980 augmentBuilders = new HashMap<>();
981 genTypeBuilders.put(augmentPackageName, augmentBuilders);
983 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
986 if (augIdentifier != null) {
987 augTypeName = BindingMapping.getClassName(augIdentifier);
989 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
992 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
994 augTypeBuilder.addImplementsType(DATA_OBJECT);
995 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
996 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
997 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
999 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1000 augmentBuilders.put(augTypeName, augTypeBuilder);
1002 if (!augSchema.getChildNodes().isEmpty()) {
1003 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1006 genCtx.get(module).addAugmentType(augTypeBuilder);
1007 return augTypeBuilder;
1012 * @param unknownSchemaNodes
1013 * @return nodeParameter of UnknownSchemaNode
1015 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1016 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1017 final QName nodeType = unknownSchemaNode.getNodeType();
1018 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1019 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1020 return unknownSchemaNode.getNodeParameter();
1027 * Returns first unique name for the augment generated type builder. The
1028 * generated type builder name for augment consists from name of augmented
1029 * node and serial number of its augmentation.
1032 * map of builders which were created in the package to which the
1033 * augmentation belongs
1034 * @param genTypeName
1035 * string with name of augmented node
1036 * @return string with unique name for augmentation builder
1038 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1040 if (builders != null) {
1041 while (builders.containsKey(genTypeName + index)) {
1045 return genTypeName + index;
1049 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1050 * node for which <code>typeBuilder</code> was created.
1052 * The subnodes aren't mapped to the methods if they are part of grouping or
1053 * augment (in this case are already part of them).
1057 * @param basePackageName
1058 * string contains the module package name
1060 * generated type builder which represents any node. The subnodes
1061 * of this node are added to the <code>typeBuilder</code> as
1062 * methods. The subnode can be of type leaf, leaf-list, list,
1063 * container, choice.
1066 * @param schemaNodes
1067 * set of data schema nodes which are the children of the node
1068 * for which <code>typeBuilder</code> was created
1069 * @return generated type builder which is the same builder as input
1070 * parameter. The getter methods (representing child nodes) could be
1073 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1074 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1075 if (schemaNodes != null && parent != null) {
1076 for (final DataSchemaNode schemaNode : schemaNodes) {
1077 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1078 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1086 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1087 * node for which <code>typeBuilder</code> was created.
1091 * @param basePackageName
1092 * string contains the module package name
1093 * @param typeBuilder
1094 * generated type builder which represents any node. The subnodes
1095 * of this node are added to the <code>typeBuilder</code> as
1096 * methods. The subnode can be of type leaf, leaf-list, list,
1097 * container, choice.
1100 * @param schemaNodes
1101 * set of data schema nodes which are the children of the node
1102 * for which <code>typeBuilder</code> was created
1103 * @return generated type builder which is the same object as the input
1104 * parameter <code>typeBuilder</code>. The getter method could be
1107 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1108 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1109 final Iterable<DataSchemaNode> schemaNodes) {
1110 if ((schemaNodes != null) && (typeBuilder != null)) {
1111 for (final DataSchemaNode schemaNode : schemaNodes) {
1112 if (!schemaNode.isAugmenting()) {
1113 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1121 * Adds to <code>typeBuilder</code> a method which is derived from
1122 * <code>schemaNode</code>.
1124 * @param basePackageName
1125 * string with the module package name
1127 * data schema node which is added to <code>typeBuilder</code> as
1129 * @param typeBuilder
1130 * generated type builder to which is <code>schemaNode</code>
1131 * added as a method.
1137 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1138 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1139 if (node != null && typeBuilder != null) {
1140 if (node instanceof LeafSchemaNode) {
1141 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1142 } else if (node instanceof LeafListSchemaNode) {
1143 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1144 } else if (node instanceof ContainerSchemaNode) {
1145 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1146 } else if (node instanceof ListSchemaNode) {
1147 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1148 } else if (node instanceof ChoiceSchemaNode) {
1149 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1151 // TODO: anyxml not yet supported
1152 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1153 typeBuilder.getFullyQualifiedName());
1159 * Converts <code>choiceNode</code> to the list of generated types for
1160 * choice and its cases.
1162 * The package names for choice and for its cases are created as
1163 * concatenation of the module package (<code>basePackageName</code>) and
1164 * names of all parents node.
1168 * @param basePackageName
1169 * string with the module package name
1173 * choice node which is mapped to generated type. Also child
1174 * nodes - cases are mapped to generated types.
1175 * @throws IllegalArgumentException
1177 * <li>if <code>basePackageName</code> is null</li>
1178 * <li>if <code>choiceNode</code> is null</li>
1181 private void choiceToGeneratedType(final Module module, final String basePackageName,
1182 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1183 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1184 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1186 if (!choiceNode.isAddedByUses()) {
1187 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1188 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1189 constructGetter(parent, choiceNode.getQName().getLocalName(),
1190 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1191 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1192 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1193 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1194 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1199 * Converts <code>caseNodes</code> set to list of corresponding generated
1202 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1203 * created generated type builder. The package names for the builder is
1204 * created as concatenation of the module package (
1205 * <code>basePackageName</code>) and names of all parents nodes of the
1206 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1207 * between every case builder and <i>choice</i> type
1211 * @param basePackageName
1212 * string with the module package name
1213 * @param refChoiceType
1214 * type which represents superior <i>case</i>
1216 * choice case node which is mapped to generated type
1217 * @return list of generated types for <code>caseNodes</code>.
1218 * @throws IllegalArgumentException
1220 * <li>if <code>basePackageName</code> equals null</li>
1221 * <li>if <code>refChoiceType</code> equals null</li>
1222 * <li>if <code>caseNodes</code> equals null</li>
1225 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1226 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1227 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1228 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1229 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1231 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1232 if (caseNodes == null) {
1236 for (final ChoiceCaseNode caseNode : caseNodes) {
1237 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1238 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1239 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1240 caseTypeBuilder.addImplementsType(refChoiceType);
1241 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1242 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1243 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1244 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1245 if (caseChildNodes != null) {
1246 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1248 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1249 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1251 if (parent instanceof AugmentationSchema) {
1252 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1253 final SchemaPath targetPath = augSchema.getTargetPath();
1254 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1255 if (targetSchemaNode instanceof DataSchemaNode
1256 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1260 if (targetSchemaNode == null) {
1261 throw new IllegalStateException(
1262 "Failed to find target node from grouping for augmentation " + augSchema
1263 + " in module " + module.getName());
1266 parent = targetSchemaNode;
1269 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1270 choiceNodeParentPath);
1271 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1272 if (childOfType == null) {
1273 childOfType = findGroupingByPath(parent.getPath());
1275 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1277 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1282 processUsesAugments(caseNode, module);
1287 * Generates list of generated types for all the cases of a choice which are
1288 * added to the choice through the augment.
1292 * @param basePackageName
1293 * string contains name of package to which augment belongs. If
1294 * an augmented choice is from an other package (pcg1) than an
1295 * augmenting choice (pcg2) then case's of the augmenting choice
1296 * will belong to pcg2.
1298 * Type which represents target choice
1300 * node which represents target choice
1301 * @param augmentedNodes
1302 * set of choice case nodes for which is checked if are/aren't
1303 * added to choice through augmentation
1304 * @return list of generated types which represents augmented cases of
1305 * choice <code>refChoiceType</code>
1306 * @throws IllegalArgumentException
1308 * <li>if <code>basePackageName</code> is null</li>
1309 * <li>if <code>targetType</code> is null</li>
1310 * <li>if <code>augmentedNodes</code> is null</li>
1313 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1314 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1315 final DataNodeContainer usesNodeParent) {
1316 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1317 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1318 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1320 for (final DataSchemaNode caseNode : augmentedNodes) {
1321 if (caseNode != null) {
1322 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1323 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1324 caseTypeBuilder.addImplementsType(targetType);
1326 SchemaNode parent = null;
1327 final SchemaPath nodeSp = targetNode.getPath();
1328 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1330 GeneratedTypeBuilder childOfType = null;
1331 if (parent instanceof Module) {
1332 childOfType = genCtx.get(parent).getModuleNode();
1333 } else if (parent instanceof ChoiceCaseNode) {
1334 childOfType = findCaseByPath(parent.getPath());
1335 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1336 childOfType = findChildNodeByPath(parent.getPath());
1337 } else if (parent instanceof GroupingDefinition) {
1338 childOfType = findGroupingByPath(parent.getPath());
1341 if (childOfType == null) {
1342 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1345 ChoiceCaseNode node = null;
1346 final String caseLocalName = caseNode.getQName().getLocalName();
1347 if (caseNode instanceof ChoiceCaseNode) {
1348 node = (ChoiceCaseNode) caseNode;
1349 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1350 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1351 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1352 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1353 ().getLocalName())) {
1354 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1359 node = targetNode.getCaseNodeByName(caseLocalName);
1361 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1362 if (childNodes != null) {
1363 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1365 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1366 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1371 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1372 // New parser with encapsulated type
1373 if (leaf.getPath().equals(type.getPath())) {
1377 // Embedded type definition with new parser. Also takes care of the old parser with bits
1378 if (leaf.getPath().equals(type.getPath().getParent())) {
1386 * Converts <code>leaf</code> to the getter method which is added to
1387 * <code>typeBuilder</code>.
1389 * @param typeBuilder
1390 * generated type builder to which is added getter method as
1391 * <code>leaf</code> mapping
1393 * leaf schema node which is mapped as getter method which is
1394 * added to <code>typeBuilder</code>
1396 * Module in which type was defined
1397 * @return boolean value
1399 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1401 * <li>true - in other cases</li>
1404 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1405 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1409 final String leafName = leaf.getQName().getLocalName();
1410 if (leafName == null) {
1414 final Module parentModule = findParentModule(schemaContext, leaf);
1415 Type returnType = null;
1417 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1418 if (isInnerType(leaf, typeDef)) {
1419 if (typeDef instanceof EnumTypeDefinition) {
1420 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1421 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1422 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1423 typeBuilder, module);
1424 if (enumBuilder != null) {
1425 returnType = enumBuilder.toInstance(typeBuilder);
1427 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1428 } else if (typeDef instanceof UnionTypeDefinition) {
1429 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1430 if (genTOBuilder != null) {
1431 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1433 } else if (typeDef instanceof BitsTypeDefinition) {
1434 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1435 if (genTOBuilder != null) {
1436 returnType = genTOBuilder.toInstance();
1439 // It is constrained version of already declared type (inner declared type exists,
1440 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1441 // In order to get proper class we need to look up closest derived type
1442 // and apply restrictions from leaf type
1443 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1444 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1448 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1449 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1452 if (returnType == null) {
1456 if (typeDef instanceof EnumTypeDefinition) {
1457 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1460 String leafDesc = leaf.getDescription();
1461 if (leafDesc == null) {
1465 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1466 processContextRefExtension(leaf, getter, parentModule);
1470 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1471 // Returns DerivedType in case of new parser.
1472 final TypeDefinition<?> baseType = typeDef.getBaseType();
1473 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1476 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1477 final Module module) {
1478 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1479 final QName nodeType = node.getNodeType();
1480 if ("context-reference".equals(nodeType.getLocalName())) {
1481 final String nodeParam = node.getNodeParameter();
1482 IdentitySchemaNode identity = null;
1483 String basePackageName = null;
1484 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1485 final Iterator<String> iterator = splittedElement.iterator();
1486 final int length = Iterables.size(splittedElement);
1488 identity = findIdentityByName(module.getIdentities(), iterator.next());
1489 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1490 } else if (length == 2) {
1491 final String prefix = iterator.next();
1492 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1493 if (dependentModule == null) {
1494 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1497 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1498 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1500 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1503 if (identity == null) {
1504 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1508 final Class<RoutingContext> clazz = RoutingContext.class;
1509 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1510 clazz.getSimpleName());
1511 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1512 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1513 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1518 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1519 for (final IdentitySchemaNode id : identities) {
1520 if (id.getQName().getLocalName().equals(name)) {
1527 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1528 for (final ModuleImport imp : imports) {
1529 if (imp.getPrefix().equals(prefix)) {
1530 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1536 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1537 final boolean isReadOnly, final Module module) {
1538 if ((leaf != null) && (toBuilder != null)) {
1539 String leafDesc = leaf.getDescription();
1540 if (leafDesc == null) {
1543 Type returnType = null;
1544 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1545 if (typeDef instanceof UnionTypeDefinition) {
1546 // GeneratedType for this type definition should be already
1548 final QName qname = typeDef.getQName();
1549 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1550 qname.getRevision());
1551 final ModuleContext mc = genCtx.get(unionModule);
1552 returnType = mc.getTypedefs().get(typeDef.getPath());
1553 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1554 // Annonymous enumeration (already generated, since it is inherited via uses).
1555 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1556 QName qname = originalLeaf.getQName();
1557 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1558 qname.getRevision());
1559 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1561 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1563 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1569 * Converts <code>leaf</code> schema node to property of generated TO
1573 * generated TO builder to which is <code>leaf</code> added as
1576 * leaf schema node which is added to <code>toBuilder</code> as
1581 * boolean value which says if leaf property is|isn't read only
1582 * @return boolean value
1584 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1585 * name equals null or if leaf is added by <i>uses</i>.</li>
1586 * <li>true - other cases</li>
1589 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1590 final Type returnType, final boolean isReadOnly) {
1591 if (returnType == null) {
1594 final String leafName = leaf.getQName().getLocalName();
1595 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1596 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1597 propBuilder.setReadOnly(isReadOnly);
1598 propBuilder.setReturnType(returnType);
1599 propBuilder.setComment(leafDesc);
1600 toBuilder.addEqualsIdentity(propBuilder);
1601 toBuilder.addHashIdentity(propBuilder);
1602 toBuilder.addToStringProperty(propBuilder);
1607 * Converts <code>node</code> leaf list schema node to getter method of
1608 * <code>typeBuilder</code>.
1610 * @param typeBuilder
1611 * generated type builder to which is <code>node</code> added as
1614 * leaf list schema node which is added to
1615 * <code>typeBuilder</code> as getter method
1617 * @return boolean value
1619 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1620 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1621 * <li>false - other cases</li>
1624 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1625 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1629 final QName nodeName = node.getQName();
1630 if (nodeName == null) {
1634 final TypeDefinition<?> typeDef = node.getType();
1635 final Module parentModule = findParentModule(schemaContext, node);
1637 Type returnType = null;
1638 if (typeDef.getBaseType() == null) {
1639 if (typeDef instanceof EnumTypeDefinition) {
1640 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1641 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1642 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1643 typeBuilder,module);
1644 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1645 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1646 } else if (typeDef instanceof UnionTypeDefinition) {
1647 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1648 if (genTOBuilder != null) {
1649 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1651 } else if (typeDef instanceof BitsTypeDefinition) {
1652 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1653 returnType = genTOBuilder.toInstance();
1655 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1656 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1659 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1660 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1663 final ParameterizedType listType = Types.listTypeFor(returnType);
1664 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1668 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1669 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1670 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1671 genTOBuilder.getName());
1672 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1674 returnType.setDescription(typedefDescription);
1675 returnType.setReference(typeDef.getReference());
1676 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1677 returnType.setModuleName(parentModule.getName());
1679 genTOBuilder.setTypedef(true);
1680 genTOBuilder.setIsUnion(true);
1681 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1685 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1688 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1689 method.setReturnType(returnType);
1690 method.addParameter(Types.STRING, "defaultValue");
1691 method.setAccessModifier(AccessModifier.PUBLIC);
1692 method.setStatic(true);
1694 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1695 if (types == null) {
1696 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1697 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1699 types.add(unionBuilder.toInstance());
1701 return returnType.toInstance();
1704 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1705 final String outerCls = Types.getOuterClassName(genTOBuilder);
1706 final StringBuilder name;
1707 if (outerCls != null) {
1708 name = new StringBuilder(outerCls);
1710 name = new StringBuilder();
1712 name.append(genTOBuilder.getName());
1713 name.append("Builder");
1714 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1715 unionBuilder.setIsUnionBuilder(true);
1716 return unionBuilder;
1719 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1720 final Module module) {
1721 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1725 * Instantiates generated type builder with <code>packageName</code> and
1726 * <code>schemaNode</code>.
1728 * The new builder always implements
1729 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1730 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1731 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1733 * If <code>schemaNode</code> is instance of
1734 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1735 * DataNodeContainer} it can also implement nodes which are specified in
1738 * @param packageName
1739 * string with the name of the package to which
1740 * <code>schemaNode</code> belongs.
1742 * schema node for which is created generated type builder
1744 * parent type (can be null)
1745 * @return generated type builder <code>schemaNode</code>
1747 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1748 final Type parent, final Module module) {
1749 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1750 if (parent == null) {
1751 it.addImplementsType(DATA_OBJECT);
1753 it.addImplementsType(BindingTypes.childOf(parent));
1755 if (!(schemaNode instanceof GroupingDefinition)) {
1756 it.addImplementsType(augmentable(it));
1759 if (schemaNode instanceof DataNodeContainer) {
1760 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1761 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1768 * Wraps the calling of the same overloaded method.
1770 * @param packageName
1771 * string with the package name to which returning generated type
1774 * schema node which provide data about the schema node name
1775 * @return generated type builder for <code>schemaNode</code>
1777 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1778 return addRawInterfaceDefinition(packageName, schemaNode, "");
1782 * Returns reference to generated type builder for specified
1783 * <code>schemaNode</code> with <code>packageName</code>.
1785 * Firstly the generated type builder is searched in
1786 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1787 * found it is created and added to <code>genTypeBuilders</code>.
1789 * @param packageName
1790 * string with the package name to which returning generated type
1793 * schema node which provide data about the schema node name
1795 * return type name prefix
1796 * @return generated type builder for <code>schemaNode</code>
1797 * @throws IllegalArgumentException
1799 * <li>if <code>schemaNode</code> is null</li>
1800 * <li>if <code>packageName</code> is null</li>
1801 * <li>if QName of schema node is null</li>
1802 * <li>if schemaNode name is null</li>
1806 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1807 final String prefix) {
1808 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1809 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1810 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1811 final String schemaNodeName = schemaNode.getQName().getLocalName();
1812 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1815 if (prefix == null) {
1816 genTypeName = BindingMapping.getClassName(schemaNodeName);
1818 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1821 // FIXME: Validation of name conflict
1822 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1823 final Module module = findParentModule(schemaContext, schemaNode);
1824 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1825 newType.addComment(schemaNode.getDescription());
1826 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1827 newType.setReference(schemaNode.getReference());
1828 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1829 newType.setModuleName(module.getName());
1831 if (!genTypeBuilders.containsKey(packageName)) {
1832 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1833 builders.put(genTypeName, newType);
1834 genTypeBuilders.put(packageName, builders);
1836 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1837 if (!builders.containsKey(genTypeName)) {
1838 builders.put(genTypeName, newType);
1845 * Creates the name of the getter method name from <code>localName</code>.
1848 * string with the name of the getter method
1851 * @return string with the name of the getter method for
1852 * <code>methodName</code> in JAVA method format
1854 public static String getterMethodName(final String localName, final Type returnType) {
1855 final StringBuilder method = new StringBuilder();
1856 if (BOOLEAN.equals(returnType)) {
1857 method.append("is");
1859 method.append("get");
1861 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1862 method.append(name);
1863 return method.toString();
1867 * Created a method signature builder as part of
1868 * <code>interfaceBuilder</code>.
1870 * The method signature builder is created for the getter method of
1871 * <code>schemaNodeName</code>. Also <code>comment</code> and
1872 * <code>returnType</code> information are added to the builder.
1874 * @param interfaceBuilder
1875 * generated type builder for which the getter method should be
1877 * @param schemaNodeName
1878 * string with schema node name. The name will be the part of the
1879 * getter method name.
1881 * string with comment for the getter method
1883 * type which represents the return type of the getter method
1885 * status from yang file, for deprecated annotation
1886 * @return method signature builder which represents the getter method of
1887 * <code>interfaceBuilder</code>
1889 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1890 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1891 final MethodSignatureBuilder getMethod = interfaceBuilder
1892 .addMethod(getterMethodName(schemaNodeName, returnType));
1893 if (status == Status.DEPRECATED) {
1894 getMethod.addAnnotation("", "Deprecated");
1896 getMethod.setComment(encodeAngleBrackets(comment));
1897 getMethod.setReturnType(returnType);
1902 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1903 * or to <code>genTOBuilder</code> as property.
1905 * @param basePackageName
1906 * string contains the module package name
1908 * data schema node which should be added as getter method to
1909 * <code>typeBuilder</code> or as a property to
1910 * <code>genTOBuilder</code> if is part of the list key
1911 * @param typeBuilder
1912 * generated type builder for the list schema node
1913 * @param genTOBuilder
1914 * generated TO builder for the list keys
1916 * list of string which contains names of the list keys
1919 * @throws IllegalArgumentException
1921 * <li>if <code>schemaNode</code> equals null</li>
1922 * <li>if <code>typeBuilder</code> equals null</li>
1925 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1926 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1927 final Module module) {
1928 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1929 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1931 if (schemaNode instanceof LeafSchemaNode) {
1932 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1933 final String leafName = leaf.getQName().getLocalName();
1934 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1935 if (listKeys.contains(leafName)) {
1937 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1939 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1942 } else if (!schemaNode.isAddedByUses()) {
1943 if (schemaNode instanceof LeafListSchemaNode) {
1944 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1945 } else if (schemaNode instanceof ContainerSchemaNode) {
1946 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1947 } else if (schemaNode instanceof ChoiceSchemaNode) {
1948 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1949 } else if (schemaNode instanceof ListSchemaNode) {
1950 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1955 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1956 final GeneratedTOBuilder genTOBuilder) {
1957 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1959 if (genTOBuilder != null) {
1960 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1961 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1962 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1967 * Selects the names of the list keys from <code>list</code> and returns
1968 * them as the list of the strings
1971 * of string with names of the list keys
1972 * @return list of string which represents names of the list keys. If the
1973 * <code>list</code> contains no keys then the empty list is
1976 private static List<String> listKeys(final ListSchemaNode list) {
1977 final List<String> listKeys = new ArrayList<>();
1979 final List<QName> keyDefinition = list.getKeyDefinition();
1980 if (keyDefinition != null) {
1981 for (final QName keyDef : keyDefinition) {
1982 listKeys.add(keyDef.getLocalName());
1989 * Generates for the <code>list</code> which contains any list keys special
1990 * generated TO builder.
1992 * @param packageName
1993 * string with package name to which the list belongs
1995 * list schema node which is source of data about the list name
1996 * @return generated TO builder which represents the keys of the
1997 * <code>list</code> or null if <code>list</code> is null or list of
1998 * key definitions is null or empty.
2000 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2001 GeneratedTOBuilder genTOBuilder = null;
2002 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2003 final String listName = list.getQName().getLocalName() + "Key";
2004 final String genTOName = BindingMapping.getClassName(listName);
2005 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2007 return genTOBuilder;
2011 * Builds generated TO builders for <code>typeDef</code> of type
2012 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2013 * also added to <code>typeBuilder</code> as enclosing transfer object.
2015 * If more then one generated TO builder is created for enclosing then all
2016 * of the generated TO builders are added to <code>typeBuilder</code> as
2017 * enclosing transfer objects.
2020 * type definition which can be of type <code>UnionType</code> or
2021 * <code>BitsTypeDefinition</code>
2022 * @param typeBuilder
2023 * generated type builder to which is added generated TO created
2024 * from <code>typeDef</code>
2026 * string with name for generated TO builder
2028 * @return generated TO builder for <code>typeDef</code>
2030 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2031 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2032 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2033 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2034 final String packageName = typeBuilder.getFullyQualifiedName();
2035 if (typeDef instanceof UnionTypeDefinition) {
2036 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2037 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2038 classNameFromLeaf, leaf);
2039 genTOBuilders.addAll(types);
2041 GeneratedTOBuilder resultTOBuilder = null;
2042 if (types.isEmpty()) {
2043 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2045 resultTOBuilder = types.remove(0);
2046 for (final GeneratedTOBuilder genTOBuilder : types) {
2047 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2050 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2051 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2052 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2053 resultTOBuilder.addHashIdentity(genPropBuilder);
2054 resultTOBuilder.addToStringProperty(genPropBuilder);
2056 } else if (typeDef instanceof BitsTypeDefinition) {
2057 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2058 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2060 if (!genTOBuilders.isEmpty()) {
2061 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2062 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2064 return genTOBuilders.get(0);
2071 * Adds the implemented types to type builder.
2073 * The method passes through the list of <i>uses</i> in
2074 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2075 * generated type from {@link BindingGeneratorImpl#allGroupings
2076 * allGroupings} which is added as <i>implements type</i> to
2077 * <code>builder</code>
2079 * @param dataNodeContainer
2080 * element which contains the list of used YANG groupings
2082 * builder to which are added implemented types according to
2083 * <code>dataNodeContainer</code>
2084 * @return generated type builder with all implemented types
2086 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2087 final GeneratedTypeBuilder builder) {
2088 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2089 if (usesNode.getGroupingPath() != null) {
2090 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2091 if (genType == null) {
2092 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2093 + builder.getName());
2096 builder.addImplementsType(genType);
2098 builder.addComment(genType.getDescription());
2099 builder.setDescription(genType.getDescription());
2100 builder.setModuleName(genType.getModuleName());
2101 builder.setReference(genType.getReference());
2102 builder.setSchemaPath(genType.getSchemaPath());
2109 private static boolean isNullOrEmpty(final Collection<?> list) {
2110 return list == null || list.isEmpty();
2113 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2114 final StringBuilder sb = new StringBuilder();
2116 if (!isNullOrEmpty(schemaNodes)) {
2117 final SchemaNode node = schemaNodes.iterator().next();
2119 if (node instanceof RpcDefinition) {
2120 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2121 } else if (node instanceof NotificationDefinition) {
2122 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2125 sb.append(NEW_LINE);
2127 if (verboseClassComments) {
2129 sb.append(NEW_LINE);
2130 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2131 sb.append("</pre>");
2132 sb.append(NEW_LINE);
2135 return replaceAllIllegalChars(sb);
2138 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2139 final StringBuilder sb = new StringBuilder();
2140 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2141 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2143 if (!Strings.isNullOrEmpty(formattedDescription)) {
2144 sb.append(formattedDescription);
2145 sb.append(NEW_LINE);
2148 if (verboseClassComments) {
2149 final Module module = findParentModule(schemaContext, schemaNode);
2150 final StringBuilder linkToBuilderClass = new StringBuilder();
2151 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2152 final String className = namespace[namespace.length - 1];
2154 if (hasBuilderClass(schemaNode)) {
2155 linkToBuilderClass.append(className);
2156 linkToBuilderClass.append("Builder");
2160 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2161 sb.append(module.getName());
2163 sb.append(NEW_LINE);
2165 sb.append(NEW_LINE);
2166 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2167 sb.append("</pre>");
2168 sb.append(NEW_LINE);
2169 sb.append("The schema path to identify an instance is");
2170 sb.append(NEW_LINE);
2172 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2174 sb.append(NEW_LINE);
2176 if (hasBuilderClass(schemaNode)) {
2177 sb.append(NEW_LINE);
2178 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2179 sb.append(NEW_LINE);
2181 sb.append(linkToBuilderClass);
2182 sb.append(NEW_LINE);
2183 if (schemaNode instanceof ListSchemaNode) {
2184 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2185 if (keyDef != null && !keyDef.isEmpty()) {
2187 sb.append(className);
2190 sb.append(NEW_LINE);
2195 return replaceAllIllegalChars(sb);
2198 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2199 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2200 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2206 private String createDescription(final Module module) {
2207 final StringBuilder sb = new StringBuilder();
2208 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2209 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2211 if (!Strings.isNullOrEmpty(formattedDescription)) {
2212 sb.append(formattedDescription);
2213 sb.append(NEW_LINE);
2216 if (verboseClassComments) {
2218 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2219 sb.append(module.getName());
2221 sb.append(NEW_LINE);
2223 sb.append(NEW_LINE);
2224 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2225 sb.append("</pre>");
2228 return replaceAllIllegalChars(sb);
2231 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2232 for (final ModuleContext ctx : genCtx.values()) {
2233 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2234 if (result != null) {
2241 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2242 for (final ModuleContext ctx : genCtx.values()) {
2243 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2244 if (result != null) {
2251 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2252 for (final ModuleContext ctx : genCtx.values()) {
2253 final GeneratedTypeBuilder result = ctx.getCase(path);
2254 if (result != null) {
2261 public Map<Module, ModuleContext> getModuleContexts() {
2266 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2267 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2268 return ret.isEmpty() ? "" : ret;
2271 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2272 if (status == Status.DEPRECATED) {
2273 builder.addAnnotation("", "Deprecated");