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.BindingGeneratorUtil.parseToValidParamName;
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.base.Splitter;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Sets;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
41 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
42 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
43 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
44 import org.opendaylight.yangtools.binding.generator.util.Types;
45 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
46 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
47 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
48 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
49 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
50 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
51 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
52 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
53 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
54 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
55 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
56 import org.opendaylight.yangtools.sal.binding.model.api.Type;
57 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
58 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
59 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
64 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
65 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
66 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
67 import org.opendaylight.yangtools.yang.binding.BindingMapping;
68 import org.opendaylight.yangtools.yang.binding.DataContainer;
69 import org.opendaylight.yangtools.yang.binding.RpcService;
70 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
71 import org.opendaylight.yangtools.yang.common.QName;
72 import org.opendaylight.yangtools.yang.common.RpcResult;
73 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
74 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
75 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
76 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
78 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
81 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.Module;
86 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
87 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
88 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
89 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
90 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
92 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.UsesNode;
95 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
99 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
100 import org.opendaylight.yangtools.yang.model.util.UnionType;
101 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
102 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
106 public class BindingGeneratorImpl implements BindingGenerator {
107 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
109 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
112 * Outer key represents the package name. Outer value represents map of all
113 * builders in the same package. Inner key represents the schema node name
114 * (in JAVA class/interface name format). Inner value represents instance of
115 * builder for schema node specified in key part.
117 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
120 * Provide methods for converting YANG types to JAVA types.
122 private TypeProvider typeProvider;
125 * Holds reference to schema context to resolve data of augmented element
126 * when creating augmentation builder
128 private SchemaContext schemaContext;
131 * Constant with the concrete name of namespace.
133 private final static String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
136 * Constant with the concrete name of identifier.
138 private final static String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
140 private final char NEW_LINE = '\n';
142 private final char TAB = '\t';
145 * Resolves generated types from <code>context</code> schema nodes of all
148 * Generated types are created for modules, groupings, types, containers,
149 * lists, choices, augments, rpcs, notification, identities.
152 * schema context which contains data about all schema nodes
154 * @return list of types (usually <code>GeneratedType</code>
155 * <code>GeneratedTransferObject</code>which are generated from
156 * <code>context</code> data.
157 * @throws IllegalArgumentException
158 * if arg <code>context</code> is null
159 * @throws IllegalStateException
160 * if <code>context</code> contain no modules
163 public List<Type> generateTypes(final SchemaContext context) {
164 checkArgument(context != null, "Schema Context reference cannot be NULL.");
165 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
166 schemaContext = context;
167 typeProvider = new TypeProviderImpl(context);
168 final Set<Module> modules = context.getModules();
169 return generateTypes(context, modules);
173 * Resolves generated types from <code>context</code> schema nodes only for
174 * modules specified in <code>modules</code>
176 * Generated types are created for modules, groupings, types, containers,
177 * lists, choices, augments, rpcs, notification, identities.
180 * schema context which contains data about all schema nodes
183 * set of modules for which schema nodes should be generated
185 * @return list of types (usually <code>GeneratedType</code> or
186 * <code>GeneratedTransferObject</code>) which:
188 * <li>are generated from <code>context</code> schema nodes and</li>
189 * <li>are also part of some of the module in <code>modules</code>
192 * @throws IllegalArgumentException
194 * <li>if arg <code>context</code> is null or</li>
195 * <li>if arg <code>modules</code> is null</li>
197 * @throws IllegalStateException
198 * if <code>context</code> contain no modules
201 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
202 checkArgument(context != null, "Schema Context reference cannot be NULL.");
203 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
204 checkArgument(modules != null, "Set of Modules cannot be NULL.");
206 schemaContext = context;
207 typeProvider = new TypeProviderImpl(context);
208 Module[] modulesArray = new Module[context.getModules().size()];
209 context.getModules().toArray(modulesArray);
210 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
211 genTypeBuilders = new HashMap<>();
213 for (Module contextModule : contextModules) {
214 moduleToGenTypes(contextModule, context);
216 for (Module contextModule : contextModules) {
217 allAugmentsToGenTypes(contextModule);
220 final List<Type> filteredGenTypes = new ArrayList<>();
221 for (Module m : modules) {
222 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
223 filteredGenTypes.addAll(ctx.getGeneratedTypes());
224 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
225 if (additionalTypes != null) {
226 filteredGenTypes.addAll(additionalTypes);
230 return filteredGenTypes;
233 private void moduleToGenTypes(final Module m, final SchemaContext context) {
234 genCtx.put(m, new ModuleContext());
235 allTypeDefinitionsToGenTypes(m);
236 groupingsToGenTypes(m, m.getGroupings());
237 rpcMethodsToGenType(m);
238 allIdentitiesToGenTypes(m, context);
239 notificationsToGenType(m);
241 if (!m.getChildNodes().isEmpty()) {
242 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
243 genCtx.get(m).addModuleNode(moduleType);
244 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
245 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
250 * Converts all extended type definitions of module to the list of
251 * <code>Type</code> objects.
254 * module from which is obtained set of type definitions
255 * @throws IllegalArgumentException
257 * <li>if module is null</li>
258 * <li>if name of module is null</li>
260 * @throws IllegalStateException
261 * if set of type definitions from module is null
263 private void allTypeDefinitionsToGenTypes(final Module module) {
264 checkArgument(module != null, "Module reference cannot be NULL.");
265 checkArgument(module.getName() != null, "Module name cannot be NULL.");
266 final DataNodeIterator it = new DataNodeIterator(module);
267 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
268 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
270 for (TypeDefinition<?> typedef : typeDefinitions) {
271 if (typedef != null) {
272 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
275 genCtx.get(module).addTypedefType(typedef.getPath(), type);
281 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
282 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
283 if (node.isAugmenting() || node.isAddedByUses()) {
286 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
287 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf);
288 genType.addComment(node.getDescription());
289 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
290 genType.setModuleName(module.getName());
291 genType.setReference(node.getReference());
292 genType.setSchemaPath(node.getPath().getPathFromRoot());
293 if (node instanceof DataNodeContainer) {
294 genCtx.get(module).addChildNodeType(node, genType);
295 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
296 processUsesAugments((DataNodeContainer) node, module);
301 private void containerToGenType(final Module module, final String basePackageName,
302 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
303 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
304 if (genType != null) {
305 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
306 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
310 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
311 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
312 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
313 if (genType != null) {
314 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
316 final List<String> listKeys = listKeys(node);
317 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
318 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
319 if (genTOBuilder != null) {
320 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
321 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
322 genTOBuilder.addImplementsType(identifierMarker);
323 genType.addImplementsType(identifiableMarker);
326 for (DataSchemaNode schemaNode : node.getChildNodes()) {
327 if (!schemaNode.isAugmenting()) {
328 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
333 if (genTOBuilder != null) {
334 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
335 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
336 genTOBuilder.setSUID(prop);
339 typeBuildersToGenTypes(module, genType, genTOBuilder);
343 private void processUsesAugments(final DataNodeContainer node, final Module module) {
344 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
345 for (UsesNode usesNode : node.getUses()) {
346 for (AugmentationSchema augment : usesNode.getAugmentations()) {
347 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
348 processUsesAugments(augment, module);
354 * Converts all <b>augmentation</b> of the module to the list
355 * <code>Type</code> objects.
358 * module from which is obtained list of all augmentation objects
359 * to iterate over them
360 * @throws IllegalArgumentException
362 * <li>if the module is null</li>
363 * <li>if the name of module is null</li>
365 * @throws IllegalStateException
366 * if set of augmentations from module is null
368 private void allAugmentsToGenTypes(final Module module) {
369 checkArgument(module != null, "Module reference cannot be NULL.");
370 checkArgument(module.getName() != null, "Module name cannot be NULL.");
371 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
373 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
374 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
375 for (AugmentationSchema augment : augmentations) {
376 augmentationToGenTypes(basePackageName, augment, module);
381 * Returns list of <code>AugmentationSchema</code> objects. The objects are
382 * sorted according to the length of their target path from the shortest to
386 * module from which is obtained list of all augmentation objects
387 * @return list of sorted <code>AugmentationSchema</code> objects obtained
388 * from <code>module</code>
389 * @throws IllegalArgumentException
391 * @throws IllegalStateException
392 * if set of module augmentations is null
394 private List<AugmentationSchema> resolveAugmentations(final Module module) {
395 checkArgument(module != null, "Module reference cannot be NULL.");
396 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
398 final Set<AugmentationSchema> augmentations = module.getAugmentations();
399 List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
400 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
402 return sortedAugmentations;
406 * Create GeneratedTypeBuilder object from module argument.
409 * Module object from which builder will be created
410 * @return <code>GeneratedTypeBuilder</code> which is internal
411 * representation of the module
412 * @throws IllegalArgumentException
415 private GeneratedTypeBuilder moduleToDataType(final Module module) {
416 checkArgument(module != null, "Module reference cannot be NULL.");
418 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
419 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
420 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
421 moduleDataTypeBuilder.addComment(module.getDescription());
422 moduleDataTypeBuilder.setDescription(createDescription(module));
423 moduleDataTypeBuilder.setReference(module.getReference());
424 return moduleDataTypeBuilder;
428 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
429 * to the list of <code>Type</code> objects. In addition are to containers
430 * and lists which belong to input or output also part of returning list.
433 * module from which is obtained set of all rpc objects to
435 * @throws IllegalArgumentException
437 * <li>if the module is null</li>
438 * <li>if the name of module is null</li>
440 * @throws IllegalStateException
441 * if set of rpcs from module is null
443 private void rpcMethodsToGenType(final Module module) {
444 checkArgument(module != null, "Module reference cannot be NULL.");
445 checkArgument(module.getName() != null, "Module name cannot be NULL.");
446 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
447 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
448 if (rpcDefinitions.isEmpty()) {
452 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
453 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
454 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
455 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
457 for (RpcDefinition rpc : rpcDefinitions) {
459 final String rpcName = BindingMapping.getClassName(rpc.getQName());
460 final String rpcMethodName = parseToValidParamName(rpcName);
461 final String rpcComment = rpc.getDescription();
462 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
463 final ContainerSchemaNode input = rpc.getInput();
464 final ContainerSchemaNode output = rpc.getOutput();
467 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
468 addImplementedInterfaceFromUses(input, inType);
469 inType.addImplementsType(DATA_OBJECT);
470 inType.addImplementsType(augmentable(inType));
471 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
472 genCtx.get(module).addChildNodeType(input, inType);
473 final GeneratedType inTypeInstance = inType.toInstance();
474 method.addParameter(inTypeInstance, "input");
477 Type outTypeInstance = VOID;
478 if (output != null) {
479 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
480 addImplementedInterfaceFromUses(output, outType);
481 outType.addImplementsType(DATA_OBJECT);
482 outType.addImplementsType(augmentable(outType));
483 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
484 genCtx.get(module).addChildNodeType(output, outType);
485 outTypeInstance = outType.toInstance();
488 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
489 method.setComment(rpcComment);
490 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
494 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
498 * Converts all <b>notifications</b> of the module to the list of
499 * <code>Type</code> objects. In addition are to this list added containers
500 * and lists which are part of this notification.
503 * module from which is obtained set of all notification objects
504 * to iterate over them
505 * @throws IllegalArgumentException
507 * <li>if the module equals null</li>
508 * <li>if the name of module equals null</li>
510 * @throws IllegalStateException
511 * if set of notifications from module is null
513 private void notificationsToGenType(final Module module) {
514 checkArgument(module != null, "Module reference cannot be NULL.");
515 checkArgument(module.getName() != null, "Module name cannot be NULL.");
516 final Set<NotificationDefinition> notifications = module.getNotifications();
517 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
518 if (notifications.isEmpty()) {
522 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
523 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
524 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
528 for (NotificationDefinition notification : notifications) {
529 if (notification != null) {
530 processUsesAugments(notification, module);
532 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
533 notification, BindingTypes.DATA_OBJECT);
534 notificationInterface.addImplementsType(NOTIFICATION);
535 genCtx.get(module).addChildNodeType(notification, notificationInterface);
537 // Notification object
538 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
539 notification.getChildNodes());
541 listenerInterface.addMethod("on" + notificationInterface.getName())
542 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
543 .setComment(notification.getDescription()).setReturnType(Types.VOID);
546 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
548 genCtx.get(module).addTopLevelNodeType(listenerInterface);
552 * Converts all <b>identities</b> of the module to the list of
553 * <code>Type</code> objects.
556 * module from which is obtained set of all identity objects to
559 * schema context only used as input parameter for method
560 * {@link identityToGenType}
563 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
564 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
565 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
567 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
568 for (IdentitySchemaNode identity : schemaIdentities) {
569 identityToGenType(module, basePackageName, identity, context);
575 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
576 * created transport object builder. If identity contains base identity then
577 * reference to base identity is added to superior identity as its extend.
578 * If identity doesn't contain base identity then only reference to abstract
579 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
580 * BaseIdentity} is added
584 * @param basePackageName
585 * string contains the module package name
587 * IdentitySchemaNode which contains data about identity
589 * SchemaContext which is used to get package and name
590 * information about base of identity
593 private void identityToGenType(final Module module, final String basePackageName,
594 final IdentitySchemaNode identity, final SchemaContext context) {
595 if (identity == null) {
598 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
599 final String genTypeName = BindingMapping.getClassName(identity.getQName());
600 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
601 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
602 if (baseIdentity == null) {
603 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
604 BaseIdentity.class.getSimpleName());
605 newType.setExtendsType(gto.toInstance());
607 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
608 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
610 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
611 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
613 newType.setExtendsType(gto);
615 newType.setAbstract(true);
616 newType.addComment(identity.getDescription());
617 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
618 newType.setReference(identity.getReference());
619 newType.setModuleName(module.getName());
620 SchemaPath path = identity.getPath();
621 newType.setSchemaPath(identity.getPath().getPathFromRoot());
623 final QName qname = identity.getQName();
624 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
626 genCtx.get(module).addIdentityType(identity.getQName(), newType);
629 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
631 StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
632 sb.append(".create(");
634 sb.append(name.getNamespace());
636 sb.append(name.getFormattedRevision());
638 sb.append(name.getLocalName());
641 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
645 * Converts all <b>groupings</b> of the module to the list of
646 * <code>Type</code> objects. Firstly are groupings sorted according mutual
647 * dependencies. At least dependent (independent) groupings are in the list
648 * saved at first positions. For every grouping the record is added to map
649 * {@link BindingGeneratorImpl#allGroupings allGroupings}
654 * of groupings from which types will be generated
657 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
658 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
659 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
661 for (GroupingDefinition grouping : groupingsSortedByDependencies) {
662 groupingToGenType(basePackageName, grouping, module);
667 * Converts individual grouping to GeneratedType. Firstly generated type
668 * builder is created and every child node of grouping is resolved to the
671 * @param basePackageName
672 * string contains the module package name
674 * GroupingDefinition which contains data about grouping
677 * @return GeneratedType which is generated from grouping (object of type
678 * <code>GroupingDefinition</code>)
680 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
681 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
682 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping);
683 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
684 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
685 groupingsToGenTypes(module, grouping.getGroupings());
686 processUsesAugments(grouping, module);
690 * Adds enumeration builder created from <code>enumTypeDef</code> to
691 * <code>typeBuilder</code>.
693 * Each <code>enumTypeDef</code> item is added to builder with its name and
697 * EnumTypeDefinition contains enum data
699 * string contains name which will be assigned to enumeration
702 * GeneratedTypeBuilder to which will be enum builder assigned
703 * @return enumeration builder which contains data from
704 * <code>enumTypeDef</code>
706 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
707 final GeneratedTypeBuilder typeBuilder) {
708 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
709 && (enumTypeDef.getQName().getLocalName() != null)) {
710 final String enumerationName = BindingMapping.getClassName(enumName);
711 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
712 enumBuilder.setDescription(enumTypeDef.getDescription());
713 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
720 * Generates type builder for <code>module</code>.
723 * Module which is source of package name for generated type
726 * string which is added to the module class name representation
728 * @return instance of GeneratedTypeBuilder which represents
729 * <code>module</code>.
730 * @throws IllegalArgumentException
731 * if <code>module</code> is null
733 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
734 checkArgument(module != null, "Module reference cannot be NULL.");
735 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
736 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
738 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
739 moduleBuilder.setDescription(createDescription(module));
740 moduleBuilder.setReference(module.getReference());
741 moduleBuilder.setModuleName(moduleName);
743 return moduleBuilder;
747 * Converts <code>augSchema</code> to list of <code>Type</code> which
748 * contains generated type for augmentation. In addition there are also
749 * generated types for all containers, list and choices which are child of
750 * <code>augSchema</code> node or a generated types for cases are added if
751 * augmented node is choice.
753 * @param augmentPackageName
754 * string with the name of the package to which the augmentation
757 * AugmentationSchema which is contains data about augmentation
758 * (target path, childs...)
761 * @param parentUsesNode
762 * @throws IllegalArgumentException
764 * <li>if <code>augmentPackageName</code> equals null</li>
765 * <li>if <code>augSchema</code> equals null</li>
767 * @throws IllegalStateException
768 * if augment target path is null
770 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
771 final Module module) {
772 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
773 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
774 checkState(augSchema.getTargetPath() != null,
775 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
777 processUsesAugments(augSchema, module);
778 final SchemaPath targetPath = augSchema.getTargetPath();
779 SchemaNode targetSchemaNode = null;
781 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
782 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
783 if (targetSchemaNode instanceof DerivableSchemaNode) {
784 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
786 if (targetSchemaNode == null) {
787 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
788 + " in module " + module.getName());
791 if (targetSchemaNode == null) {
792 throw new IllegalArgumentException("augment target not found: " + targetPath);
795 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
796 if (targetTypeBuilder == null) {
797 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
799 if (targetTypeBuilder == null) {
800 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
803 if (!(targetSchemaNode instanceof ChoiceNode)) {
804 String packageName = augmentPackageName;
805 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
806 targetTypeBuilder.getName());
807 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
810 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
811 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
815 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
816 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
817 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
818 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
819 checkState(augSchema.getTargetPath() != null,
820 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
822 processUsesAugments(augSchema, module);
823 final SchemaPath targetPath = augSchema.getTargetPath();
824 SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
825 if (targetSchemaNode == null) {
826 throw new IllegalArgumentException("augment target not found: " + targetPath);
829 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
830 if (targetTypeBuilder == null) {
831 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
833 if (targetTypeBuilder == null) {
834 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
837 if (!(targetSchemaNode instanceof ChoiceNode)) {
838 String packageName = augmentPackageName;
839 if (usesNodeParent instanceof SchemaNode) {
840 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
843 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
846 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
847 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
852 * Convenient method to find node added by uses statement.
856 * @param parentUsesNode
857 * parent of uses node
858 * @return node from its original location in grouping
860 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
861 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
863 if (!(targetGrouping instanceof GroupingDefinition)) {
864 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
867 GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
868 SchemaNode result = grouping;
869 for (QName node : targetPath.getPathFromRoot()) {
870 // finding by local name is valid, grouping cannot contain nodes
871 // with same name and different namespace
872 if (result instanceof DataNodeContainer) {
873 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
874 } else if (result instanceof ChoiceNode) {
875 result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
878 if (result == null) {
882 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
883 Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
884 while (groupingUses.hasNext() && fromUses) {
885 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
886 if (result != null) {
887 fromUses = ((DataSchemaNode) result).isAddedByUses();
891 // this indicates invalid yang and thus possible bug in code because
892 // invalid yang should be already spotted by parser
893 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
896 return (DataSchemaNode) result;
900 * Returns a generated type builder for an augmentation.
902 * The name of the type builder is equal to the name of augmented node with
903 * serial number as suffix.
907 * @param augmentPackageName
908 * string with contains the package name to which the augment
910 * @param basePackageName
911 * string with the package name to which the augmented node
913 * @param targetTypeRef
916 * augmentation schema which contains data about the child nodes
917 * and uses of augment
918 * @return generated type builder for augment
920 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
921 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
922 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
923 if (augmentBuilders == null) {
924 augmentBuilders = new HashMap<>();
925 genTypeBuilders.put(augmentPackageName, augmentBuilders);
927 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
930 if (augIdentifier != null) {
931 augTypeName = BindingMapping.getClassName(augIdentifier);
933 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
936 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
938 augTypeBuilder.addImplementsType(DATA_OBJECT);
939 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
940 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
942 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
943 augmentBuilders.put(augTypeName, augTypeBuilder);
945 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
946 genCtx.get(module).addAugmentType(augTypeBuilder);
947 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
948 return augTypeBuilder;
953 * @param unknownSchemaNodes
954 * @return nodeParameter of UnknownSchemaNode
956 private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
957 for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
958 final QName nodeType = unknownSchemaNode.getNodeType();
959 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
960 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
961 return unknownSchemaNode.getNodeParameter();
968 * Returns first unique name for the augment generated type builder. The
969 * generated type builder name for augment consists from name of augmented
970 * node and serial number of its augmentation.
973 * map of builders which were created in the package to which the
974 * augmentation belongs
976 * string with name of augmented node
977 * @return string with unique name for augmentation builder
979 private String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
981 if (builders != null) {
982 while (builders.containsKey(genTypeName + index)) {
986 return genTypeName + index;
990 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
991 * node for which <code>typeBuilder</code> was created.
993 * The subnodes aren't mapped to the methods if they are part of grouping or
994 * augment (in this case are already part of them).
998 * @param basePackageName
999 * string contains the module package name
1001 * generated type builder which represents any node. The subnodes
1002 * of this node are added to the <code>typeBuilder</code> as
1003 * methods. The subnode can be of type leaf, leaf-list, list,
1004 * container, choice.
1007 * @param schemaNodes
1008 * set of data schema nodes which are the children of the node
1009 * for which <code>typeBuilder</code> was created
1010 * @return generated type builder which is the same builder as input
1011 * parameter. The getter methods (representing child nodes) could be
1014 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1015 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1016 if (schemaNodes != null && parent != null) {
1017 for (DataSchemaNode schemaNode : schemaNodes) {
1018 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1019 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1027 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1028 * node for which <code>typeBuilder</code> was created.
1032 * @param basePackageName
1033 * string contains the module package name
1034 * @param typeBuilder
1035 * generated type builder which represents any node. The subnodes
1036 * of this node are added to the <code>typeBuilder</code> as
1037 * methods. The subnode can be of type leaf, leaf-list, list,
1038 * container, choice.
1041 * @param schemaNodes
1042 * set of data schema nodes which are the children of the node
1043 * for which <code>typeBuilder</code> was created
1044 * @return generated type builder which is the same object as the input
1045 * parameter <code>typeBuilder</code>. The getter method could be
1048 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1049 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1050 final Iterable<DataSchemaNode> schemaNodes) {
1051 if ((schemaNodes != null) && (typeBuilder != null)) {
1052 for (DataSchemaNode schemaNode : schemaNodes) {
1053 if (!schemaNode.isAugmenting()) {
1054 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1062 * Adds to <code>typeBuilder</code> a method which is derived from
1063 * <code>schemaNode</code>.
1065 * @param basePackageName
1066 * string with the module package name
1068 * data schema node which is added to <code>typeBuilder</code> as
1070 * @param typeBuilder
1071 * generated type builder to which is <code>schemaNode</code>
1072 * added as a method.
1078 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1079 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1080 if (node != null && typeBuilder != null) {
1081 if (node instanceof LeafSchemaNode) {
1082 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
1083 } else if (node instanceof LeafListSchemaNode) {
1084 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
1085 } else if (node instanceof ContainerSchemaNode) {
1086 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1087 } else if (node instanceof ListSchemaNode) {
1088 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1089 } else if (node instanceof ChoiceNode) {
1090 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
1092 // TODO: anyxml not yet supported
1093 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1094 typeBuilder.getFullyQualifiedName());
1100 * Converts <code>choiceNode</code> to the list of generated types for
1101 * choice and its cases.
1103 * The package names for choice and for its cases are created as
1104 * concatenation of the module package (<code>basePackageName</code>) and
1105 * names of all parents node.
1109 * @param basePackageName
1110 * string with the module package name
1114 * choice node which is mapped to generated type. Also child
1115 * nodes - cases are mapped to generated types.
1116 * @throws IllegalArgumentException
1118 * <li>if <code>basePackageName</code> is null</li>
1119 * <li>if <code>choiceNode</code> is null</li>
1122 private void choiceToGeneratedType(final Module module, final String basePackageName,
1123 final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
1124 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1125 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1127 if (!choiceNode.isAddedByUses()) {
1128 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1129 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1130 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1132 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1133 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1134 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1139 * Converts <code>caseNodes</code> set to list of corresponding generated
1142 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1143 * created generated type builder. The package names for the builder is
1144 * created as concatenation of the module package (
1145 * <code>basePackageName</code>) and names of all parents nodes of the
1146 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1147 * between every case builder and <i>choice</i> type
1151 * @param basePackageName
1152 * string with the module package name
1153 * @param refChoiceType
1154 * type which represents superior <i>case</i>
1156 * choice case node which is mapped to generated type
1157 * @return list of generated types for <code>caseNodes</code>.
1158 * @throws IllegalArgumentException
1160 * <li>if <code>basePackageName</code> equals null</li>
1161 * <li>if <code>refChoiceType</code> equals null</li>
1162 * <li>if <code>caseNodes</code> equals null</li>
1165 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1166 final Type refChoiceType, final ChoiceNode choiceNode) {
1167 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1168 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1169 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1171 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1172 if (caseNodes == null) {
1176 for (ChoiceCaseNode caseNode : caseNodes) {
1177 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1178 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1179 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
1180 caseTypeBuilder.addImplementsType(refChoiceType);
1181 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1182 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1183 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1184 if (caseChildNodes != null) {
1185 Object parentNode = null;
1186 final SchemaPath nodeSp = choiceNode.getPath();
1187 parentNode = findDataSchemaNode(schemaContext, nodeSp.getParent());
1190 if (parentNode instanceof AugmentationSchema) {
1191 final AugmentationSchema augSchema = (AugmentationSchema) parentNode;
1192 final SchemaPath targetPath = augSchema.getTargetPath();
1193 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1194 if (targetSchemaNode instanceof DataSchemaNode
1195 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1196 if (targetSchemaNode instanceof DerivableSchemaNode) {
1197 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1199 if (targetSchemaNode == null) {
1200 throw new IllegalStateException(
1201 "Failed to find target node from grouping for augmentation " + augSchema
1202 + " in module " + module.getName());
1205 parent = targetSchemaNode;
1207 final SchemaPath sp = choiceNode.getPath();
1208 parent = findDataSchemaNode(schemaContext, sp.getParent());
1210 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1211 if (childOfType == null) {
1212 childOfType = findGroupingByPath(parent.getPath());
1214 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1218 processUsesAugments(caseNode, module);
1223 * Generates list of generated types for all the cases of a choice which are
1224 * added to the choice through the augment.
1228 * @param basePackageName
1229 * string contains name of package to which augment belongs. If
1230 * an augmented choice is from an other package (pcg1) than an
1231 * augmenting choice (pcg2) then case's of the augmenting choice
1232 * will belong to pcg2.
1234 * Type which represents target choice
1236 * node which represents target choice
1237 * @param augmentedNodes
1238 * set of choice case nodes for which is checked if are/aren't
1239 * added to choice through augmentation
1240 * @return list of generated types which represents augmented cases of
1241 * choice <code>refChoiceType</code>
1242 * @throws IllegalArgumentException
1244 * <li>if <code>basePackageName</code> is null</li>
1245 * <li>if <code>targetType</code> is null</li>
1246 * <li>if <code>augmentedNodes</code> is null</li>
1249 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1250 final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1251 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1252 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1253 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1255 for (DataSchemaNode caseNode : augmentedNodes) {
1256 if (caseNode != null) {
1257 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1258 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
1259 caseTypeBuilder.addImplementsType(targetType);
1261 SchemaNode parent = null;
1262 final SchemaPath nodeSp = targetNode.getPath();
1263 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1265 GeneratedTypeBuilder childOfType = null;
1266 if (parent instanceof Module) {
1267 childOfType = genCtx.get(parent).getModuleNode();
1268 } else if (parent instanceof ChoiceCaseNode) {
1269 childOfType = findCaseByPath(parent.getPath());
1270 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1271 childOfType = findChildNodeByPath(parent.getPath());
1272 } else if (parent instanceof GroupingDefinition) {
1273 childOfType = findGroupingByPath(parent.getPath());
1276 if (childOfType == null) {
1277 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1280 ChoiceCaseNode node = null;
1281 if (caseNode instanceof ChoiceCaseNode) {
1282 node = (ChoiceCaseNode) caseNode;
1284 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1286 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1287 if (childNodes != null) {
1288 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1290 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1291 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1297 * Converts <code>leaf</code> to the getter method which is added to
1298 * <code>typeBuilder</code>.
1300 * @param typeBuilder
1301 * generated type builder to which is added getter method as
1302 * <code>leaf</code> mapping
1304 * leaf schema node which is mapped as getter method which is
1305 * added to <code>typeBuilder</code>
1306 * @return boolean value
1308 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1310 * <li>true - in other cases</li>
1313 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
1314 Type returnType = null;
1315 if ((leaf != null) && (typeBuilder != null)) {
1316 final String leafName = leaf.getQName().getLocalName();
1317 String leafDesc = leaf.getDescription();
1318 if (leafDesc == null) {
1322 final Module parentModule = findParentModule(schemaContext, leaf);
1323 if (leafName != null && !leaf.isAddedByUses()) {
1324 final TypeDefinition<?> typeDef = leaf.getType();
1326 GeneratedTOBuilder genTOBuilder;
1327 if (typeDef instanceof EnumTypeDefinition) {
1328 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1329 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1330 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1333 if (enumBuilder != null) {
1334 returnType = enumBuilder.toInstance(typeBuilder);
1336 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1337 } else if (typeDef instanceof UnionType) {
1338 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1339 if (genTOBuilder != null) {
1340 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1342 } else if (typeDef instanceof BitsTypeDefinition) {
1343 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1344 if (genTOBuilder != null) {
1345 returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
1348 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1349 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1351 if (returnType != null) {
1352 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1353 processContextRefExtension(leaf, getter, parentModule);
1360 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1361 final Module module) {
1362 for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1363 final QName nodeType = node.getNodeType();
1364 if ("context-reference".equals(nodeType.getLocalName())) {
1365 final String nodeParam = node.getNodeParameter();
1366 IdentitySchemaNode identity = null;
1367 String basePackageName = null;
1368 final Iterable<String> splittedElement = Splitter.on(':').split(nodeParam);
1369 final Iterator<String> iterator = splittedElement.iterator();
1370 final int length = Iterables.size(splittedElement);
1372 identity = findIdentityByName(module.getIdentities(), iterator.next());
1373 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1374 } else if (length == 2) {
1375 String prefix = iterator.next();
1376 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1377 if (dependentModule == null) {
1378 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1381 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1382 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1384 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1387 if (identity == null) {
1388 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1392 final Class<RoutingContext> clazz = RoutingContext.class;
1393 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1394 clazz.getSimpleName());
1395 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1396 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1397 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1402 private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1403 for (IdentitySchemaNode id : identities) {
1404 if (id.getQName().getLocalName().equals(name)) {
1411 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1412 for (ModuleImport imp : imports) {
1413 if (imp.getPrefix().equals(prefix)) {
1414 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1420 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1421 final boolean isReadOnly, final Module module) {
1422 if ((leaf != null) && (toBuilder != null)) {
1423 final String leafName = leaf.getQName().getLocalName();
1424 String leafDesc = leaf.getDescription();
1425 if (leafDesc == null) {
1429 if (leafName != null) {
1430 Type returnType = null;
1431 final TypeDefinition<?> typeDef = leaf.getType();
1432 if (typeDef instanceof UnionTypeDefinition) {
1433 // GeneratedType for this type definition should be already
1435 QName qname = typeDef.getQName();
1436 Module unionModule = null;
1437 String prefix = qname.getPrefix();
1438 if (prefix == null || prefix.isEmpty() || prefix.equals(module.getPrefix())) {
1439 unionModule = module;
1441 unionModule = findModuleFromImports(module.getImports(), qname.getPrefix());
1443 final ModuleContext mc = genCtx.get(unionModule);
1444 returnType = mc.getTypedefs().get(typeDef.getPath());
1446 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1448 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1455 * Converts <code>leaf</code> schema node to property of generated TO
1459 * generated TO builder to which is <code>leaf</code> added as
1462 * leaf schema node which is added to <code>toBuilder</code> as
1467 * boolean value which says if leaf property is|isn't read only
1468 * @return boolean value
1470 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1471 * name equals null or if leaf is added by <i>uses</i>.</li>
1472 * <li>true - other cases</li>
1475 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1476 final Type returnType, final boolean isReadOnly) {
1477 if (returnType == null) {
1480 final String leafName = leaf.getQName().getLocalName();
1481 final String leafDesc = leaf.getDescription();
1482 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(parseToValidParamName(leafName));
1483 propBuilder.setReadOnly(isReadOnly);
1484 propBuilder.setReturnType(returnType);
1485 propBuilder.setComment(leafDesc);
1486 toBuilder.addEqualsIdentity(propBuilder);
1487 toBuilder.addHashIdentity(propBuilder);
1488 toBuilder.addToStringProperty(propBuilder);
1493 * Converts <code>node</code> leaf list schema node to getter method of
1494 * <code>typeBuilder</code>.
1496 * @param typeBuilder
1497 * generated type builder to which is <code>node</code> added as
1500 * leaf list schema node which is added to
1501 * <code>typeBuilder</code> as getter method
1502 * @return boolean value
1504 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1505 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1506 * <li>false - other cases</li>
1509 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
1510 if ((node != null) && (typeBuilder != null)) {
1511 final QName nodeName = node.getQName();
1513 if (nodeName != null && !node.isAddedByUses()) {
1514 final TypeDefinition<?> typeDef = node.getType();
1515 final Module parentModule = findParentModule(schemaContext, node);
1517 Type returnType = null;
1518 if (typeDef instanceof EnumTypeDefinition) {
1519 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1520 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1521 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1523 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1524 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1525 } else if (typeDef instanceof UnionType) {
1526 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1527 if (genTOBuilder != null) {
1528 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1530 } else if (typeDef instanceof BitsTypeDefinition) {
1531 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1532 returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
1534 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1535 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1538 final ParameterizedType listType = Types.listTypeFor(returnType);
1539 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1546 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1547 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1548 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1549 genTOBuilder.getName());
1551 returnType.setDescription(typeDef.getDescription());
1552 returnType.setReference(typeDef.getReference());
1553 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1554 returnType.setModuleName(parentModule.getName());
1556 genTOBuilder.setTypedef(true);
1557 genTOBuilder.setIsUnion(true);
1558 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1561 final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
1562 genTOBuilder.getName() + "Builder");
1563 unionBuilder.setIsUnionBuilder(true);
1564 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1565 method.setReturnType(returnType);
1566 method.addParameter(Types.STRING, "defaultValue");
1567 method.setAccessModifier(AccessModifier.PUBLIC);
1568 method.setStatic(true);
1570 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1571 if (types == null) {
1572 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1573 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1575 types.add(unionBuilder.toInstance());
1577 return returnType.toInstance();
1580 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1581 return addDefaultInterfaceDefinition(packageName, schemaNode, null);
1585 * Instantiates generated type builder with <code>packageName</code> and
1586 * <code>schemaNode</code>.
1588 * The new builder always implements
1589 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br />
1590 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1591 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1592 * Augmentable}.<br />
1593 * If <code>schemaNode</code> is instance of
1594 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1595 * DataNodeContainer} it can also implement nodes which are specified in
1598 * @param packageName
1599 * string with the name of the package to which
1600 * <code>schemaNode</code> belongs.
1602 * schema node for which is created generated type builder
1604 * parent type (can be null)
1605 * @return generated type builder <code>schemaNode</code>
1607 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1608 final Type parent) {
1609 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1610 if (parent == null) {
1611 it.addImplementsType(DATA_OBJECT);
1613 it.addImplementsType(BindingTypes.childOf(parent));
1615 if (!(schemaNode instanceof GroupingDefinition)) {
1616 it.addImplementsType(augmentable(it));
1619 if (schemaNode instanceof DataNodeContainer) {
1620 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1627 * Wraps the calling of the same overloaded method.
1629 * @param packageName
1630 * string with the package name to which returning generated type
1633 * schema node which provide data about the schema node name
1634 * @return generated type builder for <code>schemaNode</code>
1636 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1637 return addRawInterfaceDefinition(packageName, schemaNode, "");
1641 * Returns reference to generated type builder for specified
1642 * <code>schemaNode</code> with <code>packageName</code>.
1644 * Firstly the generated type builder is searched in
1645 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1646 * found it is created and added to <code>genTypeBuilders</code>.
1648 * @param packageName
1649 * string with the package name to which returning generated type
1652 * schema node which provide data about the schema node name
1654 * return type name prefix
1655 * @return generated type builder for <code>schemaNode</code>
1656 * @throws IllegalArgumentException
1658 * <li>if <code>schemaNode</code> is null</li>
1659 * <li>if <code>packageName</code> is null</li>
1660 * <li>if QName of schema node is null</li>
1661 * <li>if schemaNode name is null</li>
1665 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1666 final String prefix) {
1667 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1668 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1669 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1670 final String schemaNodeName = schemaNode.getQName().getLocalName();
1671 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1674 if (prefix == null) {
1675 genTypeName = BindingMapping.getClassName(schemaNodeName);
1677 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1680 // FIXME: Validation of name conflict
1681 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1682 final Module module = findParentModule(schemaContext, schemaNode);
1683 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1684 newType.addComment(schemaNode.getDescription());
1685 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1686 newType.setReference(schemaNode.getReference());
1687 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1688 newType.setModuleName(module.getName());
1690 if (!genTypeBuilders.containsKey(packageName)) {
1691 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1692 builders.put(genTypeName, newType);
1693 genTypeBuilders.put(packageName, builders);
1695 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1696 if (!builders.containsKey(genTypeName)) {
1697 builders.put(genTypeName, newType);
1704 * Creates the name of the getter method name from <code>localName</code>.
1707 * string with the name of the getter method
1710 * @return string with the name of the getter method for
1711 * <code>methodName</code> in JAVA method format
1713 public static String getterMethodName(final String localName, final Type returnType) {
1714 final StringBuilder method = new StringBuilder();
1715 if (BOOLEAN.equals(returnType)) {
1716 method.append("is");
1718 method.append("get");
1720 String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1721 method.append(name);
1722 return method.toString();
1726 * Created a method signature builder as part of
1727 * <code>interfaceBuilder</code>.
1729 * The method signature builder is created for the getter method of
1730 * <code>schemaNodeName</code>. Also <code>comment</code> and
1731 * <code>returnType</code> information are added to the builder.
1733 * @param interfaceBuilder
1734 * generated type builder for which the getter method should be
1736 * @param schemaNodeName
1737 * string with schema node name. The name will be the part of the
1738 * getter method name.
1740 * string with comment for the getter method
1742 * type which represents the return type of the getter method
1743 * @return method signature builder which represents the getter method of
1744 * <code>interfaceBuilder</code>
1746 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1747 final String schemaNodeName, final String comment, final Type returnType) {
1748 final MethodSignatureBuilder getMethod = interfaceBuilder
1749 .addMethod(getterMethodName(schemaNodeName, returnType));
1750 getMethod.setComment(comment);
1751 getMethod.setReturnType(returnType);
1756 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1757 * or to <code>genTOBuilder</code> as property.
1759 * @param basePackageName
1760 * string contains the module package name
1762 * data schema node which should be added as getter method to
1763 * <code>typeBuilder</code> or as a property to
1764 * <code>genTOBuilder</code> if is part of the list key
1765 * @param typeBuilder
1766 * generated type builder for the list schema node
1767 * @param genTOBuilder
1768 * generated TO builder for the list keys
1770 * list of string which contains names of the list keys
1773 * @throws IllegalArgumentException
1775 * <li>if <code>schemaNode</code> equals null</li>
1776 * <li>if <code>typeBuilder</code> equals null</li>
1779 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1780 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1781 final Module module) {
1782 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1783 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1785 if (schemaNode instanceof LeafSchemaNode) {
1786 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1787 final String leafName = leaf.getQName().getLocalName();
1788 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf);
1789 if (listKeys.contains(leafName)) {
1791 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1793 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1796 } else if (!schemaNode.isAddedByUses()) {
1797 if (schemaNode instanceof LeafListSchemaNode) {
1798 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode);
1799 } else if (schemaNode instanceof ContainerSchemaNode) {
1800 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1801 } else if (schemaNode instanceof ChoiceNode) {
1802 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) schemaNode);
1803 } else if (schemaNode instanceof ListSchemaNode) {
1804 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1809 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1810 final GeneratedTOBuilder genTOBuilder) {
1811 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1813 if (genTOBuilder != null) {
1814 GeneratedTransferObject genTO = genTOBuilder.toInstance();
1815 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1816 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1821 * Selects the names of the list keys from <code>list</code> and returns
1822 * them as the list of the strings
1825 * of string with names of the list keys
1826 * @return list of string which represents names of the list keys. If the
1827 * <code>list</code> contains no keys then the empty list is
1830 private List<String> listKeys(final ListSchemaNode list) {
1831 final List<String> listKeys = new ArrayList<>();
1833 List<QName> keyDefinition = list.getKeyDefinition();
1834 if (keyDefinition != null) {
1835 for (QName keyDef : keyDefinition) {
1836 listKeys.add(keyDef.getLocalName());
1843 * Generates for the <code>list</code> which contains any list keys special
1844 * generated TO builder.
1846 * @param packageName
1847 * string with package name to which the list belongs
1849 * list schema node which is source of data about the list name
1850 * @return generated TO builder which represents the keys of the
1851 * <code>list</code> or null if <code>list</code> is null or list of
1852 * key definitions is null or empty.
1854 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1855 GeneratedTOBuilder genTOBuilder = null;
1856 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1857 final String listName = list.getQName().getLocalName() + "Key";
1858 final String genTOName = BindingMapping.getClassName(listName);
1859 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1861 return genTOBuilder;
1865 * Builds generated TO builders for <code>typeDef</code> of type
1866 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1867 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1868 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1869 * enclosing transfer object.
1871 * If more then one generated TO builder is created for enclosing then all
1872 * of the generated TO builders are added to <code>typeBuilder</code> as
1873 * enclosing transfer objects.
1876 * type definition which can be of type <code>UnionType</code> or
1877 * <code>BitsTypeDefinition</code>
1878 * @param typeBuilder
1879 * generated type builder to which is added generated TO created
1880 * from <code>typeDef</code>
1882 * string with name for generated TO builder
1884 * @return generated TO builder for <code>typeDef</code>
1886 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1887 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1888 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1889 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1890 final String packageName = typeBuilder.getFullyQualifiedName();
1891 if (typeDef instanceof UnionTypeDefinition) {
1892 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1893 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1894 classNameFromLeaf, leaf);
1895 genTOBuilders.addAll(types);
1897 GeneratedTOBuilder resultTOBuilder = null;
1898 if (!types.isEmpty()) {
1899 resultTOBuilder = types.remove(0);
1900 for (GeneratedTOBuilder genTOBuilder : types) {
1901 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1905 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1906 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
1907 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1908 resultTOBuilder.addHashIdentity(genPropBuilder);
1909 resultTOBuilder.addToStringProperty(genPropBuilder);
1911 } else if (typeDef instanceof BitsTypeDefinition) {
1912 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1913 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1915 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1916 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1917 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1919 return genTOBuilders.get(0);
1926 * Adds the implemented types to type builder.
1928 * The method passes through the list of <i>uses</i> in
1929 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1930 * generated type from {@link BindingGeneratorImpl#allGroupings
1931 * allGroupings} which is added as <i>implements type</i> to
1932 * <code>builder</code>
1934 * @param dataNodeContainer
1935 * element which contains the list of used YANG groupings
1937 * builder to which are added implemented types according to
1938 * <code>dataNodeContainer</code>
1939 * @return generated type builder with all implemented types
1941 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1942 final GeneratedTypeBuilder builder) {
1943 for (UsesNode usesNode : dataNodeContainer.getUses()) {
1944 if (usesNode.getGroupingPath() != null) {
1945 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1946 if (genType == null) {
1947 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1948 + builder.getName());
1951 builder.addImplementsType(genType);
1953 builder.addComment(genType.getDescription());
1954 builder.setDescription(genType.getDescription());
1955 builder.setModuleName(genType.getModuleName());
1956 builder.setReference(genType.getReference());
1957 builder.setSchemaPath(genType.getSchemaPath());
1964 private boolean isNullOrEmpty(final Collection<?> list) {
1965 return (list == null || list.isEmpty() ? true : false);
1968 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
1969 final StringBuilder sb = new StringBuilder();
1970 final String yangSnipet = YangTemplate.generateYangSnipet(schemaNodes);
1972 if (!isNullOrEmpty(schemaNodes)) {
1973 final SchemaNode node = schemaNodes.iterator().next();
1975 if (node instanceof RpcDefinition) {
1976 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
1978 else if (node instanceof NotificationDefinition) {
1979 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
1982 sb.append(NEW_LINE);
1983 sb.append("<br />(Source path: <i>");
1984 sb.append(moduleSourcePath);
1985 sb.append("</i>):");
1986 sb.append(NEW_LINE);
1988 sb.append(NEW_LINE);
1989 sb.append(yangSnipet);
1990 sb.append("</pre>");
1991 sb.append(NEW_LINE);
1993 return sb.toString();
1996 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
1997 final StringBuilder sb = new StringBuilder();
1998 final Module module = findParentModule(schemaContext, schemaNode);
1999 final String yangSnipet = YangTemplate.generateYangSnipet(schemaNode);
2000 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2001 final StringBuilder linkToBuilderClass = new StringBuilder();
2002 final StringBuilder linkToKeyClass = new StringBuilder();
2003 final Splitter splitter = Splitter.on("\\.");
2004 final String[] namespace = Iterables.toArray(splitter.split(fullyQualifiedName), String.class);
2005 String className = namespace[namespace.length - 1];
2007 if (hasBuilderClass(schemaNode)) {
2008 linkToBuilderClass.append(className);
2009 linkToBuilderClass.append("Builder");
2011 if (schemaNode instanceof ListSchemaNode) {
2012 linkToKeyClass.append(className);
2013 linkToKeyClass.append("Key");
2017 if (!isNullOrEmpty(formattedDescription)) {
2018 sb.append(formattedDescription);
2019 sb.append(NEW_LINE);
2022 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2023 sb.append(module.getName());
2025 sb.append(NEW_LINE);
2026 sb.append("<br />(Source path: <i>");
2027 sb.append(module.getModuleSourcePath());
2028 sb.append("</i>):");
2029 sb.append(NEW_LINE);
2031 sb.append(NEW_LINE);
2032 sb.append(yangSnipet);
2033 sb.append("</pre>");
2034 sb.append(NEW_LINE);
2035 sb.append("The schema path to identify an instance is");
2036 sb.append(NEW_LINE);
2038 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2040 sb.append(NEW_LINE);
2042 if (hasBuilderClass(schemaNode)) {
2043 sb.append(NEW_LINE);
2044 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2045 sb.append(NEW_LINE);
2047 sb.append(linkToBuilderClass);
2048 if (schemaNode instanceof ListSchemaNode) {
2050 sb.append(linkToKeyClass);
2052 sb.append(NEW_LINE);
2055 return sb.toString();
2058 private boolean hasBuilderClass(final SchemaNode schemaNode) {
2059 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2060 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition)
2065 private boolean isNullOrEmpty(final String string) {
2066 return (string == null || string.isEmpty() ? true : false);
2069 private String createDescription(final Module module) {
2070 final StringBuilder sb = new StringBuilder();
2071 final String yangSnipet = YangTemplate.generateYangSnipet(module);
2072 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2074 if (!isNullOrEmpty(formattedDescription)) {
2075 sb.append(formattedDescription);
2076 sb.append(NEW_LINE);
2079 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2080 sb.append(module.getName());
2082 sb.append(NEW_LINE);
2083 sb.append("<br />Source path: <i>");
2084 sb.append(module.getModuleSourcePath());
2085 sb.append("</i>):");
2086 sb.append(NEW_LINE);
2088 sb.append(NEW_LINE);
2089 sb.append(yangSnipet);
2090 sb.append("</pre>");
2092 return sb.toString();
2095 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2096 for (ModuleContext ctx : genCtx.values()) {
2097 GeneratedTypeBuilder result = ctx.getChildNode(path);
2098 if (result != null) {
2105 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2106 for (ModuleContext ctx : genCtx.values()) {
2107 GeneratedTypeBuilder result = ctx.getGrouping(path);
2108 if (result != null) {
2115 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2116 for (ModuleContext ctx : genCtx.values()) {
2117 GeneratedTypeBuilder result = ctx.getCase(path);
2118 if (result != null) {
2125 public Map<Module, ModuleContext> getModuleContexts() {