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.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.regex.Pattern;
47 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
48 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
49 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
50 import org.opendaylight.yangtools.binding.generator.util.Types;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
53 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
54 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
55 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
56 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
57 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
61 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
62 import org.opendaylight.yangtools.sal.binding.model.api.Type;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
69 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
70 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
71 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
72 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
73 import org.opendaylight.yangtools.yang.binding.BindingMapping;
74 import org.opendaylight.yangtools.yang.binding.DataContainer;
75 import org.opendaylight.yangtools.yang.binding.RpcService;
76 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
106 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
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.UnionType;
110 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
111 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
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 * Constant with the concrete name of identifier.
125 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
128 * Constant with the concrete name of namespace.
130 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
132 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
134 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
137 * When set to true, generated classes will include javadoc comments which
138 * are useful for users.
140 private final boolean verboseClassComments;
143 * Outer key represents the package name. Outer value represents map of all
144 * builders in the same package. Inner key represents the schema node name
145 * (in JAVA class/interface name format). Inner value represents instance of
146 * builder for schema node specified in key part.
148 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
151 * Provide methods for converting YANG types to JAVA types.
153 private TypeProvider typeProvider;
156 * Holds reference to schema context to resolve data of augmented element
157 * when creating augmentation builder
159 private SchemaContext schemaContext;
162 * Create a new binding generator.
164 * @param verboseClassComments generate verbose comments
166 public BindingGeneratorImpl(final boolean verboseClassComments) {
167 this.verboseClassComments = verboseClassComments;
171 * Resolves generated types from <code>context</code> schema nodes of all
174 * Generated types are created for modules, groupings, types, containers,
175 * lists, choices, augments, rpcs, notification, identities.
178 * schema context which contains data about all schema nodes
180 * @return list of types (usually <code>GeneratedType</code>
181 * <code>GeneratedTransferObject</code>which are generated from
182 * <code>context</code> data.
183 * @throws IllegalArgumentException
184 * if arg <code>context</code> is null
185 * @throws IllegalStateException
186 * if <code>context</code> contain no modules
189 public List<Type> generateTypes(final SchemaContext context) {
190 checkArgument(context != null, "Schema Context reference cannot be NULL.");
191 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
192 schemaContext = context;
193 typeProvider = new TypeProviderImpl(context);
194 final Set<Module> modules = context.getModules();
195 return generateTypes(context, modules);
199 * Resolves generated types from <code>context</code> schema nodes only for
200 * modules specified in <code>modules</code>
202 * Generated types are created for modules, groupings, types, containers,
203 * lists, choices, augments, rpcs, notification, identities.
206 * schema context which contains data about all schema nodes
209 * set of modules for which schema nodes should be generated
211 * @return list of types (usually <code>GeneratedType</code> or
212 * <code>GeneratedTransferObject</code>) which:
214 * <li>are generated from <code>context</code> schema nodes and</li>
215 * <li>are also part of some of the module in <code>modules</code>
218 * @throws IllegalArgumentException
220 * <li>if arg <code>context</code> is null or</li>
221 * <li>if arg <code>modules</code> is null</li>
223 * @throws IllegalStateException
224 * if <code>context</code> contain no modules
227 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
228 checkArgument(context != null, "Schema Context reference cannot be NULL.");
229 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
230 checkArgument(modules != null, "Set of Modules cannot be NULL.");
232 schemaContext = context;
233 typeProvider = new TypeProviderImpl(context);
234 final Module[] modulesArray = new Module[context.getModules().size()];
235 context.getModules().toArray(modulesArray);
236 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
237 genTypeBuilders = new HashMap<>();
239 for (final Module contextModule : contextModules) {
240 moduleToGenTypes(contextModule, context);
242 for (final Module contextModule : contextModules) {
243 allAugmentsToGenTypes(contextModule);
246 final List<Type> filteredGenTypes = new ArrayList<>();
247 for (final Module m : modules) {
248 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
249 filteredGenTypes.addAll(ctx.getGeneratedTypes());
250 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
251 if (additionalTypes != null) {
252 filteredGenTypes.addAll(additionalTypes);
256 return filteredGenTypes;
259 private void moduleToGenTypes(final Module m, final SchemaContext context) {
260 genCtx.put(m, new ModuleContext());
261 allTypeDefinitionsToGenTypes(m);
262 groupingsToGenTypes(m, m.getGroupings());
263 rpcMethodsToGenType(m);
264 allIdentitiesToGenTypes(m, context);
265 notificationsToGenType(m);
267 if (!m.getChildNodes().isEmpty()) {
268 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
269 genCtx.get(m).addModuleNode(moduleType);
270 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
271 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
276 * Converts all extended type definitions of module to the list of
277 * <code>Type</code> objects.
280 * module from which is obtained set of type definitions
281 * @throws IllegalArgumentException
283 * <li>if module is null</li>
284 * <li>if name of module is null</li>
286 * @throws IllegalStateException
287 * if set of type definitions from module is null
289 private void allTypeDefinitionsToGenTypes(final Module module) {
290 checkArgument(module != null, "Module reference cannot be NULL.");
291 checkArgument(module.getName() != null, "Module name cannot be NULL.");
292 final DataNodeIterator it = new DataNodeIterator(module);
293 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
294 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
296 for (final TypeDefinition<?> typedef : typeDefinitions) {
297 if (typedef != null) {
298 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
301 final ModuleContext ctx = genCtx.get(module);
302 ctx.addTypedefType(typedef.getPath(), type);
303 ctx.addTypeToSchema(type,typedef);
309 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
310 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
311 if (node.isAugmenting() || node.isAddedByUses()) {
314 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
315 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
316 genType.addComment(node.getDescription());
317 annotateDeprecatedIfNecessary(node.getStatus(), genType);
318 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
319 genType.setModuleName(module.getName());
320 genType.setReference(node.getReference());
321 genType.setSchemaPath(node.getPath().getPathFromRoot());
322 if (node instanceof DataNodeContainer) {
323 genCtx.get(module).addChildNodeType(node, genType);
324 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
325 processUsesAugments((DataNodeContainer) node, module);
330 private void containerToGenType(final Module module, final String basePackageName,
331 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
332 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
333 if (genType != null) {
334 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
335 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
339 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
340 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
341 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
342 if (genType != null) {
343 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
344 Types.listTypeFor(genType), node.getStatus());
346 final List<String> listKeys = listKeys(node);
347 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
348 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
349 if (genTOBuilder != null) {
350 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
351 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
352 genTOBuilder.addImplementsType(identifierMarker);
353 genType.addImplementsType(identifiableMarker);
356 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
357 if (!schemaNode.isAugmenting()) {
358 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
363 if (genTOBuilder != null) {
364 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
365 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
366 genTOBuilder.setSUID(prop);
369 typeBuildersToGenTypes(module, genType, genTOBuilder);
373 private void processUsesAugments(final DataNodeContainer node, final Module module) {
374 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
375 for (final UsesNode usesNode : node.getUses()) {
376 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
377 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
378 processUsesAugments(augment, module);
384 * Converts all <b>augmentation</b> of the module to the list
385 * <code>Type</code> objects.
388 * module from which is obtained list of all augmentation objects
389 * to iterate over them
390 * @throws IllegalArgumentException
392 * <li>if the module is null</li>
393 * <li>if the name of module is null</li>
395 * @throws IllegalStateException
396 * if set of augmentations from module is null
398 private void allAugmentsToGenTypes(final Module module) {
399 checkArgument(module != null, "Module reference cannot be NULL.");
400 checkArgument(module.getName() != null, "Module name cannot be NULL.");
401 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
403 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
404 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
405 for (final AugmentationSchema augment : augmentations) {
406 augmentationToGenTypes(basePackageName, augment, module);
411 * Returns list of <code>AugmentationSchema</code> objects. The objects are
412 * sorted according to the length of their target path from the shortest to
416 * module from which is obtained list of all augmentation objects
417 * @return list of sorted <code>AugmentationSchema</code> objects obtained
418 * from <code>module</code>
419 * @throws IllegalArgumentException
421 * @throws IllegalStateException
422 * if set of module augmentations is null
424 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
425 checkArgument(module != null, "Module reference cannot be NULL.");
426 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
428 final Set<AugmentationSchema> augmentations = module.getAugmentations();
429 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
430 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
432 return sortedAugmentations;
436 * Create GeneratedTypeBuilder object from module argument.
439 * Module object from which builder will be created
440 * @return <code>GeneratedTypeBuilder</code> which is internal
441 * representation of the module
442 * @throws IllegalArgumentException
445 private GeneratedTypeBuilder moduleToDataType(final Module module) {
446 checkArgument(module != null, "Module reference cannot be NULL.");
448 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
449 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
450 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
451 moduleDataTypeBuilder.addComment(module.getDescription());
452 moduleDataTypeBuilder.setDescription(createDescription(module));
453 moduleDataTypeBuilder.setReference(module.getReference());
454 return moduleDataTypeBuilder;
458 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
459 * to the list of <code>Type</code> objects. In addition are to containers
460 * and lists which belong to input or output also part of returning list.
463 * module from which is obtained set of all rpc objects to
465 * @throws IllegalArgumentException
467 * <li>if the module is null</li>
468 * <li>if the name of module is null</li>
470 * @throws IllegalStateException
471 * if set of rpcs from module is null
473 private void rpcMethodsToGenType(final Module module) {
474 checkArgument(module != null, "Module reference cannot be NULL.");
475 checkArgument(module.getName() != null, "Module name cannot be NULL.");
476 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
477 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
478 if (rpcDefinitions.isEmpty()) {
482 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
483 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
484 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
485 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
487 for (final RpcDefinition rpc : rpcDefinitions) {
489 final String rpcName = BindingMapping.getClassName(rpc.getQName());
490 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
491 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
492 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
493 final ContainerSchemaNode input = rpc.getInput();
494 final ContainerSchemaNode output = rpc.getOutput();
497 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
498 addImplementedInterfaceFromUses(input, inType);
499 inType.addImplementsType(DATA_OBJECT);
500 inType.addImplementsType(augmentable(inType));
501 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
502 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
503 genCtx.get(module).addChildNodeType(input, inType);
504 final GeneratedType inTypeInstance = inType.toInstance();
505 method.addParameter(inTypeInstance, "input");
508 Type outTypeInstance = VOID;
509 if (output != null) {
510 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
511 addImplementedInterfaceFromUses(output, outType);
512 outType.addImplementsType(DATA_OBJECT);
513 outType.addImplementsType(augmentable(outType));
514 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
515 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
516 genCtx.get(module).addChildNodeType(output, outType);
517 outTypeInstance = outType.toInstance();
520 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
521 method.setComment(rpcComment);
522 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
526 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
530 * Converts all <b>notifications</b> of the module to the list of
531 * <code>Type</code> objects. In addition are to this list added containers
532 * and lists which are part of this notification.
535 * module from which is obtained set of all notification objects
536 * to iterate over them
537 * @throws IllegalArgumentException
539 * <li>if the module equals null</li>
540 * <li>if the name of module equals null</li>
542 * @throws IllegalStateException
543 * if set of notifications from module is null
545 private void notificationsToGenType(final Module module) {
546 checkArgument(module != null, "Module reference cannot be NULL.");
547 checkArgument(module.getName() != null, "Module name cannot be NULL.");
548 final Set<NotificationDefinition> notifications = module.getNotifications();
549 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
550 if (notifications.isEmpty()) {
554 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
555 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
556 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
560 for (final NotificationDefinition notification : notifications) {
561 if (notification != null) {
562 processUsesAugments(notification, module);
564 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
565 notification, null, module);
566 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
567 notificationInterface.addImplementsType(NOTIFICATION);
568 genCtx.get(module).addChildNodeType(notification, notificationInterface);
570 // Notification object
571 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
572 notification.getChildNodes());
574 listenerInterface.addMethod("on" + notificationInterface.getName())
575 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
576 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
579 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
581 genCtx.get(module).addTopLevelNodeType(listenerInterface);
585 * Converts all <b>identities</b> of the module to the list of
586 * <code>Type</code> objects.
589 * module from which is obtained set of all identity objects to
592 * schema context only used as input parameter for method
593 * {@link identityToGenType}
596 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
597 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
598 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
600 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
601 for (final IdentitySchemaNode identity : schemaIdentities) {
602 identityToGenType(module, basePackageName, identity, context);
608 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
609 * created transport object builder. If identity contains base identity then
610 * reference to base identity is added to superior identity as its extend.
611 * If identity doesn't contain base identity then only reference to abstract
612 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
613 * BaseIdentity} is added
617 * @param basePackageName
618 * string contains the module package name
620 * IdentitySchemaNode which contains data about identity
622 * SchemaContext which is used to get package and name
623 * information about base of identity
626 private void identityToGenType(final Module module, final String basePackageName,
627 final IdentitySchemaNode identity, final SchemaContext context) {
628 if (identity == null) {
631 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
632 final String genTypeName = BindingMapping.getClassName(identity.getQName());
633 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
634 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
635 if (baseIdentity == null) {
636 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
637 BaseIdentity.class.getSimpleName());
638 newType.setExtendsType(gto.toInstance());
640 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
641 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
643 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
644 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
646 newType.setExtendsType(gto);
648 newType.setAbstract(true);
649 newType.addComment(identity.getDescription());
650 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
651 newType.setReference(identity.getReference());
652 newType.setModuleName(module.getName());
653 newType.setSchemaPath(identity.getPath().getPathFromRoot());
655 final QName qname = identity.getQName();
656 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
658 genCtx.get(module).addIdentityType(identity.getQName(), newType);
661 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
663 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
667 * Converts all <b>groupings</b> of the module to the list of
668 * <code>Type</code> objects. Firstly are groupings sorted according mutual
669 * dependencies. At least dependent (independent) groupings are in the list
670 * saved at first positions. For every grouping the record is added to map
671 * {@link BindingGeneratorImpl#allGroupings allGroupings}
676 * of groupings from which types will be generated
679 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
680 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
681 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
683 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
684 groupingToGenType(basePackageName, grouping, module);
689 * Converts individual grouping to GeneratedType. Firstly generated type
690 * builder is created and every child node of grouping is resolved to the
693 * @param basePackageName
694 * string contains the module package name
696 * GroupingDefinition which contains data about grouping
699 * @return GeneratedType which is generated from grouping (object of type
700 * <code>GroupingDefinition</code>)
702 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
703 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
704 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
705 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
706 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
707 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
708 groupingsToGenTypes(module, grouping.getGroupings());
709 processUsesAugments(grouping, module);
713 * Adds enumeration builder created from <code>enumTypeDef</code> to
714 * <code>typeBuilder</code>.
716 * Each <code>enumTypeDef</code> item is added to builder with its name and
720 * EnumTypeDefinition contains enum data
722 * string contains name which will be assigned to enumeration
725 * GeneratedTypeBuilder to which will be enum builder assigned
727 * Module in which type should be generated
728 * @return enumeration builder which contains data from
729 * <code>enumTypeDef</code>
731 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
732 final GeneratedTypeBuilder typeBuilder, final Module module) {
733 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
734 && (enumTypeDef.getQName().getLocalName() != null)) {
735 final String enumerationName = BindingMapping.getClassName(enumName);
736 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
737 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
738 enumBuilder.setDescription(enumTypedefDescription);
739 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
740 ModuleContext ctx = genCtx.get(module);
741 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
748 * Generates type builder for <code>module</code>.
751 * Module which is source of package name for generated type
754 * string which is added to the module class name representation
756 * @return instance of GeneratedTypeBuilder which represents
757 * <code>module</code>.
758 * @throws IllegalArgumentException
759 * if <code>module</code> is null
761 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
762 checkArgument(module != null, "Module reference cannot be NULL.");
763 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
764 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
766 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
767 moduleBuilder.setDescription(createDescription(module));
768 moduleBuilder.setReference(module.getReference());
769 moduleBuilder.setModuleName(moduleName);
771 return moduleBuilder;
775 * Converts <code>augSchema</code> to list of <code>Type</code> which
776 * contains generated type for augmentation. In addition there are also
777 * generated types for all containers, list and choices which are child of
778 * <code>augSchema</code> node or a generated types for cases are added if
779 * augmented node is choice.
781 * @param augmentPackageName
782 * string with the name of the package to which the augmentation
785 * AugmentationSchema which is contains data about augmentation
786 * (target path, childs...)
789 * @param parentUsesNode
790 * @throws IllegalArgumentException
792 * <li>if <code>augmentPackageName</code> equals null</li>
793 * <li>if <code>augSchema</code> equals null</li>
795 * @throws IllegalStateException
796 * if augment target path is null
798 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
799 final Module module) {
800 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
801 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
802 checkState(augSchema.getTargetPath() != null,
803 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
805 processUsesAugments(augSchema, module);
806 final SchemaPath targetPath = augSchema.getTargetPath();
807 SchemaNode targetSchemaNode = null;
809 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
810 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
811 if (targetSchemaNode instanceof DerivableSchemaNode) {
812 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
814 if (targetSchemaNode == null) {
815 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
816 + " in module " + module.getName());
819 if (targetSchemaNode == null) {
820 throw new IllegalArgumentException("augment target not found: " + targetPath);
823 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
824 if (targetTypeBuilder == null) {
825 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
827 if (targetTypeBuilder == null) {
828 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
831 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
832 final String packageName = augmentPackageName;
833 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
834 targetTypeBuilder.getName());
835 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
838 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
839 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
843 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
844 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
845 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
846 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
847 checkState(augSchema.getTargetPath() != null,
848 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
850 processUsesAugments(augSchema, module);
851 final SchemaPath targetPath = augSchema.getTargetPath();
852 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
853 if (targetSchemaNode == null) {
854 throw new IllegalArgumentException("augment target not found: " + targetPath);
857 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
858 if (targetTypeBuilder == null) {
859 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
861 if (targetTypeBuilder == null) {
862 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
865 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
866 String packageName = augmentPackageName;
867 if (usesNodeParent instanceof SchemaNode) {
868 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
870 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
873 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
874 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
879 * Convenient method to find node added by uses statement.
883 * @param parentUsesNode
884 * parent of uses node
885 * @return node from its original location in grouping
887 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
888 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
890 if (!(targetGrouping instanceof GroupingDefinition)) {
891 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
894 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
895 SchemaNode result = grouping;
896 for (final QName node : targetPath.getPathFromRoot()) {
897 // finding by local name is valid, grouping cannot contain nodes
898 // with same name and different namespace
899 if (result instanceof DataNodeContainer) {
900 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
901 } else if (result instanceof ChoiceSchemaNode) {
902 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
905 if (result == null) {
909 if (result instanceof DerivableSchemaNode) {
910 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
911 Optional<? extends SchemaNode> originalNode = castedResult
913 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
914 result = originalNode.get();
918 if (result instanceof DataSchemaNode) {
919 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
920 if (resultDataSchemaNode.isAddedByUses()) {
921 // The original node is required, but we have only the copy of
922 // the original node.
923 // Maybe this indicates a bug in Yang parser.
924 throw new IllegalStateException(
925 "Failed to generate code for augment in "
928 return resultDataSchemaNode;
931 throw new IllegalStateException(
932 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
938 * Returns a generated type builder for an augmentation.
940 * The name of the type builder is equal to the name of augmented node with
941 * serial number as suffix.
945 * @param augmentPackageName
946 * string with contains the package name to which the augment
948 * @param basePackageName
949 * string with the package name to which the augmented node
951 * @param targetTypeRef
954 * augmentation schema which contains data about the child nodes
955 * and uses of augment
956 * @return generated type builder for augment
958 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
959 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
960 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
961 if (augmentBuilders == null) {
962 augmentBuilders = new HashMap<>();
963 genTypeBuilders.put(augmentPackageName, augmentBuilders);
965 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
968 if (augIdentifier != null) {
969 augTypeName = BindingMapping.getClassName(augIdentifier);
971 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
974 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
976 augTypeBuilder.addImplementsType(DATA_OBJECT);
977 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
978 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
979 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
981 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
982 augmentBuilders.put(augTypeName, augTypeBuilder);
984 if(!augSchema.getChildNodes().isEmpty()) {
985 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
986 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
989 genCtx.get(module).addAugmentType(augTypeBuilder);
990 return augTypeBuilder;
995 * @param unknownSchemaNodes
996 * @return nodeParameter of UnknownSchemaNode
998 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
999 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1000 final QName nodeType = unknownSchemaNode.getNodeType();
1001 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1002 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1003 return unknownSchemaNode.getNodeParameter();
1010 * Returns first unique name for the augment generated type builder. The
1011 * generated type builder name for augment consists from name of augmented
1012 * node and serial number of its augmentation.
1015 * map of builders which were created in the package to which the
1016 * augmentation belongs
1017 * @param genTypeName
1018 * string with name of augmented node
1019 * @return string with unique name for augmentation builder
1021 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1023 if (builders != null) {
1024 while (builders.containsKey(genTypeName + index)) {
1028 return genTypeName + index;
1032 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1033 * node for which <code>typeBuilder</code> was created.
1035 * The subnodes aren't mapped to the methods if they are part of grouping or
1036 * augment (in this case are already part of them).
1040 * @param basePackageName
1041 * string contains the module package name
1043 * generated type builder which represents any node. The subnodes
1044 * of this node are added to the <code>typeBuilder</code> as
1045 * methods. The subnode can be of type leaf, leaf-list, list,
1046 * container, choice.
1049 * @param schemaNodes
1050 * set of data schema nodes which are the children of the node
1051 * for which <code>typeBuilder</code> was created
1052 * @return generated type builder which is the same builder as input
1053 * parameter. The getter methods (representing child nodes) could be
1056 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1057 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1058 if (schemaNodes != null && parent != null) {
1059 for (final DataSchemaNode schemaNode : schemaNodes) {
1060 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1061 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1069 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1070 * node for which <code>typeBuilder</code> was created.
1074 * @param basePackageName
1075 * string contains the module package name
1076 * @param typeBuilder
1077 * generated type builder which represents any node. The subnodes
1078 * of this node are added to the <code>typeBuilder</code> as
1079 * methods. The subnode can be of type leaf, leaf-list, list,
1080 * container, choice.
1083 * @param schemaNodes
1084 * set of data schema nodes which are the children of the node
1085 * for which <code>typeBuilder</code> was created
1086 * @return generated type builder which is the same object as the input
1087 * parameter <code>typeBuilder</code>. The getter method could be
1090 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1091 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1092 final Iterable<DataSchemaNode> schemaNodes) {
1093 if ((schemaNodes != null) && (typeBuilder != null)) {
1094 for (final DataSchemaNode schemaNode : schemaNodes) {
1095 if (!schemaNode.isAugmenting()) {
1096 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1104 * Adds to <code>typeBuilder</code> a method which is derived from
1105 * <code>schemaNode</code>.
1107 * @param basePackageName
1108 * string with the module package name
1110 * data schema node which is added to <code>typeBuilder</code> as
1112 * @param typeBuilder
1113 * generated type builder to which is <code>schemaNode</code>
1114 * added as a method.
1120 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1121 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1122 if (node != null && typeBuilder != null) {
1123 if (node instanceof LeafSchemaNode) {
1124 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1125 } else if (node instanceof LeafListSchemaNode) {
1126 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1127 } else if (node instanceof ContainerSchemaNode) {
1128 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1129 } else if (node instanceof ListSchemaNode) {
1130 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1131 } else if (node instanceof ChoiceSchemaNode) {
1132 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1134 // TODO: anyxml not yet supported
1135 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1136 typeBuilder.getFullyQualifiedName());
1142 * Converts <code>choiceNode</code> to the list of generated types for
1143 * choice and its cases.
1145 * The package names for choice and for its cases are created as
1146 * concatenation of the module package (<code>basePackageName</code>) and
1147 * names of all parents node.
1151 * @param basePackageName
1152 * string with the module package name
1156 * choice node which is mapped to generated type. Also child
1157 * nodes - cases are mapped to generated types.
1158 * @throws IllegalArgumentException
1160 * <li>if <code>basePackageName</code> is null</li>
1161 * <li>if <code>choiceNode</code> is null</li>
1164 private void choiceToGeneratedType(final Module module, final String basePackageName,
1165 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1166 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1167 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1169 if (!choiceNode.isAddedByUses()) {
1170 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1171 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1172 constructGetter(parent, choiceNode.getQName().getLocalName(),
1173 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1174 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1175 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1176 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1177 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1182 * Converts <code>caseNodes</code> set to list of corresponding generated
1185 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1186 * created generated type builder. The package names for the builder is
1187 * created as concatenation of the module package (
1188 * <code>basePackageName</code>) and names of all parents nodes of the
1189 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1190 * between every case builder and <i>choice</i> type
1194 * @param basePackageName
1195 * string with the module package name
1196 * @param refChoiceType
1197 * type which represents superior <i>case</i>
1199 * choice case node which is mapped to generated type
1200 * @return list of generated types for <code>caseNodes</code>.
1201 * @throws IllegalArgumentException
1203 * <li>if <code>basePackageName</code> equals null</li>
1204 * <li>if <code>refChoiceType</code> equals null</li>
1205 * <li>if <code>caseNodes</code> equals null</li>
1208 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1209 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1210 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1211 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1212 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1214 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1215 if (caseNodes == null) {
1219 for (final ChoiceCaseNode caseNode : caseNodes) {
1220 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1221 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1222 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1223 caseTypeBuilder.addImplementsType(refChoiceType);
1224 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1225 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1226 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1227 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1228 if (caseChildNodes != null) {
1229 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1231 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1232 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1234 if (parent instanceof AugmentationSchema) {
1235 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1236 final SchemaPath targetPath = augSchema.getTargetPath();
1237 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1238 if (targetSchemaNode instanceof DataSchemaNode
1239 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1240 if (targetSchemaNode instanceof DerivableSchemaNode) {
1241 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1243 if (targetSchemaNode == null) {
1244 throw new IllegalStateException(
1245 "Failed to find target node from grouping for augmentation " + augSchema
1246 + " in module " + module.getName());
1249 parent = targetSchemaNode;
1252 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1253 choiceNodeParentPath);
1254 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1255 if (childOfType == null) {
1256 childOfType = findGroupingByPath(parent.getPath());
1258 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1260 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1265 processUsesAugments(caseNode, module);
1270 * Generates list of generated types for all the cases of a choice which are
1271 * added to the choice through the augment.
1275 * @param basePackageName
1276 * string contains name of package to which augment belongs. If
1277 * an augmented choice is from an other package (pcg1) than an
1278 * augmenting choice (pcg2) then case's of the augmenting choice
1279 * will belong to pcg2.
1281 * Type which represents target choice
1283 * node which represents target choice
1284 * @param augmentedNodes
1285 * set of choice case nodes for which is checked if are/aren't
1286 * added to choice through augmentation
1287 * @return list of generated types which represents augmented cases of
1288 * choice <code>refChoiceType</code>
1289 * @throws IllegalArgumentException
1291 * <li>if <code>basePackageName</code> is null</li>
1292 * <li>if <code>targetType</code> is null</li>
1293 * <li>if <code>augmentedNodes</code> is null</li>
1296 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1297 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1298 final DataNodeContainer usesNodeParent) {
1299 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1300 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1301 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1303 for (final DataSchemaNode caseNode : augmentedNodes) {
1304 if (caseNode != null) {
1305 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1306 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1307 caseTypeBuilder.addImplementsType(targetType);
1309 SchemaNode parent = null;
1310 final SchemaPath nodeSp = targetNode.getPath();
1311 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1313 GeneratedTypeBuilder childOfType = null;
1314 if (parent instanceof Module) {
1315 childOfType = genCtx.get(parent).getModuleNode();
1316 } else if (parent instanceof ChoiceCaseNode) {
1317 childOfType = findCaseByPath(parent.getPath());
1318 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1319 childOfType = findChildNodeByPath(parent.getPath());
1320 } else if (parent instanceof GroupingDefinition) {
1321 childOfType = findGroupingByPath(parent.getPath());
1324 if (childOfType == null) {
1325 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1328 ChoiceCaseNode node = null;
1329 final String caseLocalName = caseNode.getQName().getLocalName();
1330 if (caseNode instanceof ChoiceCaseNode) {
1331 node = (ChoiceCaseNode) caseNode;
1332 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1333 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1334 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1335 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1336 ().getLocalName())) {
1337 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1342 node = targetNode.getCaseNodeByName(caseLocalName);
1344 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1345 if (childNodes != null) {
1346 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1348 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1349 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1354 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1355 // Deal with old parser, clearing out references to typedefs
1356 if (type instanceof ExtendedType) {
1360 // New parser with encapsulated type
1361 if (leaf.getPath().equals(type.getPath())) {
1365 // Embedded type definition with new parser. Also takes care of the old parser with bits
1366 if (leaf.getPath().equals(type.getPath().getParent())) {
1370 // Old parser uses broken Union type, which does not change its schema path
1371 if (type instanceof UnionType) {
1379 * Converts <code>leaf</code> to the getter method which is added to
1380 * <code>typeBuilder</code>.
1382 * @param typeBuilder
1383 * generated type builder to which is added getter method as
1384 * <code>leaf</code> mapping
1386 * leaf schema node which is mapped as getter method which is
1387 * added to <code>typeBuilder</code>
1389 * Module in which type was defined
1390 * @return boolean value
1392 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1394 * <li>true - in other cases</li>
1397 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1398 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1402 final String leafName = leaf.getQName().getLocalName();
1403 if (leafName == null) {
1407 final Module parentModule = findParentModule(schemaContext, leaf);
1408 Type returnType = null;
1410 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1411 if (isInnerType(leaf, typeDef)) {
1412 if (typeDef instanceof EnumTypeDefinition) {
1413 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1414 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1415 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1416 typeBuilder, module);
1418 if (enumBuilder != null) {
1419 returnType = enumBuilder.toInstance(typeBuilder);
1421 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1422 } else if (typeDef instanceof UnionTypeDefinition) {
1423 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1424 if (genTOBuilder != null) {
1425 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1427 } else if (typeDef instanceof BitsTypeDefinition) {
1428 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1429 if (genTOBuilder != null) {
1430 returnType = genTOBuilder.toInstance();
1433 // It is constrained version of already declared type (inner declared type exists,
1434 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1435 // In order to get proper class we need to look up closest derived type
1436 // and apply restrictions from leaf type
1437 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1438 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1442 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1443 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1446 if (returnType == null) {
1450 String leafDesc = leaf.getDescription();
1451 if (leafDesc == null) {
1455 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1456 processContextRefExtension(leaf, getter, parentModule);
1460 private static TypeDefinition<?> getBaseOrDeclaredType(TypeDefinition<?> typeDef) {
1461 if (typeDef instanceof ExtendedType) {
1462 // Legacy behaviour returning ExtendedType is enough
1465 // Returns DerivedType in case of new parser.
1466 final TypeDefinition<?> baseType = typeDef.getBaseType();
1467 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1470 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1471 final Module module) {
1472 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1473 final QName nodeType = node.getNodeType();
1474 if ("context-reference".equals(nodeType.getLocalName())) {
1475 final String nodeParam = node.getNodeParameter();
1476 IdentitySchemaNode identity = null;
1477 String basePackageName = null;
1478 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1479 final Iterator<String> iterator = splittedElement.iterator();
1480 final int length = Iterables.size(splittedElement);
1482 identity = findIdentityByName(module.getIdentities(), iterator.next());
1483 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1484 } else if (length == 2) {
1485 final String prefix = iterator.next();
1486 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1487 if (dependentModule == null) {
1488 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1491 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1492 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1494 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1497 if (identity == null) {
1498 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1502 final Class<RoutingContext> clazz = RoutingContext.class;
1503 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1504 clazz.getSimpleName());
1505 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1506 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1507 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1512 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1513 for (final IdentitySchemaNode id : identities) {
1514 if (id.getQName().getLocalName().equals(name)) {
1521 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1522 for (final ModuleImport imp : imports) {
1523 if (imp.getPrefix().equals(prefix)) {
1524 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1530 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1531 final boolean isReadOnly, final Module module) {
1532 if ((leaf != null) && (toBuilder != null)) {
1533 String leafDesc = leaf.getDescription();
1534 if (leafDesc == null) {
1537 Type returnType = null;
1538 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1539 if (typeDef instanceof UnionTypeDefinition) {
1540 // GeneratedType for this type definition should be already
1542 final QName qname = typeDef.getQName();
1543 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1544 qname.getRevision());
1545 final ModuleContext mc = genCtx.get(unionModule);
1546 returnType = mc.getTypedefs().get(typeDef.getPath());
1547 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1548 // Annonymous enumeration (already generated, since it is inherited via uses).
1549 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1550 QName qname = originalLeaf.getQName();
1551 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1552 qname.getRevision());
1553 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1555 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1557 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1563 * Converts <code>leaf</code> schema node to property of generated TO
1567 * generated TO builder to which is <code>leaf</code> added as
1570 * leaf schema node which is added to <code>toBuilder</code> as
1575 * boolean value which says if leaf property is|isn't read only
1576 * @return boolean value
1578 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1579 * name equals null or if leaf is added by <i>uses</i>.</li>
1580 * <li>true - other cases</li>
1583 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1584 final Type returnType, final boolean isReadOnly) {
1585 if (returnType == null) {
1588 final String leafName = leaf.getQName().getLocalName();
1589 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1590 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1591 propBuilder.setReadOnly(isReadOnly);
1592 propBuilder.setReturnType(returnType);
1593 propBuilder.setComment(leafDesc);
1594 toBuilder.addEqualsIdentity(propBuilder);
1595 toBuilder.addHashIdentity(propBuilder);
1596 toBuilder.addToStringProperty(propBuilder);
1601 * Converts <code>node</code> leaf list schema node to getter method of
1602 * <code>typeBuilder</code>.
1604 * @param typeBuilder
1605 * generated type builder to which is <code>node</code> added as
1608 * leaf list schema node which is added to
1609 * <code>typeBuilder</code> as getter method
1611 * @return boolean value
1613 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1614 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1615 * <li>false - other cases</li>
1618 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1619 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1623 final QName nodeName = node.getQName();
1624 if (nodeName == null) {
1628 final TypeDefinition<?> typeDef = node.getType();
1629 final Module parentModule = findParentModule(schemaContext, node);
1631 Type returnType = null;
1632 if (typeDef.getBaseType() == null) {
1633 if (typeDef instanceof EnumTypeDefinition) {
1634 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1635 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1636 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1637 typeBuilder,module);
1638 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1639 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1640 } else if (typeDef instanceof UnionTypeDefinition) {
1641 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1642 if (genTOBuilder != null) {
1643 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1645 } else if (typeDef instanceof BitsTypeDefinition) {
1646 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1647 returnType = genTOBuilder.toInstance();
1649 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1650 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1653 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1654 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1657 final ParameterizedType listType = Types.listTypeFor(returnType);
1658 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1662 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1663 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1664 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1665 genTOBuilder.getName());
1666 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1668 returnType.setDescription(typedefDescription);
1669 returnType.setReference(typeDef.getReference());
1670 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1671 returnType.setModuleName(parentModule.getName());
1673 genTOBuilder.setTypedef(true);
1674 genTOBuilder.setIsUnion(true);
1675 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1679 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1682 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1683 method.setReturnType(returnType);
1684 method.addParameter(Types.STRING, "defaultValue");
1685 method.setAccessModifier(AccessModifier.PUBLIC);
1686 method.setStatic(true);
1688 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1689 if (types == null) {
1690 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1691 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1693 types.add(unionBuilder.toInstance());
1695 return returnType.toInstance();
1698 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1699 final String outerCls = Types.getOuterClassName(genTOBuilder);
1700 final StringBuilder name;
1701 if (outerCls != null) {
1702 name = new StringBuilder(outerCls);
1704 name = new StringBuilder();
1706 name.append(genTOBuilder.getName());
1707 name.append("Builder");
1708 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1709 unionBuilder.setIsUnionBuilder(true);
1710 return unionBuilder;
1713 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1714 final Module module) {
1715 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1719 * Instantiates generated type builder with <code>packageName</code> and
1720 * <code>schemaNode</code>.
1722 * The new builder always implements
1723 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1724 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1725 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1727 * If <code>schemaNode</code> is instance of
1728 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1729 * DataNodeContainer} it can also implement nodes which are specified in
1732 * @param packageName
1733 * string with the name of the package to which
1734 * <code>schemaNode</code> belongs.
1736 * schema node for which is created generated type builder
1738 * parent type (can be null)
1739 * @return generated type builder <code>schemaNode</code>
1741 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1742 final Type parent, final Module module) {
1743 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1744 if (parent == null) {
1745 it.addImplementsType(DATA_OBJECT);
1747 it.addImplementsType(BindingTypes.childOf(parent));
1749 if (!(schemaNode instanceof GroupingDefinition)) {
1750 it.addImplementsType(augmentable(it));
1753 if (schemaNode instanceof DataNodeContainer) {
1754 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1755 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1762 * Wraps the calling of the same overloaded method.
1764 * @param packageName
1765 * string with the package name to which returning generated type
1768 * schema node which provide data about the schema node name
1769 * @return generated type builder for <code>schemaNode</code>
1771 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1772 return addRawInterfaceDefinition(packageName, schemaNode, "");
1776 * Returns reference to generated type builder for specified
1777 * <code>schemaNode</code> with <code>packageName</code>.
1779 * Firstly the generated type builder is searched in
1780 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1781 * found it is created and added to <code>genTypeBuilders</code>.
1783 * @param packageName
1784 * string with the package name to which returning generated type
1787 * schema node which provide data about the schema node name
1789 * return type name prefix
1790 * @return generated type builder for <code>schemaNode</code>
1791 * @throws IllegalArgumentException
1793 * <li>if <code>schemaNode</code> is null</li>
1794 * <li>if <code>packageName</code> is null</li>
1795 * <li>if QName of schema node is null</li>
1796 * <li>if schemaNode name is null</li>
1800 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1801 final String prefix) {
1802 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1803 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1804 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1805 final String schemaNodeName = schemaNode.getQName().getLocalName();
1806 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1809 if (prefix == null) {
1810 genTypeName = BindingMapping.getClassName(schemaNodeName);
1812 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1815 // FIXME: Validation of name conflict
1816 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1817 final Module module = findParentModule(schemaContext, schemaNode);
1818 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1819 newType.addComment(schemaNode.getDescription());
1820 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1821 newType.setReference(schemaNode.getReference());
1822 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1823 newType.setModuleName(module.getName());
1825 if (!genTypeBuilders.containsKey(packageName)) {
1826 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1827 builders.put(genTypeName, newType);
1828 genTypeBuilders.put(packageName, builders);
1830 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1831 if (!builders.containsKey(genTypeName)) {
1832 builders.put(genTypeName, newType);
1839 * Creates the name of the getter method name from <code>localName</code>.
1842 * string with the name of the getter method
1845 * @return string with the name of the getter method for
1846 * <code>methodName</code> in JAVA method format
1848 public static String getterMethodName(final String localName, final Type returnType) {
1849 final StringBuilder method = new StringBuilder();
1850 if (BOOLEAN.equals(returnType)) {
1851 method.append("is");
1853 method.append("get");
1855 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1856 method.append(name);
1857 return method.toString();
1861 * Created a method signature builder as part of
1862 * <code>interfaceBuilder</code>.
1864 * The method signature builder is created for the getter method of
1865 * <code>schemaNodeName</code>. Also <code>comment</code> and
1866 * <code>returnType</code> information are added to the builder.
1868 * @param interfaceBuilder
1869 * generated type builder for which the getter method should be
1871 * @param schemaNodeName
1872 * string with schema node name. The name will be the part of the
1873 * getter method name.
1875 * string with comment for the getter method
1877 * type which represents the return type of the getter method
1879 * status from yang file, for deprecated annotation
1880 * @return method signature builder which represents the getter method of
1881 * <code>interfaceBuilder</code>
1883 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1884 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1885 final MethodSignatureBuilder getMethod = interfaceBuilder
1886 .addMethod(getterMethodName(schemaNodeName, returnType));
1887 if (status == Status.DEPRECATED) {
1888 getMethod.addAnnotation("", "Deprecated");
1890 getMethod.setComment(encodeAngleBrackets(comment));
1891 getMethod.setReturnType(returnType);
1896 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1897 * or to <code>genTOBuilder</code> as property.
1899 * @param basePackageName
1900 * string contains the module package name
1902 * data schema node which should be added as getter method to
1903 * <code>typeBuilder</code> or as a property to
1904 * <code>genTOBuilder</code> if is part of the list key
1905 * @param typeBuilder
1906 * generated type builder for the list schema node
1907 * @param genTOBuilder
1908 * generated TO builder for the list keys
1910 * list of string which contains names of the list keys
1913 * @throws IllegalArgumentException
1915 * <li>if <code>schemaNode</code> equals null</li>
1916 * <li>if <code>typeBuilder</code> equals null</li>
1919 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1920 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1921 final Module module) {
1922 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1923 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1925 if (schemaNode instanceof LeafSchemaNode) {
1926 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1927 final String leafName = leaf.getQName().getLocalName();
1928 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1929 if (listKeys.contains(leafName)) {
1931 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1933 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1936 } else if (!schemaNode.isAddedByUses()) {
1937 if (schemaNode instanceof LeafListSchemaNode) {
1938 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1939 } else if (schemaNode instanceof ContainerSchemaNode) {
1940 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1941 } else if (schemaNode instanceof ChoiceSchemaNode) {
1942 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1943 } else if (schemaNode instanceof ListSchemaNode) {
1944 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1949 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1950 final GeneratedTOBuilder genTOBuilder) {
1951 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1953 if (genTOBuilder != null) {
1954 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1955 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1956 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1961 * Selects the names of the list keys from <code>list</code> and returns
1962 * them as the list of the strings
1965 * of string with names of the list keys
1966 * @return list of string which represents names of the list keys. If the
1967 * <code>list</code> contains no keys then the empty list is
1970 private static List<String> listKeys(final ListSchemaNode list) {
1971 final List<String> listKeys = new ArrayList<>();
1973 final List<QName> keyDefinition = list.getKeyDefinition();
1974 if (keyDefinition != null) {
1975 for (final QName keyDef : keyDefinition) {
1976 listKeys.add(keyDef.getLocalName());
1983 * Generates for the <code>list</code> which contains any list keys special
1984 * generated TO builder.
1986 * @param packageName
1987 * string with package name to which the list belongs
1989 * list schema node which is source of data about the list name
1990 * @return generated TO builder which represents the keys of the
1991 * <code>list</code> or null if <code>list</code> is null or list of
1992 * key definitions is null or empty.
1994 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1995 GeneratedTOBuilder genTOBuilder = null;
1996 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1997 final String listName = list.getQName().getLocalName() + "Key";
1998 final String genTOName = BindingMapping.getClassName(listName);
1999 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2001 return genTOBuilder;
2005 * Builds generated TO builders for <code>typeDef</code> of type
2006 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
2007 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
2008 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
2009 * enclosing transfer object.
2011 * If more then one generated TO builder is created for enclosing then all
2012 * of the generated TO builders are added to <code>typeBuilder</code> as
2013 * enclosing transfer objects.
2016 * type definition which can be of type <code>UnionType</code> or
2017 * <code>BitsTypeDefinition</code>
2018 * @param typeBuilder
2019 * generated type builder to which is added generated TO created
2020 * from <code>typeDef</code>
2022 * string with name for generated TO builder
2024 * @return generated TO builder for <code>typeDef</code>
2026 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2027 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2028 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2029 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2030 final String packageName = typeBuilder.getFullyQualifiedName();
2031 if (typeDef instanceof UnionTypeDefinition) {
2032 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2033 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2034 classNameFromLeaf, leaf);
2035 genTOBuilders.addAll(types);
2037 GeneratedTOBuilder resultTOBuilder = null;
2038 if (types.isEmpty()) {
2039 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2041 resultTOBuilder = types.remove(0);
2042 for (final GeneratedTOBuilder genTOBuilder : types) {
2043 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2046 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2047 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2048 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2049 resultTOBuilder.addHashIdentity(genPropBuilder);
2050 resultTOBuilder.addToStringProperty(genPropBuilder);
2052 } else if (typeDef instanceof BitsTypeDefinition) {
2053 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2054 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2056 if (!genTOBuilders.isEmpty()) {
2057 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2058 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2060 return genTOBuilders.get(0);
2067 * Adds the implemented types to type builder.
2069 * The method passes through the list of <i>uses</i> in
2070 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2071 * generated type from {@link BindingGeneratorImpl#allGroupings
2072 * allGroupings} which is added as <i>implements type</i> to
2073 * <code>builder</code>
2075 * @param dataNodeContainer
2076 * element which contains the list of used YANG groupings
2078 * builder to which are added implemented types according to
2079 * <code>dataNodeContainer</code>
2080 * @return generated type builder with all implemented types
2082 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2083 final GeneratedTypeBuilder builder) {
2084 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2085 if (usesNode.getGroupingPath() != null) {
2086 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2087 if (genType == null) {
2088 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2089 + builder.getName());
2092 builder.addImplementsType(genType);
2094 builder.addComment(genType.getDescription());
2095 builder.setDescription(genType.getDescription());
2096 builder.setModuleName(genType.getModuleName());
2097 builder.setReference(genType.getReference());
2098 builder.setSchemaPath(genType.getSchemaPath());
2105 private static boolean isNullOrEmpty(final Collection<?> list) {
2106 return list == null || list.isEmpty();
2109 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2110 final StringBuilder sb = new StringBuilder();
2112 if (!isNullOrEmpty(schemaNodes)) {
2113 final SchemaNode node = schemaNodes.iterator().next();
2115 if (node instanceof RpcDefinition) {
2116 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2117 } else if (node instanceof NotificationDefinition) {
2118 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2121 sb.append(NEW_LINE);
2122 sb.append("<br>(Source path: <i>");
2123 sb.append(moduleSourcePath);
2124 sb.append("</i>):");
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 = YangTemplate.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);
2164 sb.append("<br>(Source path: <i>");
2165 sb.append(module.getModuleSourcePath());
2166 sb.append("</i>):");
2167 sb.append(NEW_LINE);
2169 sb.append(NEW_LINE);
2170 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2171 sb.append("</pre>");
2172 sb.append(NEW_LINE);
2173 sb.append("The schema path to identify an instance is");
2174 sb.append(NEW_LINE);
2176 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2178 sb.append(NEW_LINE);
2180 if (hasBuilderClass(schemaNode)) {
2181 sb.append(NEW_LINE);
2182 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2183 sb.append(NEW_LINE);
2185 sb.append(linkToBuilderClass);
2186 sb.append(NEW_LINE);
2187 if (schemaNode instanceof ListSchemaNode) {
2188 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2189 if (keyDef != null && !keyDef.isEmpty()) {
2191 sb.append(className);
2194 sb.append(NEW_LINE);
2199 return replaceAllIllegalChars(sb);
2202 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2203 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2204 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2210 private String createDescription(final Module module) {
2211 final StringBuilder sb = new StringBuilder();
2212 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2213 final String formattedDescription = YangTemplate.formatToParagraph(moduleDescription, 0);
2215 if (!Strings.isNullOrEmpty(formattedDescription)) {
2216 sb.append(formattedDescription);
2217 sb.append(NEW_LINE);
2220 if (verboseClassComments) {
2222 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2223 sb.append(module.getName());
2225 sb.append(NEW_LINE);
2226 sb.append("<br>Source path: <i>");
2227 sb.append(module.getModuleSourcePath());
2228 sb.append("</i>):");
2229 sb.append(NEW_LINE);
2231 sb.append(NEW_LINE);
2232 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2233 sb.append("</pre>");
2236 return replaceAllIllegalChars(sb);
2239 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2240 for (final ModuleContext ctx : genCtx.values()) {
2241 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2242 if (result != null) {
2249 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2250 for (final ModuleContext ctx : genCtx.values()) {
2251 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2252 if (result != null) {
2259 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2260 for (final ModuleContext ctx : genCtx.values()) {
2261 final GeneratedTypeBuilder result = ctx.getCase(path);
2262 if (result != null) {
2269 public Map<Module, ModuleContext> getModuleContexts() {
2274 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2275 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2276 return ret.isEmpty() ? "" : ret;
2279 private void annotateDeprecatedIfNecessary(Status status, GeneratedTypeBuilder builder) {
2280 if (status == Status.DEPRECATED) {
2281 builder.addAnnotation("", "Deprecated");