2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Splitter;
34 import com.google.common.base.Strings;
35 import com.google.common.collect.Iterables;
36 import com.google.common.collect.Sets;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
45 import java.util.regex.Pattern;
46 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
47 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
48 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
49 import org.opendaylight.yangtools.binding.generator.util.Types;
50 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
53 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
54 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
55 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
56 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
57 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
59 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
61 import org.opendaylight.yangtools.sal.binding.model.api.Type;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
69 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
70 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
71 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
72 import org.opendaylight.yangtools.yang.binding.BindingMapping;
73 import org.opendaylight.yangtools.yang.binding.DataContainer;
74 import org.opendaylight.yangtools.yang.binding.RpcService;
75 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
86 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
94 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
97 import org.opendaylight.yangtools.yang.model.api.Status;
98 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.UsesNode;
101 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
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);
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(), Types.listTypeFor(genType));
345 final List<String> listKeys = listKeys(node);
346 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
347 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
348 if (genTOBuilder != null) {
349 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
350 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
351 genTOBuilder.addImplementsType(identifierMarker);
352 genType.addImplementsType(identifiableMarker);
355 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
356 if (!schemaNode.isAugmenting()) {
357 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
362 if (genTOBuilder != null) {
363 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
364 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
365 genTOBuilder.setSUID(prop);
368 typeBuildersToGenTypes(module, genType, genTOBuilder);
372 private void processUsesAugments(final DataNodeContainer node, final Module module) {
373 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
374 for (final UsesNode usesNode : node.getUses()) {
375 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
376 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
377 processUsesAugments(augment, module);
383 * Converts all <b>augmentation</b> of the module to the list
384 * <code>Type</code> objects.
387 * module from which is obtained list of all augmentation objects
388 * to iterate over them
389 * @throws IllegalArgumentException
391 * <li>if the module is null</li>
392 * <li>if the name of module is null</li>
394 * @throws IllegalStateException
395 * if set of augmentations from module is null
397 private void allAugmentsToGenTypes(final Module module) {
398 checkArgument(module != null, "Module reference cannot be NULL.");
399 checkArgument(module.getName() != null, "Module name cannot be NULL.");
400 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
402 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
403 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
404 for (final AugmentationSchema augment : augmentations) {
405 augmentationToGenTypes(basePackageName, augment, module);
410 * Returns list of <code>AugmentationSchema</code> objects. The objects are
411 * sorted according to the length of their target path from the shortest to
415 * module from which is obtained list of all augmentation objects
416 * @return list of sorted <code>AugmentationSchema</code> objects obtained
417 * from <code>module</code>
418 * @throws IllegalArgumentException
420 * @throws IllegalStateException
421 * if set of module augmentations is null
423 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
424 checkArgument(module != null, "Module reference cannot be NULL.");
425 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
427 final Set<AugmentationSchema> augmentations = module.getAugmentations();
428 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
429 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
431 return sortedAugmentations;
435 * Create GeneratedTypeBuilder object from module argument.
438 * Module object from which builder will be created
439 * @return <code>GeneratedTypeBuilder</code> which is internal
440 * representation of the module
441 * @throws IllegalArgumentException
444 private GeneratedTypeBuilder moduleToDataType(final Module module) {
445 checkArgument(module != null, "Module reference cannot be NULL.");
447 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
448 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
449 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
450 moduleDataTypeBuilder.addComment(module.getDescription());
451 moduleDataTypeBuilder.setDescription(createDescription(module));
452 moduleDataTypeBuilder.setReference(module.getReference());
453 return moduleDataTypeBuilder;
457 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
458 * to the list of <code>Type</code> objects. In addition are to containers
459 * and lists which belong to input or output also part of returning list.
462 * module from which is obtained set of all rpc objects to
464 * @throws IllegalArgumentException
466 * <li>if the module is null</li>
467 * <li>if the name of module is null</li>
469 * @throws IllegalStateException
470 * if set of rpcs from module is null
472 private void rpcMethodsToGenType(final Module module) {
473 checkArgument(module != null, "Module reference cannot be NULL.");
474 checkArgument(module.getName() != null, "Module name cannot be NULL.");
475 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
476 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
477 if (rpcDefinitions.isEmpty()) {
481 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
482 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
483 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
484 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
486 for (final RpcDefinition rpc : rpcDefinitions) {
488 final String rpcName = BindingMapping.getClassName(rpc.getQName());
489 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
490 final String rpcComment = rpc.getDescription();
491 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
492 final ContainerSchemaNode input = rpc.getInput();
493 final ContainerSchemaNode output = rpc.getOutput();
496 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
497 addImplementedInterfaceFromUses(input, inType);
498 inType.addImplementsType(DATA_OBJECT);
499 inType.addImplementsType(augmentable(inType));
500 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
501 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
502 genCtx.get(module).addChildNodeType(input, inType);
503 final GeneratedType inTypeInstance = inType.toInstance();
504 method.addParameter(inTypeInstance, "input");
507 Type outTypeInstance = VOID;
508 if (output != null) {
509 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
510 addImplementedInterfaceFromUses(output, outType);
511 outType.addImplementsType(DATA_OBJECT);
512 outType.addImplementsType(augmentable(outType));
513 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
514 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
515 genCtx.get(module).addChildNodeType(output, outType);
516 outTypeInstance = outType.toInstance();
519 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
520 method.setComment(rpcComment);
521 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
525 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
529 * Converts all <b>notifications</b> of the module to the list of
530 * <code>Type</code> objects. In addition are to this list added containers
531 * and lists which are part of this notification.
534 * module from which is obtained set of all notification objects
535 * to iterate over them
536 * @throws IllegalArgumentException
538 * <li>if the module equals null</li>
539 * <li>if the name of module equals null</li>
541 * @throws IllegalStateException
542 * if set of notifications from module is null
544 private void notificationsToGenType(final Module module) {
545 checkArgument(module != null, "Module reference cannot be NULL.");
546 checkArgument(module.getName() != null, "Module name cannot be NULL.");
547 final Set<NotificationDefinition> notifications = module.getNotifications();
548 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
549 if (notifications.isEmpty()) {
553 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
554 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
555 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
559 for (final NotificationDefinition notification : notifications) {
560 if (notification != null) {
561 processUsesAugments(notification, module);
563 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
564 notification, null, module);
565 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
566 notificationInterface.addImplementsType(NOTIFICATION);
567 genCtx.get(module).addChildNodeType(notification, notificationInterface);
569 // Notification object
570 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
571 notification.getChildNodes());
573 listenerInterface.addMethod("on" + notificationInterface.getName())
574 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
575 .setComment(notification.getDescription()).setReturnType(Types.VOID);
578 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
580 genCtx.get(module).addTopLevelNodeType(listenerInterface);
584 * Converts all <b>identities</b> of the module to the list of
585 * <code>Type</code> objects.
588 * module from which is obtained set of all identity objects to
591 * schema context only used as input parameter for method
592 * {@link identityToGenType}
595 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
596 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
597 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
599 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
600 for (final IdentitySchemaNode identity : schemaIdentities) {
601 identityToGenType(module, basePackageName, identity, context);
607 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
608 * created transport object builder. If identity contains base identity then
609 * reference to base identity is added to superior identity as its extend.
610 * If identity doesn't contain base identity then only reference to abstract
611 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
612 * BaseIdentity} is added
616 * @param basePackageName
617 * string contains the module package name
619 * IdentitySchemaNode which contains data about identity
621 * SchemaContext which is used to get package and name
622 * information about base of identity
625 private void identityToGenType(final Module module, final String basePackageName,
626 final IdentitySchemaNode identity, final SchemaContext context) {
627 if (identity == null) {
630 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
631 final String genTypeName = BindingMapping.getClassName(identity.getQName());
632 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
633 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
634 if (baseIdentity == null) {
635 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
636 BaseIdentity.class.getSimpleName());
637 newType.setExtendsType(gto.toInstance());
639 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
640 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
642 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
643 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
645 newType.setExtendsType(gto);
647 newType.setAbstract(true);
648 newType.addComment(identity.getDescription());
649 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
650 newType.setReference(identity.getReference());
651 newType.setModuleName(module.getName());
652 newType.setSchemaPath(identity.getPath().getPathFromRoot());
654 final QName qname = identity.getQName();
655 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
657 genCtx.get(module).addIdentityType(identity.getQName(), newType);
660 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
662 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
666 * Converts all <b>groupings</b> of the module to the list of
667 * <code>Type</code> objects. Firstly are groupings sorted according mutual
668 * dependencies. At least dependent (independent) groupings are in the list
669 * saved at first positions. For every grouping the record is added to map
670 * {@link BindingGeneratorImpl#allGroupings allGroupings}
675 * of groupings from which types will be generated
678 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
679 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
680 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
682 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
683 groupingToGenType(basePackageName, grouping, module);
688 * Converts individual grouping to GeneratedType. Firstly generated type
689 * builder is created and every child node of grouping is resolved to the
692 * @param basePackageName
693 * string contains the module package name
695 * GroupingDefinition which contains data about grouping
698 * @return GeneratedType which is generated from grouping (object of type
699 * <code>GroupingDefinition</code>)
701 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
702 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
703 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
704 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
705 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
706 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
707 groupingsToGenTypes(module, grouping.getGroupings());
708 processUsesAugments(grouping, module);
712 * Adds enumeration builder created from <code>enumTypeDef</code> to
713 * <code>typeBuilder</code>.
715 * Each <code>enumTypeDef</code> item is added to builder with its name and
719 * EnumTypeDefinition contains enum data
721 * string contains name which will be assigned to enumeration
724 * GeneratedTypeBuilder to which will be enum builder assigned
726 * Module in which type should be generated
727 * @return enumeration builder which contains data from
728 * <code>enumTypeDef</code>
730 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
731 final GeneratedTypeBuilder typeBuilder, final Module module) {
732 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
733 && (enumTypeDef.getQName().getLocalName() != null)) {
734 final String enumerationName = BindingMapping.getClassName(enumName);
735 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
736 enumBuilder.setDescription(enumTypeDef.getDescription());
737 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
738 ModuleContext ctx = genCtx.get(module);
739 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
746 * Generates type builder for <code>module</code>.
749 * Module which is source of package name for generated type
752 * string which is added to the module class name representation
754 * @return instance of GeneratedTypeBuilder which represents
755 * <code>module</code>.
756 * @throws IllegalArgumentException
757 * if <code>module</code> is null
759 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
760 checkArgument(module != null, "Module reference cannot be NULL.");
761 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
762 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
764 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
765 moduleBuilder.setDescription(createDescription(module));
766 moduleBuilder.setReference(module.getReference());
767 moduleBuilder.setModuleName(moduleName);
769 return moduleBuilder;
773 * Converts <code>augSchema</code> to list of <code>Type</code> which
774 * contains generated type for augmentation. In addition there are also
775 * generated types for all containers, list and choices which are child of
776 * <code>augSchema</code> node or a generated types for cases are added if
777 * augmented node is choice.
779 * @param augmentPackageName
780 * string with the name of the package to which the augmentation
783 * AugmentationSchema which is contains data about augmentation
784 * (target path, childs...)
787 * @param parentUsesNode
788 * @throws IllegalArgumentException
790 * <li>if <code>augmentPackageName</code> equals null</li>
791 * <li>if <code>augSchema</code> equals null</li>
793 * @throws IllegalStateException
794 * if augment target path is null
796 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
797 final Module module) {
798 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
799 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
800 checkState(augSchema.getTargetPath() != null,
801 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
803 processUsesAugments(augSchema, module);
804 final SchemaPath targetPath = augSchema.getTargetPath();
805 SchemaNode targetSchemaNode = null;
807 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
808 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
809 if (targetSchemaNode instanceof DerivableSchemaNode) {
810 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
812 if (targetSchemaNode == null) {
813 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
814 + " in module " + module.getName());
817 if (targetSchemaNode == null) {
818 throw new IllegalArgumentException("augment target not found: " + targetPath);
821 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
822 if (targetTypeBuilder == null) {
823 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
825 if (targetTypeBuilder == null) {
826 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
829 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
830 final String packageName = augmentPackageName;
831 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
832 targetTypeBuilder.getName());
833 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
836 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
837 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
841 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
842 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
843 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
844 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
845 checkState(augSchema.getTargetPath() != null,
846 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
848 processUsesAugments(augSchema, module);
849 final SchemaPath targetPath = augSchema.getTargetPath();
850 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
851 if (targetSchemaNode == null) {
852 throw new IllegalArgumentException("augment target not found: " + targetPath);
855 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
856 if (targetTypeBuilder == null) {
857 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
859 if (targetTypeBuilder == null) {
860 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
863 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
864 String packageName = augmentPackageName;
865 if (usesNodeParent instanceof SchemaNode) {
866 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
868 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
871 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
872 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
877 * Convenient method to find node added by uses statement.
881 * @param parentUsesNode
882 * parent of uses node
883 * @return node from its original location in grouping
885 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
886 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
888 if (!(targetGrouping instanceof GroupingDefinition)) {
889 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
892 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
893 SchemaNode result = grouping;
894 for (final QName node : targetPath.getPathFromRoot()) {
895 // finding by local name is valid, grouping cannot contain nodes
896 // with same name and different namespace
897 if (result instanceof DataNodeContainer) {
898 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
899 } else if (result instanceof ChoiceSchemaNode) {
900 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
903 if (result == null) {
907 if (result instanceof DerivableSchemaNode) {
908 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
909 Optional<? extends SchemaNode> originalNode = castedResult
911 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
912 result = originalNode.get();
916 if (result instanceof DataSchemaNode) {
917 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
918 if (resultDataSchemaNode.isAddedByUses()) {
919 // The original node is required, but we have only the copy of
920 // the original node.
921 // Maybe this indicates a bug in Yang parser.
922 throw new IllegalStateException(
923 "Failed to generate code for augment in "
926 return resultDataSchemaNode;
929 throw new IllegalStateException(
930 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
936 * Returns a generated type builder for an augmentation.
938 * The name of the type builder is equal to the name of augmented node with
939 * serial number as suffix.
943 * @param augmentPackageName
944 * string with contains the package name to which the augment
946 * @param basePackageName
947 * string with the package name to which the augmented node
949 * @param targetTypeRef
952 * augmentation schema which contains data about the child nodes
953 * and uses of augment
954 * @return generated type builder for augment
956 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
957 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
958 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
959 if (augmentBuilders == null) {
960 augmentBuilders = new HashMap<>();
961 genTypeBuilders.put(augmentPackageName, augmentBuilders);
963 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
966 if (augIdentifier != null) {
967 augTypeName = BindingMapping.getClassName(augIdentifier);
969 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
972 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
974 augTypeBuilder.addImplementsType(DATA_OBJECT);
975 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
976 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
977 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
979 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
980 augmentBuilders.put(augTypeName, augTypeBuilder);
982 if(!augSchema.getChildNodes().isEmpty()) {
983 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
984 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
987 genCtx.get(module).addAugmentType(augTypeBuilder);
988 return augTypeBuilder;
993 * @param unknownSchemaNodes
994 * @return nodeParameter of UnknownSchemaNode
996 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
997 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
998 final QName nodeType = unknownSchemaNode.getNodeType();
999 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1000 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1001 return unknownSchemaNode.getNodeParameter();
1008 * Returns first unique name for the augment generated type builder. The
1009 * generated type builder name for augment consists from name of augmented
1010 * node and serial number of its augmentation.
1013 * map of builders which were created in the package to which the
1014 * augmentation belongs
1015 * @param genTypeName
1016 * string with name of augmented node
1017 * @return string with unique name for augmentation builder
1019 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1021 if (builders != null) {
1022 while (builders.containsKey(genTypeName + index)) {
1026 return genTypeName + index;
1030 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1031 * node for which <code>typeBuilder</code> was created.
1033 * The subnodes aren't mapped to the methods if they are part of grouping or
1034 * augment (in this case are already part of them).
1038 * @param basePackageName
1039 * string contains the module package name
1041 * generated type builder which represents any node. The subnodes
1042 * of this node are added to the <code>typeBuilder</code> as
1043 * methods. The subnode can be of type leaf, leaf-list, list,
1044 * container, choice.
1047 * @param schemaNodes
1048 * set of data schema nodes which are the children of the node
1049 * for which <code>typeBuilder</code> was created
1050 * @return generated type builder which is the same builder as input
1051 * parameter. The getter methods (representing child nodes) could be
1054 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1055 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1056 if (schemaNodes != null && parent != null) {
1057 for (final DataSchemaNode schemaNode : schemaNodes) {
1058 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1059 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1067 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1068 * node for which <code>typeBuilder</code> was created.
1072 * @param basePackageName
1073 * string contains the module package name
1074 * @param typeBuilder
1075 * generated type builder which represents any node. The subnodes
1076 * of this node are added to the <code>typeBuilder</code> as
1077 * methods. The subnode can be of type leaf, leaf-list, list,
1078 * container, choice.
1081 * @param schemaNodes
1082 * set of data schema nodes which are the children of the node
1083 * for which <code>typeBuilder</code> was created
1084 * @return generated type builder which is the same object as the input
1085 * parameter <code>typeBuilder</code>. The getter method could be
1088 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1089 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1090 final Iterable<DataSchemaNode> schemaNodes) {
1091 if ((schemaNodes != null) && (typeBuilder != null)) {
1092 for (final DataSchemaNode schemaNode : schemaNodes) {
1093 if (!schemaNode.isAugmenting()) {
1094 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1102 * Adds to <code>typeBuilder</code> a method which is derived from
1103 * <code>schemaNode</code>.
1105 * @param basePackageName
1106 * string with the module package name
1108 * data schema node which is added to <code>typeBuilder</code> as
1110 * @param typeBuilder
1111 * generated type builder to which is <code>schemaNode</code>
1112 * added as a method.
1118 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1119 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1120 if (node != null && typeBuilder != null) {
1121 if (node instanceof LeafSchemaNode) {
1122 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1123 } else if (node instanceof LeafListSchemaNode) {
1124 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1125 } else if (node instanceof ContainerSchemaNode) {
1126 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1127 } else if (node instanceof ListSchemaNode) {
1128 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1129 } else if (node instanceof ChoiceSchemaNode) {
1130 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1132 // TODO: anyxml not yet supported
1133 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1134 typeBuilder.getFullyQualifiedName());
1140 * Converts <code>choiceNode</code> to the list of generated types for
1141 * choice and its cases.
1143 * The package names for choice and for its cases are created as
1144 * concatenation of the module package (<code>basePackageName</code>) and
1145 * names of all parents node.
1149 * @param basePackageName
1150 * string with the module package name
1154 * choice node which is mapped to generated type. Also child
1155 * nodes - cases are mapped to generated types.
1156 * @throws IllegalArgumentException
1158 * <li>if <code>basePackageName</code> is null</li>
1159 * <li>if <code>choiceNode</code> is null</li>
1162 private void choiceToGeneratedType(final Module module, final String basePackageName,
1163 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1164 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1165 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1167 if (!choiceNode.isAddedByUses()) {
1168 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1169 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1170 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1172 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1173 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1174 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1175 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1180 * Converts <code>caseNodes</code> set to list of corresponding generated
1183 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1184 * created generated type builder. The package names for the builder is
1185 * created as concatenation of the module package (
1186 * <code>basePackageName</code>) and names of all parents nodes of the
1187 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1188 * between every case builder and <i>choice</i> type
1192 * @param basePackageName
1193 * string with the module package name
1194 * @param refChoiceType
1195 * type which represents superior <i>case</i>
1197 * choice case node which is mapped to generated type
1198 * @return list of generated types for <code>caseNodes</code>.
1199 * @throws IllegalArgumentException
1201 * <li>if <code>basePackageName</code> equals null</li>
1202 * <li>if <code>refChoiceType</code> equals null</li>
1203 * <li>if <code>caseNodes</code> equals null</li>
1206 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1207 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1208 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1209 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1210 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1212 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1213 if (caseNodes == null) {
1217 for (final ChoiceCaseNode caseNode : caseNodes) {
1218 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1219 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1220 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1221 caseTypeBuilder.addImplementsType(refChoiceType);
1222 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1223 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1224 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1225 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1226 if (caseChildNodes != null) {
1227 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1229 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1230 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1232 if (parent instanceof AugmentationSchema) {
1233 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1234 final SchemaPath targetPath = augSchema.getTargetPath();
1235 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1236 if (targetSchemaNode instanceof DataSchemaNode
1237 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1238 if (targetSchemaNode instanceof DerivableSchemaNode) {
1239 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1241 if (targetSchemaNode == null) {
1242 throw new IllegalStateException(
1243 "Failed to find target node from grouping for augmentation " + augSchema
1244 + " in module " + module.getName());
1247 parent = targetSchemaNode;
1250 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1251 choiceNodeParentPath);
1252 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1253 if (childOfType == null) {
1254 childOfType = findGroupingByPath(parent.getPath());
1256 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1258 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1263 processUsesAugments(caseNode, module);
1268 * Generates list of generated types for all the cases of a choice which are
1269 * added to the choice through the augment.
1273 * @param basePackageName
1274 * string contains name of package to which augment belongs. If
1275 * an augmented choice is from an other package (pcg1) than an
1276 * augmenting choice (pcg2) then case's of the augmenting choice
1277 * will belong to pcg2.
1279 * Type which represents target choice
1281 * node which represents target choice
1282 * @param augmentedNodes
1283 * set of choice case nodes for which is checked if are/aren't
1284 * added to choice through augmentation
1285 * @return list of generated types which represents augmented cases of
1286 * choice <code>refChoiceType</code>
1287 * @throws IllegalArgumentException
1289 * <li>if <code>basePackageName</code> is null</li>
1290 * <li>if <code>targetType</code> is null</li>
1291 * <li>if <code>augmentedNodes</code> is null</li>
1294 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1295 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1296 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1297 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1298 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1300 for (final DataSchemaNode caseNode : augmentedNodes) {
1301 if (caseNode != null) {
1302 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1303 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1304 caseTypeBuilder.addImplementsType(targetType);
1306 SchemaNode parent = null;
1307 final SchemaPath nodeSp = targetNode.getPath();
1308 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1310 GeneratedTypeBuilder childOfType = null;
1311 if (parent instanceof Module) {
1312 childOfType = genCtx.get(parent).getModuleNode();
1313 } else if (parent instanceof ChoiceCaseNode) {
1314 childOfType = findCaseByPath(parent.getPath());
1315 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1316 childOfType = findChildNodeByPath(parent.getPath());
1317 } else if (parent instanceof GroupingDefinition) {
1318 childOfType = findGroupingByPath(parent.getPath());
1321 if (childOfType == null) {
1322 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1325 ChoiceCaseNode node = null;
1326 if (caseNode instanceof ChoiceCaseNode) {
1327 node = (ChoiceCaseNode) caseNode;
1329 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1331 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1332 if (childNodes != null) {
1333 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1335 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1336 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1341 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1342 // Deal with old parser, clearing out references to typedefs
1343 if (type instanceof ExtendedType) {
1347 // New parser with encapsulated type
1348 if (leaf.getPath().equals(type.getPath())) {
1352 // Embedded type definition with new parser. Also takes care of the old parser with bits
1353 if (leaf.getPath().equals(type.getPath().getParent())) {
1357 // Old parser uses broken Union type, which does not change its schema path
1358 if (type instanceof UnionType) {
1366 * Converts <code>leaf</code> to the getter method which is added to
1367 * <code>typeBuilder</code>.
1369 * @param typeBuilder
1370 * generated type builder to which is added getter method as
1371 * <code>leaf</code> mapping
1373 * leaf schema node which is mapped as getter method which is
1374 * added to <code>typeBuilder</code>
1376 * Module in which type was defined
1377 * @return boolean value
1379 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1381 * <li>true - in other cases</li>
1384 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1385 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1389 final String leafName = leaf.getQName().getLocalName();
1390 if (leafName == null) {
1394 final Module parentModule = findParentModule(schemaContext, leaf);
1395 Type returnType = null;
1397 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1398 if (isInnerType(leaf, typeDef)) {
1399 if (typeDef instanceof EnumTypeDefinition) {
1400 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1401 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1402 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1403 typeBuilder, module);
1405 if (enumBuilder != null) {
1406 returnType = enumBuilder.toInstance(typeBuilder);
1408 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1409 } else if (typeDef instanceof UnionTypeDefinition) {
1410 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1411 if (genTOBuilder != null) {
1412 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1414 } else if (typeDef instanceof BitsTypeDefinition) {
1415 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1416 if (genTOBuilder != null) {
1417 returnType = genTOBuilder.toInstance();
1420 // It is constrained version of already declared type (inner declared type exists,
1421 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1422 // In order to get proper class we need to look up closest derived type
1423 // and apply restrictions from leaf type
1424 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1425 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1429 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1430 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1433 if (returnType == null) {
1437 String leafDesc = leaf.getDescription();
1438 if (leafDesc == null) {
1442 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1443 processContextRefExtension(leaf, getter, parentModule);
1447 private static TypeDefinition<?> getBaseOrDeclaredType(TypeDefinition<?> typeDef) {
1448 if (typeDef instanceof ExtendedType) {
1449 // Legacy behaviour returning ExtendedType is enough
1452 // Returns DerivedType in case of new parser.
1453 final TypeDefinition<?> baseType = typeDef.getBaseType();
1454 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1457 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1458 final Module module) {
1459 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1460 final QName nodeType = node.getNodeType();
1461 if ("context-reference".equals(nodeType.getLocalName())) {
1462 final String nodeParam = node.getNodeParameter();
1463 IdentitySchemaNode identity = null;
1464 String basePackageName = null;
1465 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1466 final Iterator<String> iterator = splittedElement.iterator();
1467 final int length = Iterables.size(splittedElement);
1469 identity = findIdentityByName(module.getIdentities(), iterator.next());
1470 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1471 } else if (length == 2) {
1472 final String prefix = iterator.next();
1473 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1474 if (dependentModule == null) {
1475 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1478 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1479 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1481 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1484 if (identity == null) {
1485 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1489 final Class<RoutingContext> clazz = RoutingContext.class;
1490 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1491 clazz.getSimpleName());
1492 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1493 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1494 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1499 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1500 for (final IdentitySchemaNode id : identities) {
1501 if (id.getQName().getLocalName().equals(name)) {
1508 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1509 for (final ModuleImport imp : imports) {
1510 if (imp.getPrefix().equals(prefix)) {
1511 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1517 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1518 final boolean isReadOnly, final Module module) {
1519 if ((leaf != null) && (toBuilder != null)) {
1520 String leafDesc = leaf.getDescription();
1521 if (leafDesc == null) {
1524 Type returnType = null;
1525 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1526 if (typeDef instanceof UnionTypeDefinition) {
1527 // GeneratedType for this type definition should be already
1529 final QName qname = typeDef.getQName();
1530 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1531 qname.getRevision());
1532 final ModuleContext mc = genCtx.get(unionModule);
1533 returnType = mc.getTypedefs().get(typeDef.getPath());
1534 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1535 // Annonymous enumeration (already generated, since it is inherited via uses).
1536 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1537 QName qname = originalLeaf.getQName();
1538 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1539 qname.getRevision());
1540 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1542 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1544 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1550 * Converts <code>leaf</code> schema node to property of generated TO
1554 * generated TO builder to which is <code>leaf</code> added as
1557 * leaf schema node which is added to <code>toBuilder</code> as
1562 * boolean value which says if leaf property is|isn't read only
1563 * @return boolean value
1565 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1566 * name equals null or if leaf is added by <i>uses</i>.</li>
1567 * <li>true - other cases</li>
1570 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1571 final Type returnType, final boolean isReadOnly) {
1572 if (returnType == null) {
1575 final String leafName = leaf.getQName().getLocalName();
1576 final String leafDesc = leaf.getDescription();
1577 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1578 propBuilder.setReadOnly(isReadOnly);
1579 propBuilder.setReturnType(returnType);
1580 propBuilder.setComment(leafDesc);
1581 toBuilder.addEqualsIdentity(propBuilder);
1582 toBuilder.addHashIdentity(propBuilder);
1583 toBuilder.addToStringProperty(propBuilder);
1588 * Converts <code>node</code> leaf list schema node to getter method of
1589 * <code>typeBuilder</code>.
1591 * @param typeBuilder
1592 * generated type builder to which is <code>node</code> added as
1595 * leaf list schema node which is added to
1596 * <code>typeBuilder</code> as getter method
1598 * @return boolean value
1600 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1601 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1602 * <li>false - other cases</li>
1605 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1606 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1610 final QName nodeName = node.getQName();
1611 if (nodeName == null) {
1615 final TypeDefinition<?> typeDef = node.getType();
1616 final Module parentModule = findParentModule(schemaContext, node);
1618 Type returnType = null;
1619 if (typeDef.getBaseType() == null) {
1620 if (typeDef instanceof EnumTypeDefinition) {
1621 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1622 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1623 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1624 typeBuilder,module);
1625 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1626 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1627 } else if (typeDef instanceof UnionTypeDefinition) {
1628 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1629 if (genTOBuilder != null) {
1630 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1632 } else if (typeDef instanceof BitsTypeDefinition) {
1633 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1634 returnType = genTOBuilder.toInstance();
1636 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1637 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1640 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1641 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1644 final ParameterizedType listType = Types.listTypeFor(returnType);
1645 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1649 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1650 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1651 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1652 genTOBuilder.getName());
1654 returnType.setDescription(typeDef.getDescription());
1655 returnType.setReference(typeDef.getReference());
1656 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1657 returnType.setModuleName(parentModule.getName());
1659 genTOBuilder.setTypedef(true);
1660 genTOBuilder.setIsUnion(true);
1661 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1665 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1668 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1669 method.setReturnType(returnType);
1670 method.addParameter(Types.STRING, "defaultValue");
1671 method.setAccessModifier(AccessModifier.PUBLIC);
1672 method.setStatic(true);
1674 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1675 if (types == null) {
1676 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1677 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1679 types.add(unionBuilder.toInstance());
1681 return returnType.toInstance();
1684 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1685 final String outerCls = Types.getOuterClassName(genTOBuilder);
1686 final StringBuilder name;
1687 if (outerCls != null) {
1688 name = new StringBuilder(outerCls);
1690 name = new StringBuilder();
1692 name.append(genTOBuilder.getName());
1693 name.append("Builder");
1694 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1695 unionBuilder.setIsUnionBuilder(true);
1696 return unionBuilder;
1699 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1700 final Module module) {
1701 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1705 * Instantiates generated type builder with <code>packageName</code> and
1706 * <code>schemaNode</code>.
1708 * The new builder always implements
1709 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1710 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1711 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1713 * If <code>schemaNode</code> is instance of
1714 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1715 * DataNodeContainer} it can also implement nodes which are specified in
1718 * @param packageName
1719 * string with the name of the package to which
1720 * <code>schemaNode</code> belongs.
1722 * schema node for which is created generated type builder
1724 * parent type (can be null)
1725 * @return generated type builder <code>schemaNode</code>
1727 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1728 final Type parent, final Module module) {
1729 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1730 if (parent == null) {
1731 it.addImplementsType(DATA_OBJECT);
1733 it.addImplementsType(BindingTypes.childOf(parent));
1735 if (!(schemaNode instanceof GroupingDefinition)) {
1736 it.addImplementsType(augmentable(it));
1739 if (schemaNode instanceof DataNodeContainer) {
1740 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1741 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1748 * Wraps the calling of the same overloaded method.
1750 * @param packageName
1751 * string with the package name to which returning generated type
1754 * schema node which provide data about the schema node name
1755 * @return generated type builder for <code>schemaNode</code>
1757 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1758 return addRawInterfaceDefinition(packageName, schemaNode, "");
1762 * Returns reference to generated type builder for specified
1763 * <code>schemaNode</code> with <code>packageName</code>.
1765 * Firstly the generated type builder is searched in
1766 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1767 * found it is created and added to <code>genTypeBuilders</code>.
1769 * @param packageName
1770 * string with the package name to which returning generated type
1773 * schema node which provide data about the schema node name
1775 * return type name prefix
1776 * @return generated type builder for <code>schemaNode</code>
1777 * @throws IllegalArgumentException
1779 * <li>if <code>schemaNode</code> is null</li>
1780 * <li>if <code>packageName</code> is null</li>
1781 * <li>if QName of schema node is null</li>
1782 * <li>if schemaNode name is null</li>
1786 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1787 final String prefix) {
1788 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1789 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1790 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1791 final String schemaNodeName = schemaNode.getQName().getLocalName();
1792 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1795 if (prefix == null) {
1796 genTypeName = BindingMapping.getClassName(schemaNodeName);
1798 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1801 // FIXME: Validation of name conflict
1802 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1803 final Module module = findParentModule(schemaContext, schemaNode);
1804 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1805 newType.addComment(schemaNode.getDescription());
1806 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1807 newType.setReference(schemaNode.getReference());
1808 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1809 newType.setModuleName(module.getName());
1811 if (!genTypeBuilders.containsKey(packageName)) {
1812 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1813 builders.put(genTypeName, newType);
1814 genTypeBuilders.put(packageName, builders);
1816 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1817 if (!builders.containsKey(genTypeName)) {
1818 builders.put(genTypeName, newType);
1825 * Creates the name of the getter method name from <code>localName</code>.
1828 * string with the name of the getter method
1831 * @return string with the name of the getter method for
1832 * <code>methodName</code> in JAVA method format
1834 public static String getterMethodName(final String localName, final Type returnType) {
1835 final StringBuilder method = new StringBuilder();
1836 if (BOOLEAN.equals(returnType)) {
1837 method.append("is");
1839 method.append("get");
1841 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1842 method.append(name);
1843 return method.toString();
1847 * Created a method signature builder as part of
1848 * <code>interfaceBuilder</code>.
1850 * The method signature builder is created for the getter method of
1851 * <code>schemaNodeName</code>. Also <code>comment</code> and
1852 * <code>returnType</code> information are added to the builder.
1854 * @param interfaceBuilder
1855 * generated type builder for which the getter method should be
1857 * @param schemaNodeName
1858 * string with schema node name. The name will be the part of the
1859 * getter method name.
1861 * string with comment for the getter method
1863 * type which represents the return type of the getter method
1864 * @return method signature builder which represents the getter method of
1865 * <code>interfaceBuilder</code>
1867 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1868 final String schemaNodeName, final String comment, final Type returnType) {
1869 final MethodSignatureBuilder getMethod = interfaceBuilder
1870 .addMethod(getterMethodName(schemaNodeName, returnType));
1871 getMethod.setComment(comment);
1872 getMethod.setReturnType(returnType);
1877 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1878 * or to <code>genTOBuilder</code> as property.
1880 * @param basePackageName
1881 * string contains the module package name
1883 * data schema node which should be added as getter method to
1884 * <code>typeBuilder</code> or as a property to
1885 * <code>genTOBuilder</code> if is part of the list key
1886 * @param typeBuilder
1887 * generated type builder for the list schema node
1888 * @param genTOBuilder
1889 * generated TO builder for the list keys
1891 * list of string which contains names of the list keys
1894 * @throws IllegalArgumentException
1896 * <li>if <code>schemaNode</code> equals null</li>
1897 * <li>if <code>typeBuilder</code> equals null</li>
1900 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1901 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1902 final Module module) {
1903 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1904 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1906 if (schemaNode instanceof LeafSchemaNode) {
1907 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1908 final String leafName = leaf.getQName().getLocalName();
1909 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1910 if (listKeys.contains(leafName)) {
1912 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1914 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1917 } else if (!schemaNode.isAddedByUses()) {
1918 if (schemaNode instanceof LeafListSchemaNode) {
1919 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1920 } else if (schemaNode instanceof ContainerSchemaNode) {
1921 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1922 } else if (schemaNode instanceof ChoiceSchemaNode) {
1923 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1924 } else if (schemaNode instanceof ListSchemaNode) {
1925 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1930 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1931 final GeneratedTOBuilder genTOBuilder) {
1932 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1934 if (genTOBuilder != null) {
1935 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1936 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1937 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1942 * Selects the names of the list keys from <code>list</code> and returns
1943 * them as the list of the strings
1946 * of string with names of the list keys
1947 * @return list of string which represents names of the list keys. If the
1948 * <code>list</code> contains no keys then the empty list is
1951 private static List<String> listKeys(final ListSchemaNode list) {
1952 final List<String> listKeys = new ArrayList<>();
1954 final List<QName> keyDefinition = list.getKeyDefinition();
1955 if (keyDefinition != null) {
1956 for (final QName keyDef : keyDefinition) {
1957 listKeys.add(keyDef.getLocalName());
1964 * Generates for the <code>list</code> which contains any list keys special
1965 * generated TO builder.
1967 * @param packageName
1968 * string with package name to which the list belongs
1970 * list schema node which is source of data about the list name
1971 * @return generated TO builder which represents the keys of the
1972 * <code>list</code> or null if <code>list</code> is null or list of
1973 * key definitions is null or empty.
1975 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1976 GeneratedTOBuilder genTOBuilder = null;
1977 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1978 final String listName = list.getQName().getLocalName() + "Key";
1979 final String genTOName = BindingMapping.getClassName(listName);
1980 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1982 return genTOBuilder;
1986 * Builds generated TO builders for <code>typeDef</code> of type
1987 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1988 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1989 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1990 * enclosing transfer object.
1992 * If more then one generated TO builder is created for enclosing then all
1993 * of the generated TO builders are added to <code>typeBuilder</code> as
1994 * enclosing transfer objects.
1997 * type definition which can be of type <code>UnionType</code> or
1998 * <code>BitsTypeDefinition</code>
1999 * @param typeBuilder
2000 * generated type builder to which is added generated TO created
2001 * from <code>typeDef</code>
2003 * string with name for generated TO builder
2005 * @return generated TO builder for <code>typeDef</code>
2007 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2008 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2009 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2010 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2011 final String packageName = typeBuilder.getFullyQualifiedName();
2012 if (typeDef instanceof UnionTypeDefinition) {
2013 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2014 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2015 classNameFromLeaf, leaf);
2016 genTOBuilders.addAll(types);
2018 GeneratedTOBuilder resultTOBuilder = null;
2019 if (types.isEmpty()) {
2020 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2022 resultTOBuilder = types.remove(0);
2023 for (final GeneratedTOBuilder genTOBuilder : types) {
2024 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2027 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2028 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2029 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2030 resultTOBuilder.addHashIdentity(genPropBuilder);
2031 resultTOBuilder.addToStringProperty(genPropBuilder);
2033 } else if (typeDef instanceof BitsTypeDefinition) {
2034 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2035 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2037 if (!genTOBuilders.isEmpty()) {
2038 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2039 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2041 return genTOBuilders.get(0);
2048 * Adds the implemented types to type builder.
2050 * The method passes through the list of <i>uses</i> in
2051 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2052 * generated type from {@link BindingGeneratorImpl#allGroupings
2053 * allGroupings} which is added as <i>implements type</i> to
2054 * <code>builder</code>
2056 * @param dataNodeContainer
2057 * element which contains the list of used YANG groupings
2059 * builder to which are added implemented types according to
2060 * <code>dataNodeContainer</code>
2061 * @return generated type builder with all implemented types
2063 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2064 final GeneratedTypeBuilder builder) {
2065 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2066 if (usesNode.getGroupingPath() != null) {
2067 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2068 if (genType == null) {
2069 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2070 + builder.getName());
2073 builder.addImplementsType(genType);
2075 builder.addComment(genType.getDescription());
2076 builder.setDescription(genType.getDescription());
2077 builder.setModuleName(genType.getModuleName());
2078 builder.setReference(genType.getReference());
2079 builder.setSchemaPath(genType.getSchemaPath());
2086 private static boolean isNullOrEmpty(final Collection<?> list) {
2087 return list == null || list.isEmpty();
2090 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2091 final StringBuilder sb = new StringBuilder();
2093 if (!isNullOrEmpty(schemaNodes)) {
2094 final SchemaNode node = schemaNodes.iterator().next();
2096 if (node instanceof RpcDefinition) {
2097 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2098 } else if (node instanceof NotificationDefinition) {
2099 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2102 sb.append(NEW_LINE);
2103 sb.append("<br>(Source path: <i>");
2104 sb.append(moduleSourcePath);
2105 sb.append("</i>):");
2106 sb.append(NEW_LINE);
2108 if (verboseClassComments) {
2110 sb.append(NEW_LINE);
2111 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2112 sb.append("</pre>");
2113 sb.append(NEW_LINE);
2116 return replaceAllIllegalChars(sb);
2119 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2120 final StringBuilder sb = new StringBuilder();
2121 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2123 if (!Strings.isNullOrEmpty(formattedDescription)) {
2124 sb.append(formattedDescription);
2125 sb.append(NEW_LINE);
2128 if (verboseClassComments) {
2129 final Module module = findParentModule(schemaContext, schemaNode);
2130 final StringBuilder linkToBuilderClass = new StringBuilder();
2131 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2132 final String className = namespace[namespace.length - 1];
2134 if (hasBuilderClass(schemaNode)) {
2135 linkToBuilderClass.append(className);
2136 linkToBuilderClass.append("Builder");
2140 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2141 sb.append(module.getName());
2143 sb.append(NEW_LINE);
2144 sb.append("<br>(Source path: <i>");
2145 sb.append(module.getModuleSourcePath());
2146 sb.append("</i>):");
2147 sb.append(NEW_LINE);
2149 sb.append(NEW_LINE);
2150 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2151 sb.append("</pre>");
2152 sb.append(NEW_LINE);
2153 sb.append("The schema path to identify an instance is");
2154 sb.append(NEW_LINE);
2156 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2158 sb.append(NEW_LINE);
2160 if (hasBuilderClass(schemaNode)) {
2161 sb.append(NEW_LINE);
2162 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2163 sb.append(NEW_LINE);
2165 sb.append(linkToBuilderClass);
2166 sb.append(NEW_LINE);
2167 if (schemaNode instanceof ListSchemaNode) {
2168 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2169 if (keyDef != null && !keyDef.isEmpty()) {
2171 sb.append(className);
2174 sb.append(NEW_LINE);
2179 return replaceAllIllegalChars(sb);
2182 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2183 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2184 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2190 private String createDescription(final Module module) {
2191 final StringBuilder sb = new StringBuilder();
2192 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2194 if (!Strings.isNullOrEmpty(formattedDescription)) {
2195 sb.append(formattedDescription);
2196 sb.append(NEW_LINE);
2199 if (verboseClassComments) {
2201 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2202 sb.append(module.getName());
2204 sb.append(NEW_LINE);
2205 sb.append("<br>Source path: <i>");
2206 sb.append(module.getModuleSourcePath());
2207 sb.append("</i>):");
2208 sb.append(NEW_LINE);
2210 sb.append(NEW_LINE);
2211 sb.append(YangTemplate.generateYangSnipet(module));
2212 sb.append("</pre>");
2215 return replaceAllIllegalChars(sb);
2218 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2219 for (final ModuleContext ctx : genCtx.values()) {
2220 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2221 if (result != null) {
2228 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2229 for (final ModuleContext ctx : genCtx.values()) {
2230 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2231 if (result != null) {
2238 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2239 for (final ModuleContext ctx : genCtx.values()) {
2240 final GeneratedTypeBuilder result = ctx.getCase(path);
2241 if (result != null) {
2248 public Map<Module, ModuleContext> getModuleContexts() {
2253 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2254 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2255 return ret.isEmpty() ? "" : ret;
2258 private void annotateDeprecatedIfNecessary(Status status, GeneratedTypeBuilder builder) {
2259 if (status == Status.DEPRECATED) {
2260 builder.addAnnotation("", "Deprecated");