2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
21 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
25 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
29 import com.google.common.base.Preconditions;
30 import com.google.common.base.Splitter;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Sets;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
43 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
44 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
45 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
46 import org.opendaylight.yangtools.binding.generator.util.Types;
47 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
49 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
50 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
51 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
52 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
53 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
54 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
55 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
56 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
57 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
58 import org.opendaylight.yangtools.sal.binding.model.api.Type;
59 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
66 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
68 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
69 import org.opendaylight.yangtools.yang.binding.BindingMapping;
70 import org.opendaylight.yangtools.yang.binding.DataContainer;
71 import org.opendaylight.yangtools.yang.binding.RpcService;
72 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
76 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
77 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
83 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.Module;
88 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
89 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.UsesNode;
97 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
101 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
102 import org.opendaylight.yangtools.yang.model.util.UnionType;
103 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
104 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
105 import org.slf4j.Logger;
106 import org.slf4j.LoggerFactory;
108 public class BindingGeneratorImpl implements BindingGenerator {
109 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
110 private static final Splitter COLON_SPLITTER = Splitter.on(':');
111 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
112 private static final char NEW_LINE = '\n';
115 * Constant with the concrete name of identifier.
117 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
120 * Constant with the concrete name of namespace.
122 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
124 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
127 * When set to true, generated classes will include javadoc comments which
128 * are useful for users.
130 private final boolean verboseClassComments;
133 * Outer key represents the package name. Outer value represents map of all
134 * builders in the same package. Inner key represents the schema node name
135 * (in JAVA class/interface name format). Inner value represents instance of
136 * builder for schema node specified in key part.
138 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
141 * Provide methods for converting YANG types to JAVA types.
143 private TypeProvider typeProvider;
146 * Holds reference to schema context to resolve data of augmented element
147 * when creating augmentation builder
149 private SchemaContext schemaContext;
152 * Create a new binding generator with verboe comments.
154 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
157 public BindingGeneratorImpl() {
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 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 (Module contextModule : contextModules) {
240 moduleToGenTypes(contextModule, context);
242 for (Module contextModule : contextModules) {
243 allAugmentsToGenTypes(contextModule);
246 final List<Type> filteredGenTypes = new ArrayList<>();
247 for (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 (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 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
318 genType.setModuleName(module.getName());
319 genType.setReference(node.getReference());
320 genType.setSchemaPath(node.getPath().getPathFromRoot());
321 if (node instanceof DataNodeContainer) {
322 genCtx.get(module).addChildNodeType(node, genType);
323 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
324 processUsesAugments((DataNodeContainer) node, module);
329 private void containerToGenType(final Module module, final String basePackageName,
330 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
331 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
332 if (genType != null) {
333 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
334 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
338 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
339 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
340 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
341 if (genType != null) {
342 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
344 final List<String> listKeys = listKeys(node);
345 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
346 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
347 if (genTOBuilder != null) {
348 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
349 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
350 genTOBuilder.addImplementsType(identifierMarker);
351 genType.addImplementsType(identifiableMarker);
354 for (DataSchemaNode schemaNode : node.getChildNodes()) {
355 if (!schemaNode.isAugmenting()) {
356 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
361 if (genTOBuilder != null) {
362 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
363 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
364 genTOBuilder.setSUID(prop);
367 typeBuildersToGenTypes(module, genType, genTOBuilder);
371 private void processUsesAugments(final DataNodeContainer node, final Module module) {
372 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
373 for (UsesNode usesNode : node.getUses()) {
374 for (AugmentationSchema augment : usesNode.getAugmentations()) {
375 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
376 processUsesAugments(augment, module);
382 * Converts all <b>augmentation</b> of the module to the list
383 * <code>Type</code> objects.
386 * module from which is obtained list of all augmentation objects
387 * to iterate over them
388 * @throws IllegalArgumentException
390 * <li>if the module is null</li>
391 * <li>if the name of module is null</li>
393 * @throws IllegalStateException
394 * if set of augmentations from module is null
396 private void allAugmentsToGenTypes(final Module module) {
397 checkArgument(module != null, "Module reference cannot be NULL.");
398 checkArgument(module.getName() != null, "Module name cannot be NULL.");
399 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
401 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
402 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
403 for (AugmentationSchema augment : augmentations) {
404 augmentationToGenTypes(basePackageName, augment, module);
409 * Returns list of <code>AugmentationSchema</code> objects. The objects are
410 * sorted according to the length of their target path from the shortest to
414 * module from which is obtained list of all augmentation objects
415 * @return list of sorted <code>AugmentationSchema</code> objects obtained
416 * from <code>module</code>
417 * @throws IllegalArgumentException
419 * @throws IllegalStateException
420 * if set of module augmentations is null
422 private List<AugmentationSchema> resolveAugmentations(final Module module) {
423 checkArgument(module != null, "Module reference cannot be NULL.");
424 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
426 final Set<AugmentationSchema> augmentations = module.getAugmentations();
427 List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
428 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
430 return sortedAugmentations;
434 * Create GeneratedTypeBuilder object from module argument.
437 * Module object from which builder will be created
438 * @return <code>GeneratedTypeBuilder</code> which is internal
439 * representation of the module
440 * @throws IllegalArgumentException
443 private GeneratedTypeBuilder moduleToDataType(final Module module) {
444 checkArgument(module != null, "Module reference cannot be NULL.");
446 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
447 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
448 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
449 moduleDataTypeBuilder.addComment(module.getDescription());
450 moduleDataTypeBuilder.setDescription(createDescription(module));
451 moduleDataTypeBuilder.setReference(module.getReference());
452 return moduleDataTypeBuilder;
456 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
457 * to the list of <code>Type</code> objects. In addition are to containers
458 * and lists which belong to input or output also part of returning list.
461 * module from which is obtained set of all rpc objects to
463 * @throws IllegalArgumentException
465 * <li>if the module is null</li>
466 * <li>if the name of module is null</li>
468 * @throws IllegalStateException
469 * if set of rpcs from module is null
471 private void rpcMethodsToGenType(final Module module) {
472 checkArgument(module != null, "Module reference cannot be NULL.");
473 checkArgument(module.getName() != null, "Module name cannot be NULL.");
474 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
475 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
476 if (rpcDefinitions.isEmpty()) {
480 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
481 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
482 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
483 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
485 for (RpcDefinition rpc : rpcDefinitions) {
487 final String rpcName = BindingMapping.getClassName(rpc.getQName());
488 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
489 final String rpcComment = rpc.getDescription();
490 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
491 final ContainerSchemaNode input = rpc.getInput();
492 final ContainerSchemaNode output = rpc.getOutput();
495 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
496 addImplementedInterfaceFromUses(input, inType);
497 inType.addImplementsType(DATA_OBJECT);
498 inType.addImplementsType(augmentable(inType));
499 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
500 genCtx.get(module).addChildNodeType(input, inType);
501 final GeneratedType inTypeInstance = inType.toInstance();
502 method.addParameter(inTypeInstance, "input");
505 Type outTypeInstance = VOID;
506 if (output != null) {
507 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
508 addImplementedInterfaceFromUses(output, outType);
509 outType.addImplementsType(DATA_OBJECT);
510 outType.addImplementsType(augmentable(outType));
511 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
512 genCtx.get(module).addChildNodeType(output, outType);
513 outTypeInstance = outType.toInstance();
516 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
517 method.setComment(rpcComment);
518 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
522 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
526 * Converts all <b>notifications</b> of the module to the list of
527 * <code>Type</code> objects. In addition are to this list added containers
528 * and lists which are part of this notification.
531 * module from which is obtained set of all notification objects
532 * to iterate over them
533 * @throws IllegalArgumentException
535 * <li>if the module equals null</li>
536 * <li>if the name of module equals null</li>
538 * @throws IllegalStateException
539 * if set of notifications from module is null
541 private void notificationsToGenType(final Module module) {
542 checkArgument(module != null, "Module reference cannot be NULL.");
543 checkArgument(module.getName() != null, "Module name cannot be NULL.");
544 final Set<NotificationDefinition> notifications = module.getNotifications();
545 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
546 if (notifications.isEmpty()) {
550 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
551 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
552 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
556 for (NotificationDefinition notification : notifications) {
557 if (notification != null) {
558 processUsesAugments(notification, module);
560 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
561 notification, BindingTypes.DATA_OBJECT, module);
562 notificationInterface.addImplementsType(NOTIFICATION);
563 genCtx.get(module).addChildNodeType(notification, notificationInterface);
565 // Notification object
566 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
567 notification.getChildNodes());
569 listenerInterface.addMethod("on" + notificationInterface.getName())
570 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
571 .setComment(notification.getDescription()).setReturnType(Types.VOID);
574 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
576 genCtx.get(module).addTopLevelNodeType(listenerInterface);
580 * Converts all <b>identities</b> of the module to the list of
581 * <code>Type</code> objects.
584 * module from which is obtained set of all identity objects to
587 * schema context only used as input parameter for method
588 * {@link identityToGenType}
591 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
592 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
593 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
595 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
596 for (IdentitySchemaNode identity : schemaIdentities) {
597 identityToGenType(module, basePackageName, identity, context);
603 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
604 * created transport object builder. If identity contains base identity then
605 * reference to base identity is added to superior identity as its extend.
606 * If identity doesn't contain base identity then only reference to abstract
607 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
608 * BaseIdentity} is added
612 * @param basePackageName
613 * string contains the module package name
615 * IdentitySchemaNode which contains data about identity
617 * SchemaContext which is used to get package and name
618 * information about base of identity
621 private void identityToGenType(final Module module, final String basePackageName,
622 final IdentitySchemaNode identity, final SchemaContext context) {
623 if (identity == null) {
626 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
627 final String genTypeName = BindingMapping.getClassName(identity.getQName());
628 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
629 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
630 if (baseIdentity == null) {
631 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
632 BaseIdentity.class.getSimpleName());
633 newType.setExtendsType(gto.toInstance());
635 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
636 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
638 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
639 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
641 newType.setExtendsType(gto);
643 newType.setAbstract(true);
644 newType.addComment(identity.getDescription());
645 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
646 newType.setReference(identity.getReference());
647 newType.setModuleName(module.getName());
648 newType.setSchemaPath(identity.getPath().getPathFromRoot());
650 final QName qname = identity.getQName();
651 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
653 genCtx.get(module).addIdentityType(identity.getQName(), newType);
656 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
658 StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
659 sb.append(".create(");
661 sb.append(name.getNamespace());
663 sb.append(name.getFormattedRevision());
665 sb.append(name.getLocalName());
668 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
672 * Converts all <b>groupings</b> of the module to the list of
673 * <code>Type</code> objects. Firstly are groupings sorted according mutual
674 * dependencies. At least dependent (independent) groupings are in the list
675 * saved at first positions. For every grouping the record is added to map
676 * {@link BindingGeneratorImpl#allGroupings allGroupings}
681 * of groupings from which types will be generated
684 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
685 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
686 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
688 for (GroupingDefinition grouping : groupingsSortedByDependencies) {
689 groupingToGenType(basePackageName, grouping, module);
694 * Converts individual grouping to GeneratedType. Firstly generated type
695 * builder is created and every child node of grouping is resolved to the
698 * @param basePackageName
699 * string contains the module package name
701 * GroupingDefinition which contains data about grouping
704 * @return GeneratedType which is generated from grouping (object of type
705 * <code>GroupingDefinition</code>)
707 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
708 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
709 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
710 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
711 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
712 groupingsToGenTypes(module, grouping.getGroupings());
713 processUsesAugments(grouping, module);
717 * Adds enumeration builder created from <code>enumTypeDef</code> to
718 * <code>typeBuilder</code>.
720 * Each <code>enumTypeDef</code> item is added to builder with its name and
724 * EnumTypeDefinition contains enum data
726 * string contains name which will be assigned to enumeration
729 * GeneratedTypeBuilder to which will be enum builder assigned
730 * @return enumeration builder which contains data from
731 * <code>enumTypeDef</code>
733 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
734 final GeneratedTypeBuilder typeBuilder) {
735 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
736 && (enumTypeDef.getQName().getLocalName() != null)) {
737 final String enumerationName = BindingMapping.getClassName(enumName);
738 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
739 enumBuilder.setDescription(enumTypeDef.getDescription());
740 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
747 * Generates type builder for <code>module</code>.
750 * Module which is source of package name for generated type
753 * string which is added to the module class name representation
755 * @return instance of GeneratedTypeBuilder which represents
756 * <code>module</code>.
757 * @throws IllegalArgumentException
758 * if <code>module</code> is null
760 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
761 checkArgument(module != null, "Module reference cannot be NULL.");
762 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
763 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
765 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
766 moduleBuilder.setDescription(createDescription(module));
767 moduleBuilder.setReference(module.getReference());
768 moduleBuilder.setModuleName(moduleName);
770 return moduleBuilder;
774 * Converts <code>augSchema</code> to list of <code>Type</code> which
775 * contains generated type for augmentation. In addition there are also
776 * generated types for all containers, list and choices which are child of
777 * <code>augSchema</code> node or a generated types for cases are added if
778 * augmented node is choice.
780 * @param augmentPackageName
781 * string with the name of the package to which the augmentation
784 * AugmentationSchema which is contains data about augmentation
785 * (target path, childs...)
788 * @param parentUsesNode
789 * @throws IllegalArgumentException
791 * <li>if <code>augmentPackageName</code> equals null</li>
792 * <li>if <code>augSchema</code> equals null</li>
794 * @throws IllegalStateException
795 * if augment target path is null
797 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
798 final Module module) {
799 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
800 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
801 checkState(augSchema.getTargetPath() != null,
802 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
804 processUsesAugments(augSchema, module);
805 final SchemaPath targetPath = augSchema.getTargetPath();
806 SchemaNode targetSchemaNode = null;
808 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
809 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
810 if (targetSchemaNode instanceof DerivableSchemaNode) {
811 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
813 if (targetSchemaNode == null) {
814 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
815 + " in module " + module.getName());
818 if (targetSchemaNode == null) {
819 throw new IllegalArgumentException("augment target not found: " + targetPath);
822 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
823 if (targetTypeBuilder == null) {
824 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
826 if (targetTypeBuilder == null) {
827 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
830 if (!(targetSchemaNode instanceof ChoiceNode)) {
831 String packageName = augmentPackageName;
832 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
833 targetTypeBuilder.getName());
834 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
837 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
838 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
842 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
843 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
844 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
845 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
846 checkState(augSchema.getTargetPath() != null,
847 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
849 processUsesAugments(augSchema, module);
850 final SchemaPath targetPath = augSchema.getTargetPath();
851 SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
852 if (targetSchemaNode == null) {
853 throw new IllegalArgumentException("augment target not found: " + targetPath);
856 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
857 if (targetTypeBuilder == null) {
858 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
860 if (targetTypeBuilder == null) {
861 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
864 if (!(targetSchemaNode instanceof ChoiceNode)) {
865 String packageName = augmentPackageName;
866 if (usesNodeParent instanceof SchemaNode) {
867 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
870 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
873 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
874 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
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 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
890 if (!(targetGrouping instanceof GroupingDefinition)) {
891 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
894 GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
895 SchemaNode result = grouping;
896 for (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 ChoiceNode) {
902 result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
905 if (result == null) {
909 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
910 Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
911 while (groupingUses.hasNext() && fromUses) {
912 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
913 if (result != null) {
914 fromUses = ((DataSchemaNode) result).isAddedByUses();
918 // this indicates invalid yang and thus possible bug in code because
919 // invalid yang should be already spotted by parser
920 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
923 return (DataSchemaNode) result;
927 * Returns a generated type builder for an augmentation.
929 * The name of the type builder is equal to the name of augmented node with
930 * serial number as suffix.
934 * @param augmentPackageName
935 * string with contains the package name to which the augment
937 * @param basePackageName
938 * string with the package name to which the augmented node
940 * @param targetTypeRef
943 * augmentation schema which contains data about the child nodes
944 * and uses of augment
945 * @return generated type builder for augment
947 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
948 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
949 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
950 if (augmentBuilders == null) {
951 augmentBuilders = new HashMap<>();
952 genTypeBuilders.put(augmentPackageName, augmentBuilders);
954 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
957 if (augIdentifier != null) {
958 augTypeName = BindingMapping.getClassName(augIdentifier);
960 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
963 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
965 augTypeBuilder.addImplementsType(DATA_OBJECT);
966 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
967 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
969 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
970 augmentBuilders.put(augTypeName, augTypeBuilder);
972 if(!augSchema.getChildNodes().isEmpty()) {
973 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
974 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
977 genCtx.get(module).addAugmentType(augTypeBuilder);
978 return augTypeBuilder;
983 * @param unknownSchemaNodes
984 * @return nodeParameter of UnknownSchemaNode
986 private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
987 for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
988 final QName nodeType = unknownSchemaNode.getNodeType();
989 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
990 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
991 return unknownSchemaNode.getNodeParameter();
998 * Returns first unique name for the augment generated type builder. The
999 * generated type builder name for augment consists from name of augmented
1000 * node and serial number of its augmentation.
1003 * map of builders which were created in the package to which the
1004 * augmentation belongs
1005 * @param genTypeName
1006 * string with name of augmented node
1007 * @return string with unique name for augmentation builder
1009 private String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1011 if (builders != null) {
1012 while (builders.containsKey(genTypeName + index)) {
1016 return genTypeName + index;
1020 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1021 * node for which <code>typeBuilder</code> was created.
1023 * The subnodes aren't mapped to the methods if they are part of grouping or
1024 * augment (in this case are already part of them).
1028 * @param basePackageName
1029 * string contains the module package name
1031 * generated type builder which represents any node. The subnodes
1032 * of this node are added to the <code>typeBuilder</code> as
1033 * methods. The subnode can be of type leaf, leaf-list, list,
1034 * container, choice.
1037 * @param schemaNodes
1038 * set of data schema nodes which are the children of the node
1039 * for which <code>typeBuilder</code> was created
1040 * @return generated type builder which is the same builder as input
1041 * parameter. The getter methods (representing child nodes) could be
1044 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1045 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1046 if (schemaNodes != null && parent != null) {
1047 for (DataSchemaNode schemaNode : schemaNodes) {
1048 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1049 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1057 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1058 * node for which <code>typeBuilder</code> was created.
1062 * @param basePackageName
1063 * string contains the module package name
1064 * @param typeBuilder
1065 * generated type builder which represents any node. The subnodes
1066 * of this node are added to the <code>typeBuilder</code> as
1067 * methods. The subnode can be of type leaf, leaf-list, list,
1068 * container, choice.
1071 * @param schemaNodes
1072 * set of data schema nodes which are the children of the node
1073 * for which <code>typeBuilder</code> was created
1074 * @return generated type builder which is the same object as the input
1075 * parameter <code>typeBuilder</code>. The getter method could be
1078 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1079 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1080 final Iterable<DataSchemaNode> schemaNodes) {
1081 if ((schemaNodes != null) && (typeBuilder != null)) {
1082 for (DataSchemaNode schemaNode : schemaNodes) {
1083 if (!schemaNode.isAugmenting()) {
1084 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1092 * Adds to <code>typeBuilder</code> a method which is derived from
1093 * <code>schemaNode</code>.
1095 * @param basePackageName
1096 * string with the module package name
1098 * data schema node which is added to <code>typeBuilder</code> as
1100 * @param typeBuilder
1101 * generated type builder to which is <code>schemaNode</code>
1102 * added as a method.
1108 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1109 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1110 if (node != null && typeBuilder != null) {
1111 if (node instanceof LeafSchemaNode) {
1112 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
1113 } else if (node instanceof LeafListSchemaNode) {
1114 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
1115 } else if (node instanceof ContainerSchemaNode) {
1116 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1117 } else if (node instanceof ListSchemaNode) {
1118 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1119 } else if (node instanceof ChoiceNode) {
1120 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
1122 // TODO: anyxml not yet supported
1123 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1124 typeBuilder.getFullyQualifiedName());
1130 * Converts <code>choiceNode</code> to the list of generated types for
1131 * choice and its cases.
1133 * The package names for choice and for its cases are created as
1134 * concatenation of the module package (<code>basePackageName</code>) and
1135 * names of all parents node.
1139 * @param basePackageName
1140 * string with the module package name
1144 * choice node which is mapped to generated type. Also child
1145 * nodes - cases are mapped to generated types.
1146 * @throws IllegalArgumentException
1148 * <li>if <code>basePackageName</code> is null</li>
1149 * <li>if <code>choiceNode</code> is null</li>
1152 private void choiceToGeneratedType(final Module module, final String basePackageName,
1153 final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
1154 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1155 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1157 if (!choiceNode.isAddedByUses()) {
1158 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1159 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1160 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1162 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1163 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1164 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1169 * Converts <code>caseNodes</code> set to list of corresponding generated
1172 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1173 * created generated type builder. The package names for the builder is
1174 * created as concatenation of the module package (
1175 * <code>basePackageName</code>) and names of all parents nodes of the
1176 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1177 * between every case builder and <i>choice</i> type
1181 * @param basePackageName
1182 * string with the module package name
1183 * @param refChoiceType
1184 * type which represents superior <i>case</i>
1186 * choice case node which is mapped to generated type
1187 * @return list of generated types for <code>caseNodes</code>.
1188 * @throws IllegalArgumentException
1190 * <li>if <code>basePackageName</code> equals null</li>
1191 * <li>if <code>refChoiceType</code> equals null</li>
1192 * <li>if <code>caseNodes</code> equals null</li>
1195 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1196 final Type refChoiceType, final ChoiceNode choiceNode) {
1197 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1198 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1199 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1201 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1202 if (caseNodes == null) {
1206 for (ChoiceCaseNode caseNode : caseNodes) {
1207 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1208 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1209 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1210 caseTypeBuilder.addImplementsType(refChoiceType);
1211 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1212 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1213 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1214 if (caseChildNodes != null) {
1215 final SchemaPath nodeSp = choiceNode.getPath();
1216 final Object parentNode = findDataSchemaNode(schemaContext, nodeSp.getParent());
1219 if (parentNode instanceof AugmentationSchema) {
1220 final AugmentationSchema augSchema = (AugmentationSchema) parentNode;
1221 final SchemaPath targetPath = augSchema.getTargetPath();
1222 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1223 if (targetSchemaNode instanceof DataSchemaNode
1224 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1225 if (targetSchemaNode instanceof DerivableSchemaNode) {
1226 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1228 if (targetSchemaNode == null) {
1229 throw new IllegalStateException(
1230 "Failed to find target node from grouping for augmentation " + augSchema
1231 + " in module " + module.getName());
1234 parent = targetSchemaNode;
1236 final SchemaPath sp = choiceNode.getPath();
1237 parent = findDataSchemaNode(schemaContext, sp.getParent());
1239 Preconditions.checkState(parent != null, "Could not find Choice node parent "+choiceNode.getPath().getParent());
1240 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1241 if (childOfType == null) {
1242 childOfType = findGroupingByPath(parent.getPath());
1244 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1247 processUsesAugments(caseNode, module);
1252 * Generates list of generated types for all the cases of a choice which are
1253 * added to the choice through the augment.
1257 * @param basePackageName
1258 * string contains name of package to which augment belongs. If
1259 * an augmented choice is from an other package (pcg1) than an
1260 * augmenting choice (pcg2) then case's of the augmenting choice
1261 * will belong to pcg2.
1263 * Type which represents target choice
1265 * node which represents target choice
1266 * @param augmentedNodes
1267 * set of choice case nodes for which is checked if are/aren't
1268 * added to choice through augmentation
1269 * @return list of generated types which represents augmented cases of
1270 * choice <code>refChoiceType</code>
1271 * @throws IllegalArgumentException
1273 * <li>if <code>basePackageName</code> is null</li>
1274 * <li>if <code>targetType</code> is null</li>
1275 * <li>if <code>augmentedNodes</code> is null</li>
1278 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1279 final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1280 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1281 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1282 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1284 for (DataSchemaNode caseNode : augmentedNodes) {
1285 if (caseNode != null) {
1286 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1287 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1288 caseTypeBuilder.addImplementsType(targetType);
1290 SchemaNode parent = null;
1291 final SchemaPath nodeSp = targetNode.getPath();
1292 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1294 GeneratedTypeBuilder childOfType = null;
1295 if (parent instanceof Module) {
1296 childOfType = genCtx.get(parent).getModuleNode();
1297 } else if (parent instanceof ChoiceCaseNode) {
1298 childOfType = findCaseByPath(parent.getPath());
1299 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1300 childOfType = findChildNodeByPath(parent.getPath());
1301 } else if (parent instanceof GroupingDefinition) {
1302 childOfType = findGroupingByPath(parent.getPath());
1305 if (childOfType == null) {
1306 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1309 ChoiceCaseNode node = null;
1310 if (caseNode instanceof ChoiceCaseNode) {
1311 node = (ChoiceCaseNode) caseNode;
1313 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1315 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1316 if (childNodes != null) {
1317 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1319 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1320 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1326 * Converts <code>leaf</code> to the getter method which is added to
1327 * <code>typeBuilder</code>.
1329 * @param typeBuilder
1330 * generated type builder to which is added getter method as
1331 * <code>leaf</code> mapping
1333 * leaf schema node which is mapped as getter method which is
1334 * added to <code>typeBuilder</code>
1335 * @return boolean value
1337 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1339 * <li>true - in other cases</li>
1342 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
1343 Type returnType = null;
1344 if ((leaf != null) && (typeBuilder != null)) {
1345 final String leafName = leaf.getQName().getLocalName();
1346 String leafDesc = leaf.getDescription();
1347 if (leafDesc == null) {
1351 final Module parentModule = findParentModule(schemaContext, leaf);
1352 if (leafName != null && !leaf.isAddedByUses()) {
1353 final TypeDefinition<?> typeDef = leaf.getType();
1355 GeneratedTOBuilder genTOBuilder;
1356 if (typeDef instanceof EnumTypeDefinition) {
1357 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1358 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1359 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1362 if (enumBuilder != null) {
1363 returnType = enumBuilder.toInstance(typeBuilder);
1365 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1366 } else if (typeDef instanceof UnionType) {
1367 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1368 if (genTOBuilder != null) {
1369 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1371 } else if (typeDef instanceof BitsTypeDefinition) {
1372 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1373 if (genTOBuilder != null) {
1374 returnType = genTOBuilder.toInstance();
1377 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1378 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1380 if (returnType != null) {
1381 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1382 processContextRefExtension(leaf, getter, parentModule);
1389 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1390 final Module module) {
1391 for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1392 final QName nodeType = node.getNodeType();
1393 if ("context-reference".equals(nodeType.getLocalName())) {
1394 final String nodeParam = node.getNodeParameter();
1395 IdentitySchemaNode identity = null;
1396 String basePackageName = null;
1397 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1398 final Iterator<String> iterator = splittedElement.iterator();
1399 final int length = Iterables.size(splittedElement);
1401 identity = findIdentityByName(module.getIdentities(), iterator.next());
1402 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1403 } else if (length == 2) {
1404 String prefix = iterator.next();
1405 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1406 if (dependentModule == null) {
1407 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1410 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1411 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1413 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1416 if (identity == null) {
1417 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1421 final Class<RoutingContext> clazz = RoutingContext.class;
1422 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1423 clazz.getSimpleName());
1424 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1425 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1426 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1431 private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1432 for (IdentitySchemaNode id : identities) {
1433 if (id.getQName().getLocalName().equals(name)) {
1440 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1441 for (ModuleImport imp : imports) {
1442 if (imp.getPrefix().equals(prefix)) {
1443 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1449 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1450 final boolean isReadOnly, final Module module) {
1451 if ((leaf != null) && (toBuilder != null)) {
1452 final String leafName = leaf.getQName().getLocalName();
1453 String leafDesc = leaf.getDescription();
1454 if (leafDesc == null) {
1458 if (leafName != null) {
1459 Type returnType = null;
1460 final TypeDefinition<?> typeDef = leaf.getType();
1461 if (typeDef instanceof UnionTypeDefinition) {
1462 // GeneratedType for this type definition should be already
1464 QName qname = typeDef.getQName();
1465 Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1466 qname.getRevision());
1467 final ModuleContext mc = genCtx.get(unionModule);
1468 returnType = mc.getTypedefs().get(typeDef.getPath());
1470 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1472 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1479 * Converts <code>leaf</code> schema node to property of generated TO
1483 * generated TO builder to which is <code>leaf</code> added as
1486 * leaf schema node which is added to <code>toBuilder</code> as
1491 * boolean value which says if leaf property is|isn't read only
1492 * @return boolean value
1494 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1495 * name equals null or if leaf is added by <i>uses</i>.</li>
1496 * <li>true - other cases</li>
1499 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1500 final Type returnType, final boolean isReadOnly) {
1501 if (returnType == null) {
1504 final String leafName = leaf.getQName().getLocalName();
1505 final String leafDesc = leaf.getDescription();
1506 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1507 propBuilder.setReadOnly(isReadOnly);
1508 propBuilder.setReturnType(returnType);
1509 propBuilder.setComment(leafDesc);
1510 toBuilder.addEqualsIdentity(propBuilder);
1511 toBuilder.addHashIdentity(propBuilder);
1512 toBuilder.addToStringProperty(propBuilder);
1517 * Converts <code>node</code> leaf list schema node to getter method of
1518 * <code>typeBuilder</code>.
1520 * @param typeBuilder
1521 * generated type builder to which is <code>node</code> added as
1524 * leaf list schema node which is added to
1525 * <code>typeBuilder</code> as getter method
1526 * @return boolean value
1528 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1529 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1530 * <li>false - other cases</li>
1533 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
1534 if ((node != null) && (typeBuilder != null)) {
1535 final QName nodeName = node.getQName();
1537 if (nodeName != null && !node.isAddedByUses()) {
1538 final TypeDefinition<?> typeDef = node.getType();
1539 final Module parentModule = findParentModule(schemaContext, node);
1541 Type returnType = null;
1542 if (typeDef instanceof EnumTypeDefinition) {
1543 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1544 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1545 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1547 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1548 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1549 } else if (typeDef instanceof UnionType) {
1550 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1551 if (genTOBuilder != null) {
1552 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1554 } else if (typeDef instanceof BitsTypeDefinition) {
1555 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1556 returnType = genTOBuilder.toInstance();
1558 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1559 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1562 final ParameterizedType listType = Types.listTypeFor(returnType);
1563 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1570 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1571 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1572 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1573 genTOBuilder.getName());
1575 returnType.setDescription(typeDef.getDescription());
1576 returnType.setReference(typeDef.getReference());
1577 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1578 returnType.setModuleName(parentModule.getName());
1580 genTOBuilder.setTypedef(true);
1581 genTOBuilder.setIsUnion(true);
1582 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1585 final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
1586 genTOBuilder.getName() + "Builder");
1587 unionBuilder.setIsUnionBuilder(true);
1588 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1589 method.setReturnType(returnType);
1590 method.addParameter(Types.STRING, "defaultValue");
1591 method.setAccessModifier(AccessModifier.PUBLIC);
1592 method.setStatic(true);
1594 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1595 if (types == null) {
1596 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1597 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1599 types.add(unionBuilder.toInstance());
1601 return returnType.toInstance();
1604 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1605 final Module module) {
1606 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1610 * Instantiates generated type builder with <code>packageName</code> and
1611 * <code>schemaNode</code>.
1613 * The new builder always implements
1614 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br />
1615 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1616 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1617 * Augmentable}.<br />
1618 * If <code>schemaNode</code> is instance of
1619 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1620 * DataNodeContainer} it can also implement nodes which are specified in
1623 * @param packageName
1624 * string with the name of the package to which
1625 * <code>schemaNode</code> belongs.
1627 * schema node for which is created generated type builder
1629 * parent type (can be null)
1630 * @return generated type builder <code>schemaNode</code>
1632 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1633 final Type parent, final Module module) {
1634 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1635 if (parent == null) {
1636 it.addImplementsType(DATA_OBJECT);
1638 it.addImplementsType(BindingTypes.childOf(parent));
1640 if (!(schemaNode instanceof GroupingDefinition)) {
1641 it.addImplementsType(augmentable(it));
1644 if (schemaNode instanceof DataNodeContainer) {
1645 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1646 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1653 * Wraps the calling of the same overloaded method.
1655 * @param packageName
1656 * string with the package name to which returning generated type
1659 * schema node which provide data about the schema node name
1660 * @return generated type builder for <code>schemaNode</code>
1662 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1663 return addRawInterfaceDefinition(packageName, schemaNode, "");
1667 * Returns reference to generated type builder for specified
1668 * <code>schemaNode</code> with <code>packageName</code>.
1670 * Firstly the generated type builder is searched in
1671 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1672 * found it is created and added to <code>genTypeBuilders</code>.
1674 * @param packageName
1675 * string with the package name to which returning generated type
1678 * schema node which provide data about the schema node name
1680 * return type name prefix
1681 * @return generated type builder for <code>schemaNode</code>
1682 * @throws IllegalArgumentException
1684 * <li>if <code>schemaNode</code> is null</li>
1685 * <li>if <code>packageName</code> is null</li>
1686 * <li>if QName of schema node is null</li>
1687 * <li>if schemaNode name is null</li>
1691 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1692 final String prefix) {
1693 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1694 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1695 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1696 final String schemaNodeName = schemaNode.getQName().getLocalName();
1697 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1700 if (prefix == null) {
1701 genTypeName = BindingMapping.getClassName(schemaNodeName);
1703 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1706 // FIXME: Validation of name conflict
1707 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1708 final Module module = findParentModule(schemaContext, schemaNode);
1709 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1710 newType.addComment(schemaNode.getDescription());
1711 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1712 newType.setReference(schemaNode.getReference());
1713 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1714 newType.setModuleName(module.getName());
1716 if (!genTypeBuilders.containsKey(packageName)) {
1717 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1718 builders.put(genTypeName, newType);
1719 genTypeBuilders.put(packageName, builders);
1721 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1722 if (!builders.containsKey(genTypeName)) {
1723 builders.put(genTypeName, newType);
1730 * Creates the name of the getter method name from <code>localName</code>.
1733 * string with the name of the getter method
1736 * @return string with the name of the getter method for
1737 * <code>methodName</code> in JAVA method format
1739 public static String getterMethodName(final String localName, final Type returnType) {
1740 final StringBuilder method = new StringBuilder();
1741 if (BOOLEAN.equals(returnType)) {
1742 method.append("is");
1744 method.append("get");
1746 String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1747 method.append(name);
1748 return method.toString();
1752 * Created a method signature builder as part of
1753 * <code>interfaceBuilder</code>.
1755 * The method signature builder is created for the getter method of
1756 * <code>schemaNodeName</code>. Also <code>comment</code> and
1757 * <code>returnType</code> information are added to the builder.
1759 * @param interfaceBuilder
1760 * generated type builder for which the getter method should be
1762 * @param schemaNodeName
1763 * string with schema node name. The name will be the part of the
1764 * getter method name.
1766 * string with comment for the getter method
1768 * type which represents the return type of the getter method
1769 * @return method signature builder which represents the getter method of
1770 * <code>interfaceBuilder</code>
1772 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1773 final String schemaNodeName, final String comment, final Type returnType) {
1774 final MethodSignatureBuilder getMethod = interfaceBuilder
1775 .addMethod(getterMethodName(schemaNodeName, returnType));
1776 getMethod.setComment(comment);
1777 getMethod.setReturnType(returnType);
1782 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1783 * or to <code>genTOBuilder</code> as property.
1785 * @param basePackageName
1786 * string contains the module package name
1788 * data schema node which should be added as getter method to
1789 * <code>typeBuilder</code> or as a property to
1790 * <code>genTOBuilder</code> if is part of the list key
1791 * @param typeBuilder
1792 * generated type builder for the list schema node
1793 * @param genTOBuilder
1794 * generated TO builder for the list keys
1796 * list of string which contains names of the list keys
1799 * @throws IllegalArgumentException
1801 * <li>if <code>schemaNode</code> equals null</li>
1802 * <li>if <code>typeBuilder</code> equals null</li>
1805 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1806 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1807 final Module module) {
1808 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1809 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1811 if (schemaNode instanceof LeafSchemaNode) {
1812 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1813 final String leafName = leaf.getQName().getLocalName();
1814 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf);
1815 if (listKeys.contains(leafName)) {
1817 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1819 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1822 } else if (!schemaNode.isAddedByUses()) {
1823 if (schemaNode instanceof LeafListSchemaNode) {
1824 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode);
1825 } else if (schemaNode instanceof ContainerSchemaNode) {
1826 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1827 } else if (schemaNode instanceof ChoiceNode) {
1828 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) schemaNode);
1829 } else if (schemaNode instanceof ListSchemaNode) {
1830 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1835 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1836 final GeneratedTOBuilder genTOBuilder) {
1837 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1839 if (genTOBuilder != null) {
1840 GeneratedTransferObject genTO = genTOBuilder.toInstance();
1841 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1842 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1847 * Selects the names of the list keys from <code>list</code> and returns
1848 * them as the list of the strings
1851 * of string with names of the list keys
1852 * @return list of string which represents names of the list keys. If the
1853 * <code>list</code> contains no keys then the empty list is
1856 private List<String> listKeys(final ListSchemaNode list) {
1857 final List<String> listKeys = new ArrayList<>();
1859 List<QName> keyDefinition = list.getKeyDefinition();
1860 if (keyDefinition != null) {
1861 for (QName keyDef : keyDefinition) {
1862 listKeys.add(keyDef.getLocalName());
1869 * Generates for the <code>list</code> which contains any list keys special
1870 * generated TO builder.
1872 * @param packageName
1873 * string with package name to which the list belongs
1875 * list schema node which is source of data about the list name
1876 * @return generated TO builder which represents the keys of the
1877 * <code>list</code> or null if <code>list</code> is null or list of
1878 * key definitions is null or empty.
1880 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1881 GeneratedTOBuilder genTOBuilder = null;
1882 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1883 final String listName = list.getQName().getLocalName() + "Key";
1884 final String genTOName = BindingMapping.getClassName(listName);
1885 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1887 return genTOBuilder;
1891 * Builds generated TO builders for <code>typeDef</code> of type
1892 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1893 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1894 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1895 * enclosing transfer object.
1897 * If more then one generated TO builder is created for enclosing then all
1898 * of the generated TO builders are added to <code>typeBuilder</code> as
1899 * enclosing transfer objects.
1902 * type definition which can be of type <code>UnionType</code> or
1903 * <code>BitsTypeDefinition</code>
1904 * @param typeBuilder
1905 * generated type builder to which is added generated TO created
1906 * from <code>typeDef</code>
1908 * string with name for generated TO builder
1910 * @return generated TO builder for <code>typeDef</code>
1912 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1913 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1914 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1915 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1916 final String packageName = typeBuilder.getFullyQualifiedName();
1917 if (typeDef instanceof UnionTypeDefinition) {
1918 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1919 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1920 classNameFromLeaf, leaf);
1921 genTOBuilders.addAll(types);
1923 GeneratedTOBuilder resultTOBuilder = null;
1924 if (types.isEmpty()) {
1925 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1927 resultTOBuilder = types.remove(0);
1928 for (GeneratedTOBuilder genTOBuilder : types) {
1929 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1932 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1933 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1934 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1935 resultTOBuilder.addHashIdentity(genPropBuilder);
1936 resultTOBuilder.addToStringProperty(genPropBuilder);
1938 } else if (typeDef instanceof BitsTypeDefinition) {
1939 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1940 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1942 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1943 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1944 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1946 return genTOBuilders.get(0);
1953 * Adds the implemented types to type builder.
1955 * The method passes through the list of <i>uses</i> in
1956 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1957 * generated type from {@link BindingGeneratorImpl#allGroupings
1958 * allGroupings} which is added as <i>implements type</i> to
1959 * <code>builder</code>
1961 * @param dataNodeContainer
1962 * element which contains the list of used YANG groupings
1964 * builder to which are added implemented types according to
1965 * <code>dataNodeContainer</code>
1966 * @return generated type builder with all implemented types
1968 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1969 final GeneratedTypeBuilder builder) {
1970 for (UsesNode usesNode : dataNodeContainer.getUses()) {
1971 if (usesNode.getGroupingPath() != null) {
1972 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1973 if (genType == null) {
1974 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1975 + builder.getName());
1978 builder.addImplementsType(genType);
1980 builder.addComment(genType.getDescription());
1981 builder.setDescription(genType.getDescription());
1982 builder.setModuleName(genType.getModuleName());
1983 builder.setReference(genType.getReference());
1984 builder.setSchemaPath(genType.getSchemaPath());
1991 private boolean isNullOrEmpty(final Collection<?> list) {
1992 return (list == null || list.isEmpty() ? true : false);
1995 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
1996 final StringBuilder sb = new StringBuilder();
1998 if (!isNullOrEmpty(schemaNodes)) {
1999 final SchemaNode node = schemaNodes.iterator().next();
2001 if (node instanceof RpcDefinition) {
2002 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2003 } else if (node instanceof NotificationDefinition) {
2004 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2007 sb.append(NEW_LINE);
2008 sb.append("<br />(Source path: <i>");
2009 sb.append(moduleSourcePath);
2010 sb.append("</i>):");
2011 sb.append(NEW_LINE);
2013 if (verboseClassComments) {
2015 sb.append(NEW_LINE);
2016 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2017 sb.append("</pre>");
2018 sb.append(NEW_LINE);
2021 return sb.toString();
2024 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2025 final StringBuilder sb = new StringBuilder();
2026 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2028 if (!isNullOrEmpty(formattedDescription)) {
2029 sb.append(formattedDescription);
2030 sb.append(NEW_LINE);
2033 if (verboseClassComments) {
2034 final Module module = findParentModule(schemaContext, schemaNode);
2035 final StringBuilder linkToBuilderClass = new StringBuilder();
2036 final StringBuilder linkToKeyClass = new StringBuilder();
2037 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2038 String className = namespace[namespace.length - 1];
2040 if (hasBuilderClass(schemaNode)) {
2041 linkToBuilderClass.append(className);
2042 linkToBuilderClass.append("Builder");
2044 if (schemaNode instanceof ListSchemaNode) {
2045 linkToKeyClass.append(className);
2046 linkToKeyClass.append("Key");
2051 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2052 sb.append(module.getName());
2054 sb.append(NEW_LINE);
2055 sb.append("<br />(Source path: <i>");
2056 sb.append(module.getModuleSourcePath());
2057 sb.append("</i>):");
2058 sb.append(NEW_LINE);
2060 sb.append(NEW_LINE);
2061 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2062 sb.append("</pre>");
2063 sb.append(NEW_LINE);
2064 sb.append("The schema path to identify an instance is");
2065 sb.append(NEW_LINE);
2067 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2069 sb.append(NEW_LINE);
2071 if (hasBuilderClass(schemaNode)) {
2072 sb.append(NEW_LINE);
2073 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2074 sb.append(NEW_LINE);
2076 sb.append(linkToBuilderClass);
2077 if (schemaNode instanceof ListSchemaNode) {
2079 sb.append(linkToKeyClass);
2081 sb.append(NEW_LINE);
2085 return sb.toString();
2088 private boolean hasBuilderClass(final SchemaNode schemaNode) {
2089 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2090 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2096 private boolean isNullOrEmpty(final String string) {
2097 return (string == null || string.isEmpty() ? true : false);
2100 private String createDescription(final Module module) {
2101 final StringBuilder sb = new StringBuilder();
2102 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2104 if (!isNullOrEmpty(formattedDescription)) {
2105 sb.append(formattedDescription);
2106 sb.append(NEW_LINE);
2109 if (verboseClassComments) {
2111 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2112 sb.append(module.getName());
2114 sb.append(NEW_LINE);
2115 sb.append("<br />Source path: <i>");
2116 sb.append(module.getModuleSourcePath());
2117 sb.append("</i>):");
2118 sb.append(NEW_LINE);
2120 sb.append(NEW_LINE);
2121 sb.append(YangTemplate.generateYangSnipet(module));
2122 sb.append("</pre>");
2125 return sb.toString();
2128 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2129 for (ModuleContext ctx : genCtx.values()) {
2130 GeneratedTypeBuilder result = ctx.getChildNode(path);
2131 if (result != null) {
2138 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2139 for (ModuleContext ctx : genCtx.values()) {
2140 GeneratedTypeBuilder result = ctx.getGrouping(path);
2141 if (result != null) {
2148 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2149 for (ModuleContext ctx : genCtx.values()) {
2150 GeneratedTypeBuilder result = ctx.getCase(path);
2151 if (result != null) {
2158 public Map<Module, ModuleContext> getModuleContexts() {