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.mdsal.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.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
23 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
24 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
25 import static org.opendaylight.mdsal.binding.model.util.Types.VOID;
26 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Optional;
33 import com.google.common.base.Preconditions;
34 import com.google.common.base.Splitter;
35 import com.google.common.base.Strings;
36 import com.google.common.collect.Iterables;
37 import com.google.common.collect.Sets;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Comparator;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.regex.Pattern;
47 import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
48 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
49 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
50 import org.opendaylight.mdsal.binding.model.api.Constant;
51 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
52 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
53 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
54 import org.opendaylight.mdsal.binding.model.api.Restrictions;
55 import org.opendaylight.mdsal.binding.model.api.Type;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
63 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
64 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
65 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
66 import org.opendaylight.mdsal.binding.model.util.Types;
67 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
68 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
69 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTypeBuilderImpl;
70 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
71 import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
72 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
73 import org.opendaylight.yangtools.yang.binding.BindingMapping;
74 import org.opendaylight.yangtools.yang.binding.DataContainer;
75 import org.opendaylight.yangtools.yang.binding.RpcService;
76 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
103 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
104 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
107 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
108 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
109 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
110 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
111 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 public class BindingGeneratorImpl implements BindingGenerator {
116 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
117 private static final Splitter COLON_SPLITTER = Splitter.on(':');
118 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
119 private static final char NEW_LINE = '\n';
122 * Comparator based on augment target path.
124 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
125 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
126 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
128 while (thisIt.hasNext()) {
129 if (!otherIt.hasNext()) {
133 final int comp = thisIt.next().compareTo(otherIt.next());
139 return otherIt.hasNext() ? -1 : 0;
143 * Constant with the concrete name of identifier.
145 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
148 * Constant with the concrete name of namespace.
150 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
152 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
154 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
157 * When set to true, generated classes will include javadoc comments which
158 * are useful for users.
160 private final boolean verboseClassComments;
163 * Outer key represents the package name. Outer value represents map of all
164 * builders in the same package. Inner key represents the schema node name
165 * (in JAVA class/interface name format). Inner value represents instance of
166 * builder for schema node specified in key part.
168 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
171 * Provide methods for converting YANG types to JAVA types.
173 private TypeProvider typeProvider;
176 * Holds reference to schema context to resolve data of augmented element
177 * when creating augmentation builder
179 private SchemaContext schemaContext;
182 * Create a new binding generator.
184 * @param verboseClassComments generate verbose comments
186 public BindingGeneratorImpl(final boolean verboseClassComments) {
187 this.verboseClassComments = verboseClassComments;
191 * Resolves generated types from <code>context</code> schema nodes of all
194 * Generated types are created for modules, groupings, types, containers,
195 * lists, choices, augments, rpcs, notification, identities.
198 * schema context which contains data about all schema nodes
200 * @return list of types (usually <code>GeneratedType</code>
201 * <code>GeneratedTransferObject</code>which are generated from
202 * <code>context</code> data.
203 * @throws IllegalArgumentException
204 * if arg <code>context</code> is null
205 * @throws IllegalStateException
206 * if <code>context</code> contain no modules
209 public List<Type> generateTypes(final SchemaContext context) {
210 checkArgument(context != null, "Schema Context reference cannot be NULL.");
211 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
212 schemaContext = context;
213 final Set<Module> modules = context.getModules();
214 return generateTypes(context, modules);
218 * Resolves generated types from <code>context</code> schema nodes only for
219 * modules specified in <code>modules</code>
221 * Generated types are created for modules, groupings, types, containers,
222 * lists, choices, augments, rpcs, notification, identities.
225 * schema context which contains data about all schema nodes
228 * set of modules for which schema nodes should be generated
230 * @return list of types (usually <code>GeneratedType</code> or
231 * <code>GeneratedTransferObject</code>) which:
233 * <li>are generated from <code>context</code> schema nodes and</li>
234 * <li>are also part of some of the module in <code>modules</code>
237 * @throws IllegalArgumentException
239 * <li>if arg <code>context</code> is null or</li>
240 * <li>if arg <code>modules</code> is null</li>
242 * @throws IllegalStateException
243 * if <code>context</code> contain no modules
246 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
247 checkArgument(context != null, "Schema Context reference cannot be NULL.");
248 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
249 checkArgument(modules != null, "Set of Modules cannot be NULL.");
251 schemaContext = context;
252 typeProvider = new TypeProviderImpl(context);
253 final List<Module> contextModules = ModuleDependencySort.sort(context.getModules());
254 genTypeBuilders = new HashMap<>();
256 for (final Module contextModule : contextModules) {
257 moduleToGenTypes(contextModule, context);
259 for (final Module contextModule : contextModules) {
260 allAugmentsToGenTypes(contextModule);
263 final List<Type> filteredGenTypes = new ArrayList<>();
264 for (final Module m : modules) {
265 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
266 filteredGenTypes.addAll(ctx.getGeneratedTypes());
267 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
268 if (additionalTypes != null) {
269 filteredGenTypes.addAll(additionalTypes);
273 return filteredGenTypes;
276 private void moduleToGenTypes(final Module m, final SchemaContext context) {
277 genCtx.put(m, new ModuleContext());
278 allTypeDefinitionsToGenTypes(m);
279 groupingsToGenTypes(m, m.getGroupings());
280 rpcMethodsToGenType(m);
281 allIdentitiesToGenTypes(m, context);
282 notificationsToGenType(m);
284 if (!m.getChildNodes().isEmpty()) {
285 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
286 genCtx.get(m).addModuleNode(moduleType);
287 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
288 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
293 * Converts all extended type definitions of module to the list of
294 * <code>Type</code> objects.
297 * module from which is obtained set of type definitions
298 * @throws IllegalArgumentException
300 * <li>if module is null</li>
301 * <li>if name of module is null</li>
303 * @throws IllegalStateException
304 * if set of type definitions from module is null
306 private void allTypeDefinitionsToGenTypes(final Module module) {
307 checkArgument(module != null, "Module reference cannot be NULL.");
308 checkArgument(module.getName() != null, "Module name cannot be NULL.");
309 final DataNodeIterator it = new DataNodeIterator(module);
310 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
311 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
313 for (final TypeDefinition<?> typedef : typeDefinitions) {
314 if (typedef != null) {
315 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
318 final ModuleContext ctx = genCtx.get(module);
319 ctx.addTypedefType(typedef.getPath(), type);
320 ctx.addTypeToSchema(type,typedef);
326 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
327 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
328 if (node.isAugmenting() || node.isAddedByUses()) {
331 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
332 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
333 genType.addComment(node.getDescription());
334 annotateDeprecatedIfNecessary(node.getStatus(), genType);
335 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
336 genType.setModuleName(module.getName());
337 genType.setReference(node.getReference());
338 genType.setSchemaPath(node.getPath().getPathFromRoot());
339 if (node instanceof DataNodeContainer) {
340 genCtx.get(module).addChildNodeType(node, genType);
341 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
342 processUsesAugments((DataNodeContainer) node, module);
347 private void containerToGenType(final Module module, final String basePackageName,
348 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
349 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
350 if (genType != null) {
351 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
352 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
356 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
357 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
358 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
359 if (genType != null) {
360 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
361 Types.listTypeFor(genType), node.getStatus());
363 final List<String> listKeys = listKeys(node);
364 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
365 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
366 if (genTOBuilder != null) {
367 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
368 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
369 genTOBuilder.addImplementsType(identifierMarker);
370 genType.addImplementsType(identifiableMarker);
373 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
374 if (!schemaNode.isAugmenting()) {
375 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
380 if (genTOBuilder != null) {
381 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
382 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
383 genTOBuilder.setSUID(prop);
386 typeBuildersToGenTypes(module, genType, genTOBuilder);
390 private void processUsesAugments(final DataNodeContainer node, final Module module) {
391 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
392 for (final UsesNode usesNode : node.getUses()) {
393 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
394 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
395 processUsesAugments(augment, module);
401 * Converts all <b>augmentation</b> of the module to the list
402 * <code>Type</code> objects.
405 * module from which is obtained list of all augmentation objects
406 * to iterate over them
407 * @throws IllegalArgumentException
409 * <li>if the module is null</li>
410 * <li>if the name of module is null</li>
412 * @throws IllegalStateException
413 * if set of augmentations from module is null
415 private void allAugmentsToGenTypes(final Module module) {
416 checkArgument(module != null, "Module reference cannot be NULL.");
417 checkArgument(module.getName() != null, "Module name cannot be NULL.");
418 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
420 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
421 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
422 for (final AugmentationSchema augment : augmentations) {
423 augmentationToGenTypes(basePackageName, augment, module);
428 * Returns list of <code>AugmentationSchema</code> objects. The objects are
429 * sorted according to the length of their target path from the shortest to
433 * module from which is obtained list of all augmentation objects
434 * @return list of sorted <code>AugmentationSchema</code> objects obtained
435 * from <code>module</code>
436 * @throws IllegalArgumentException
438 * @throws IllegalStateException
439 * if set of module augmentations is null
441 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
442 checkArgument(module != null, "Module reference cannot be NULL.");
443 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
445 final Set<AugmentationSchema> augmentations = module.getAugmentations();
446 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
447 sortedAugmentations.sort(AUGMENT_COMP);
449 return sortedAugmentations;
453 * Create GeneratedTypeBuilder object from module argument.
456 * Module object from which builder will be created
457 * @return <code>GeneratedTypeBuilder</code> which is internal
458 * representation of the module
459 * @throws IllegalArgumentException
462 private GeneratedTypeBuilder moduleToDataType(final Module module) {
463 checkArgument(module != null, "Module reference cannot be NULL.");
465 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
466 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
467 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
468 moduleDataTypeBuilder.addComment(module.getDescription());
469 moduleDataTypeBuilder.setDescription(createDescription(module));
470 moduleDataTypeBuilder.setReference(module.getReference());
471 return moduleDataTypeBuilder;
475 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
476 * to the list of <code>Type</code> objects. In addition are to containers
477 * and lists which belong to input or output also part of returning list.
480 * module from which is obtained set of all rpc objects to
482 * @throws IllegalArgumentException
484 * <li>if the module is null</li>
485 * <li>if the name of module is null</li>
487 * @throws IllegalStateException
488 * if set of rpcs from module is null
490 private void rpcMethodsToGenType(final Module module) {
491 checkArgument(module != null, "Module reference cannot be NULL.");
492 checkArgument(module.getName() != null, "Module name cannot be NULL.");
493 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
494 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
495 if (rpcDefinitions.isEmpty()) {
499 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
500 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
501 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
502 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
504 for (final RpcDefinition rpc : rpcDefinitions) {
506 final String rpcName = BindingMapping.getClassName(rpc.getQName());
507 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
508 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
509 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
510 final ContainerSchemaNode input = rpc.getInput();
511 final ContainerSchemaNode output = rpc.getOutput();
513 // Do not refer to annotation class, as it may not be available at runtime
514 method.addAnnotation("javax.annotation", "CheckReturnValue");
516 //in case of implicit RPC input (StatementSource.CONTEXT),
517 // stay compatible (no input argument generated)
518 if (input != null && isExplicitStatement(input)) {
519 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
520 addImplementedInterfaceFromUses(input, inType);
521 inType.addImplementsType(DATA_OBJECT);
522 inType.addImplementsType(augmentable(inType));
523 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
524 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
525 genCtx.get(module).addChildNodeType(input, inType);
526 final GeneratedType inTypeInstance = inType.toInstance();
527 method.addParameter(inTypeInstance, "input");
530 Type outTypeInstance = VOID;
531 //in case of implicit RPC output (StatementSource.CONTEXT),
532 //stay compatible (Future<RpcResult<Void>> return type generated)
533 if (output != null && isExplicitStatement(output)) {
534 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
535 addImplementedInterfaceFromUses(output, outType);
536 outType.addImplementsType(DATA_OBJECT);
537 outType.addImplementsType(augmentable(outType));
538 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
539 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
540 genCtx.get(module).addChildNodeType(output, outType);
541 outTypeInstance = outType.toInstance();
544 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
545 method.setComment(rpcComment);
546 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
550 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
553 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
554 return node instanceof EffectiveStatement
555 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
559 * Converts all <b>notifications</b> of the module to the list of
560 * <code>Type</code> objects. In addition are to this list added containers
561 * and lists which are part of this notification.
564 * module from which is obtained set of all notification objects
565 * to iterate over them
566 * @throws IllegalArgumentException
568 * <li>if the module equals null</li>
569 * <li>if the name of module equals null</li>
571 * @throws IllegalStateException
572 * if set of notifications from module is null
574 private void notificationsToGenType(final Module module) {
575 checkArgument(module != null, "Module reference cannot be NULL.");
576 checkArgument(module.getName() != null, "Module name cannot be NULL.");
577 final Set<NotificationDefinition> notifications = module.getNotifications();
578 if (notifications.isEmpty()) {
582 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
583 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
584 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
588 for (final NotificationDefinition notification : notifications) {
589 if (notification != null) {
590 processUsesAugments(notification, module);
592 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
593 notification, null, module);
594 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
595 notificationInterface.addImplementsType(NOTIFICATION);
596 genCtx.get(module).addChildNodeType(notification, notificationInterface);
598 // Notification object
599 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
600 notification.getChildNodes());
602 listenerInterface.addMethod("on" + notificationInterface.getName())
603 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
604 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
607 listenerInterface.setDescription(createDescription(notifications, module.getName()));
609 genCtx.get(module).addTopLevelNodeType(listenerInterface);
613 * Converts all <b>identities</b> of the module to the list of
614 * <code>Type</code> objects.
617 * module from which is obtained set of all identity objects to
620 * schema context only used as input parameter for method
621 * {@link BindingGeneratorImpl#identityToGenType}
624 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
625 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
626 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
628 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
629 for (final IdentitySchemaNode identity : schemaIdentities) {
630 identityToGenType(module, basePackageName, identity, context);
636 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
637 * created transport object builder. If identity contains base identity then
638 * reference to base identity is added to superior identity as its extend.
639 * If identity doesn't contain base identity then only reference to abstract
640 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
641 * BaseIdentity} is added
645 * @param basePackageName
646 * string contains the module package name
648 * IdentitySchemaNode which contains data about identity
650 * SchemaContext which is used to get package and name
651 * information about base of identity
654 private void identityToGenType(final Module module, final String basePackageName,
655 final IdentitySchemaNode identity, final SchemaContext context) {
656 if (identity == null) {
659 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
660 final String genTypeName = BindingMapping.getClassName(identity.getQName());
661 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
662 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
663 if (baseIdentity == null) {
664 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
665 BaseIdentity.class.getSimpleName());
666 newType.setExtendsType(gto.toInstance());
668 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
669 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
671 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
672 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
674 newType.setExtendsType(gto);
676 newType.setAbstract(true);
677 newType.addComment(identity.getDescription());
678 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
679 newType.setReference(identity.getReference());
680 newType.setModuleName(module.getName());
681 newType.setSchemaPath(identity.getPath().getPathFromRoot());
683 final QName qname = identity.getQName();
684 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
686 genCtx.get(module).addIdentityType(identity.getQName(), newType);
689 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
691 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
695 * Converts all <b>groupings</b> of the module to the list of
696 * <code>Type</code> objects. Firstly are groupings sorted according mutual
697 * dependencies. At least dependent (independent) groupings are in the list
698 * saved at first positions. For every grouping the record is added to map
699 * {@link ModuleContext#groupings allGroupings}
704 * collection of groupings from which types will be generated
707 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
708 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
709 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
711 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
712 groupingToGenType(basePackageName, grouping, module);
717 * Converts individual grouping to GeneratedType. Firstly generated type
718 * builder is created and every child node of grouping is resolved to the
721 * @param basePackageName
722 * string contains the module package name
724 * GroupingDefinition which contains data about grouping
728 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
729 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
730 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
731 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
732 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
733 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
734 groupingsToGenTypes(module, grouping.getGroupings());
735 processUsesAugments(grouping, module);
739 * Adds enumeration builder created from <code>enumTypeDef</code> to
740 * <code>typeBuilder</code>.
742 * Each <code>enumTypeDef</code> item is added to builder with its name and
746 * EnumTypeDefinition contains enum data
748 * string contains name which will be assigned to enumeration
751 * GeneratedTypeBuilder to which will be enum builder assigned
753 * Module in which type should be generated
754 * @return enumeration builder which contains data from
755 * <code>enumTypeDef</code>
757 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
758 final GeneratedTypeBuilder typeBuilder, final Module module) {
759 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
760 final String enumerationName = BindingMapping.getClassName(enumName);
761 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
762 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
763 enumBuilder.setDescription(enumTypedefDescription);
764 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
765 ModuleContext ctx = genCtx.get(module);
766 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
773 * Generates type builder for <code>module</code>.
776 * Module which is source of package name for generated type
779 * string which is added to the module class name representation
781 * @return instance of GeneratedTypeBuilder which represents
782 * <code>module</code>.
783 * @throws IllegalArgumentException
784 * if <code>module</code> is null
786 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
787 checkArgument(module != null, "Module reference cannot be NULL.");
788 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
789 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
791 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
792 moduleBuilder.setDescription(createDescription(module));
793 moduleBuilder.setReference(module.getReference());
794 moduleBuilder.setModuleName(moduleName);
796 return moduleBuilder;
800 * Converts <code>augSchema</code> to list of <code>Type</code> which
801 * contains generated type for augmentation. In addition there are also
802 * generated types for all containers, list and choices which are child of
803 * <code>augSchema</code> node or a generated types for cases are added if
804 * augmented node is choice.
806 * @param augmentPackageName
807 * string with the name of the package to which the augmentation
810 * AugmentationSchema which is contains data about augmentation
811 * (target path, childs...)
814 * @throws IllegalArgumentException
816 * <li>if <code>augmentPackageName</code> equals null</li>
817 * <li>if <code>augSchema</code> equals null</li>
819 * @throws IllegalStateException
820 * if augment target path is null
822 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
823 final Module module) {
824 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
825 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
826 checkState(augSchema.getTargetPath() != null,
827 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
829 processUsesAugments(augSchema, module);
830 final SchemaPath targetPath = augSchema.getTargetPath();
831 SchemaNode targetSchemaNode = null;
833 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
834 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
835 if (targetSchemaNode instanceof DerivableSchemaNode) {
836 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
838 if (targetSchemaNode == null) {
839 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
840 + " in module " + module.getName());
843 if (targetSchemaNode == null) {
844 throw new IllegalArgumentException("augment target not found: " + targetPath);
847 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
848 if (targetTypeBuilder == null) {
849 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
851 if (targetTypeBuilder == null) {
852 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
855 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
856 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
857 targetTypeBuilder.getName());
858 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
861 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
862 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
866 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
867 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
868 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
869 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
870 checkState(augSchema.getTargetPath() != null,
871 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
873 processUsesAugments(augSchema, module);
874 final SchemaPath targetPath = augSchema.getTargetPath();
875 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
876 if (targetSchemaNode == null) {
877 throw new IllegalArgumentException("augment target not found: " + targetPath);
880 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
881 if (targetTypeBuilder == null) {
882 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
884 if (targetTypeBuilder == null) {
885 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
888 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
889 String packageName = augmentPackageName;
890 if (usesNodeParent instanceof SchemaNode) {
891 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
893 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
896 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
897 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
902 * Convenient method to find node added by uses statement.
906 * @param parentUsesNode
907 * parent of uses node
908 * @return node from its original location in grouping
910 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
911 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
913 if (!(targetGrouping instanceof GroupingDefinition)) {
914 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
917 SchemaNode result = targetGrouping;
918 for (final QName node : targetPath.getPathFromRoot()) {
919 if (result instanceof DataNodeContainer) {
920 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
921 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
922 } else if (result instanceof ChoiceSchemaNode) {
923 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
926 if (result == null) {
930 if (result instanceof DerivableSchemaNode) {
931 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
932 Optional<? extends SchemaNode> originalNode = castedResult
934 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
935 result = originalNode.get();
939 if (result instanceof DataSchemaNode) {
940 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
941 if (resultDataSchemaNode.isAddedByUses()) {
942 // The original node is required, but we have only the copy of
943 // the original node.
944 // Maybe this indicates a bug in Yang parser.
945 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
948 return resultDataSchemaNode;
951 throw new IllegalStateException(
952 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
957 * Returns a generated type builder for an augmentation.
959 * The name of the type builder is equal to the name of augmented node with
960 * serial number as suffix.
964 * @param augmentPackageName
965 * string with contains the package name to which the augment
967 * @param basePackageName
968 * string with the package name to which the augmented node
970 * @param targetTypeRef
973 * augmentation schema which contains data about the child nodes
974 * and uses of augment
975 * @return generated type builder for augment
977 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
978 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
979 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
980 if (augmentBuilders == null) {
981 augmentBuilders = new HashMap<>();
982 genTypeBuilders.put(augmentPackageName, augmentBuilders);
984 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
987 if (augIdentifier != null) {
988 augTypeName = BindingMapping.getClassName(augIdentifier);
990 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
993 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
995 augTypeBuilder.addImplementsType(DATA_OBJECT);
996 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
997 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
998 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1000 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1001 augmentBuilders.put(augTypeName, augTypeBuilder);
1003 if (!augSchema.getChildNodes().isEmpty()) {
1004 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1007 genCtx.get(module).addAugmentType(augTypeBuilder);
1008 return augTypeBuilder;
1013 * @param unknownSchemaNodes
1014 * @return nodeParameter of UnknownSchemaNode
1016 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1017 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1018 final QName nodeType = unknownSchemaNode.getNodeType();
1019 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1020 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1021 return unknownSchemaNode.getNodeParameter();
1028 * Returns first unique name for the augment generated type builder. The
1029 * generated type builder name for augment consists from name of augmented
1030 * node and serial number of its augmentation.
1033 * map of builders which were created in the package to which the
1034 * augmentation belongs
1035 * @param genTypeName
1036 * string with name of augmented node
1037 * @return string with unique name for augmentation builder
1039 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1041 if (builders != null) {
1042 while (builders.containsKey(genTypeName + index)) {
1046 return genTypeName + index;
1050 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1051 * node for which <code>typeBuilder</code> was created.
1053 * The subnodes aren't mapped to the methods if they are part of grouping or
1054 * augment (in this case are already part of them).
1058 * @param basePackageName
1059 * string contains the module package name
1061 * generated type builder which represents any node. The subnodes
1062 * of this node are added to the <code>typeBuilder</code> as
1063 * methods. The subnode can be of type leaf, leaf-list, list,
1064 * container, choice.
1067 * @param schemaNodes
1068 * set of data schema nodes which are the children of the node
1069 * for which <code>typeBuilder</code> was created
1070 * @return generated type builder which is the same builder as input
1071 * parameter. The getter methods (representing child nodes) could be
1074 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1075 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1076 if (schemaNodes != null && parent != null) {
1077 for (final DataSchemaNode schemaNode : schemaNodes) {
1078 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1079 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1087 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1088 * node for which <code>typeBuilder</code> was created.
1092 * @param basePackageName
1093 * string contains the module package name
1094 * @param typeBuilder
1095 * generated type builder which represents any node. The subnodes
1096 * of this node are added to the <code>typeBuilder</code> as
1097 * methods. The subnode can be of type leaf, leaf-list, list,
1098 * container, choice.
1101 * @param schemaNodes
1102 * set of data schema nodes which are the children of the node
1103 * for which <code>typeBuilder</code> was created
1104 * @return generated type builder which is the same object as the input
1105 * parameter <code>typeBuilder</code>. The getter method could be
1108 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1109 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1110 final Iterable<DataSchemaNode> schemaNodes) {
1111 if (schemaNodes != null && typeBuilder != null) {
1112 for (final DataSchemaNode schemaNode : schemaNodes) {
1113 if (!schemaNode.isAugmenting()) {
1114 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1122 * Adds to <code>typeBuilder</code> a method which is derived from
1123 * <code>schemaNode</code>.
1125 * @param basePackageName
1126 * string with the module package name
1128 * data schema node which is added to <code>typeBuilder</code> as
1130 * @param typeBuilder
1131 * generated type builder to which is <code>schemaNode</code>
1132 * added as a method.
1138 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1139 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1140 if (node != null && typeBuilder != null) {
1141 if (node instanceof LeafSchemaNode) {
1142 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1143 } else if (node instanceof LeafListSchemaNode) {
1144 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1145 } else if (node instanceof ContainerSchemaNode) {
1146 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1147 } else if (node instanceof ListSchemaNode) {
1148 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1149 } else if (node instanceof ChoiceSchemaNode) {
1150 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1152 // TODO: anyxml not yet supported
1153 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1154 typeBuilder.getFullyQualifiedName());
1160 * Converts <code>choiceNode</code> to the list of generated types for
1161 * choice and its cases.
1163 * The package names for choice and for its cases are created as
1164 * concatenation of the module package (<code>basePackageName</code>) and
1165 * names of all parents node.
1169 * @param basePackageName
1170 * string with the module package name
1174 * choice node which is mapped to generated type. Also child
1175 * nodes - cases are mapped to generated types.
1176 * @throws IllegalArgumentException
1178 * <li>if <code>basePackageName</code> is null</li>
1179 * <li>if <code>choiceNode</code> is null</li>
1182 private void choiceToGeneratedType(final Module module, final String basePackageName,
1183 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1184 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1185 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1187 if (!choiceNode.isAddedByUses()) {
1188 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1189 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1190 constructGetter(parent, choiceNode.getQName().getLocalName(),
1191 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1192 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1193 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1194 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1195 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1200 * Converts <code>caseNodes</code> set to list of corresponding generated
1203 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1204 * created generated type builder. The package names for the builder is
1205 * created as concatenation of the module package (
1206 * <code>basePackageName</code>) and names of all parents nodes of the
1207 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1208 * between every case builder and <i>choice</i> type
1212 * @param basePackageName
1213 * string with the module package name
1214 * @param refChoiceType
1215 * type which represents superior <i>case</i>
1217 * choice case node which is mapped to generated type
1218 * @throws IllegalArgumentException
1220 * <li>if <code>basePackageName</code> equals null</li>
1221 * <li>if <code>refChoiceType</code> equals null</li>
1222 * <li>if <code>caseNodes</code> equals null</li>
1225 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1226 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1227 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1228 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1229 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1231 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1232 if (caseNodes == null) {
1236 for (final ChoiceCaseNode caseNode : caseNodes) {
1237 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1238 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1239 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1240 caseTypeBuilder.addImplementsType(refChoiceType);
1241 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1242 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1243 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1244 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1245 if (caseChildNodes != null) {
1246 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1248 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1249 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1251 if (parent instanceof AugmentationSchema) {
1252 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1253 final SchemaPath targetPath = augSchema.getTargetPath();
1254 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1255 if (targetSchemaNode instanceof DataSchemaNode
1256 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1260 if (targetSchemaNode == null) {
1261 throw new IllegalStateException(
1262 "Failed to find target node from grouping for augmentation " + augSchema
1263 + " in module " + module.getName());
1266 parent = targetSchemaNode;
1269 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1270 choiceNodeParentPath);
1271 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1272 if (childOfType == null) {
1273 childOfType = findGroupingByPath(parent.getPath());
1275 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1277 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1282 processUsesAugments(caseNode, module);
1287 * Generates list of generated types for all the cases of a choice which are
1288 * added to the choice through the augment.
1292 * @param basePackageName
1293 * string contains name of package to which augment belongs. If
1294 * an augmented choice is from an other package (pcg1) than an
1295 * augmenting choice (pcg2) then case's of the augmenting choice
1296 * will belong to pcg2.
1298 * Type which represents target choice
1300 * node which represents target choice
1301 * @param augmentedNodes
1302 * set of choice case nodes for which is checked if are/aren't
1303 * added to choice through augmentation
1304 * @throws IllegalArgumentException
1306 * <li>if <code>basePackageName</code> is null</li>
1307 * <li>if <code>targetType</code> is null</li>
1308 * <li>if <code>augmentedNodes</code> is null</li>
1311 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1312 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1313 final DataNodeContainer usesNodeParent) {
1314 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1315 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1316 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1318 for (final DataSchemaNode caseNode : augmentedNodes) {
1319 if (caseNode != null) {
1320 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1321 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1322 caseTypeBuilder.addImplementsType(targetType);
1325 final SchemaPath nodeSp = targetNode.getPath();
1326 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1328 GeneratedTypeBuilder childOfType = null;
1329 if (parent instanceof Module) {
1330 childOfType = genCtx.get(parent).getModuleNode();
1331 } else if (parent instanceof ChoiceCaseNode) {
1332 childOfType = findCaseByPath(parent.getPath());
1333 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1334 childOfType = findChildNodeByPath(parent.getPath());
1335 } else if (parent instanceof GroupingDefinition) {
1336 childOfType = findGroupingByPath(parent.getPath());
1339 if (childOfType == null) {
1340 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1343 ChoiceCaseNode node = null;
1344 final String caseLocalName = caseNode.getQName().getLocalName();
1345 if (caseNode instanceof ChoiceCaseNode) {
1346 node = (ChoiceCaseNode) caseNode;
1347 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1348 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1349 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1350 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1351 ().getLocalName())) {
1352 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1357 node = targetNode.getCaseNodeByName(caseLocalName);
1359 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1360 if (childNodes != null) {
1361 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1363 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1364 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1369 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1370 // New parser with encapsulated type
1371 if (leaf.getPath().equals(type.getPath())) {
1375 // Embedded type definition with new parser. Also takes care of the old parser with bits
1376 if (leaf.getPath().equals(type.getPath().getParent())) {
1384 * Converts <code>leaf</code> to the getter method which is added to
1385 * <code>typeBuilder</code>.
1387 * @param typeBuilder
1388 * generated type builder to which is added getter method as
1389 * <code>leaf</code> mapping
1391 * leaf schema node which is mapped as getter method which is
1392 * added to <code>typeBuilder</code>
1394 * Module in which type was defined
1395 * @return boolean value
1397 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1399 * <li>true - in other cases</li>
1402 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1403 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1407 final String leafName = leaf.getQName().getLocalName();
1408 if (leafName == null) {
1412 final Module parentModule = findParentModule(schemaContext, leaf);
1413 Type returnType = null;
1415 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1416 if (isInnerType(leaf, typeDef)) {
1417 if (typeDef instanceof EnumTypeDefinition) {
1418 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1419 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1420 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1421 typeBuilder, module);
1422 if (enumBuilder != null) {
1423 returnType = enumBuilder.toInstance(typeBuilder);
1425 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1426 } else if (typeDef instanceof UnionTypeDefinition) {
1427 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1428 if (genTOBuilder != null) {
1429 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1431 } else if (typeDef instanceof BitsTypeDefinition) {
1432 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1433 if (genTOBuilder != null) {
1434 returnType = genTOBuilder.toInstance();
1437 // It is constrained version of already declared type (inner declared type exists,
1438 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1439 // In order to get proper class we need to look up closest derived type
1440 // and apply restrictions from leaf type
1441 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1442 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1446 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1447 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1450 if (returnType == null) {
1454 if (typeDef instanceof EnumTypeDefinition) {
1455 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1458 String leafDesc = leaf.getDescription();
1459 if (leafDesc == null) {
1463 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1464 processContextRefExtension(leaf, getter, parentModule);
1468 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1469 // Returns DerivedType in case of new parser.
1470 final TypeDefinition<?> baseType = typeDef.getBaseType();
1471 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1474 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1475 final Module module) {
1476 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1477 final QName nodeType = node.getNodeType();
1478 if ("context-reference".equals(nodeType.getLocalName())) {
1479 final String nodeParam = node.getNodeParameter();
1480 IdentitySchemaNode identity = null;
1481 String basePackageName = null;
1482 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1483 final Iterator<String> iterator = splittedElement.iterator();
1484 final int length = Iterables.size(splittedElement);
1486 identity = findIdentityByName(module.getIdentities(), iterator.next());
1487 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1488 } else if (length == 2) {
1489 final String prefix = iterator.next();
1490 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1491 if (dependentModule == null) {
1492 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1495 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1496 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1498 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1501 if (identity == null) {
1502 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1506 final Class<RoutingContext> clazz = RoutingContext.class;
1507 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1508 clazz.getSimpleName());
1509 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1510 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1511 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1516 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1517 for (final IdentitySchemaNode id : identities) {
1518 if (id.getQName().getLocalName().equals(name)) {
1525 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1526 for (final ModuleImport imp : imports) {
1527 if (imp.getPrefix().equals(prefix)) {
1528 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1534 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1535 final boolean isReadOnly, final Module module) {
1536 if (leaf != null && toBuilder != null) {
1538 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1539 if (typeDef instanceof UnionTypeDefinition) {
1540 // GeneratedType for this type definition should be already
1542 final QName qname = typeDef.getQName();
1543 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1544 qname.getRevision());
1545 final ModuleContext mc = genCtx.get(unionModule);
1546 returnType = mc.getTypedefs().get(typeDef.getPath());
1547 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1548 // Annonymous enumeration (already generated, since it is inherited via uses).
1549 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1550 QName qname = originalLeaf.getQName();
1551 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1552 qname.getRevision());
1553 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1555 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1557 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1563 * Converts <code>leaf</code> schema node to property of generated TO
1567 * generated TO builder to which is <code>leaf</code> added as
1570 * leaf schema node which is added to <code>toBuilder</code> as
1575 * boolean value which says if leaf property is|isn't read only
1576 * @return boolean value
1578 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1579 * name equals null or if leaf is added by <i>uses</i>.</li>
1580 * <li>true - other cases</li>
1583 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1584 final Type returnType, final boolean isReadOnly) {
1585 if (returnType == null) {
1588 final String leafName = leaf.getQName().getLocalName();
1589 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1590 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1591 propBuilder.setReadOnly(isReadOnly);
1592 propBuilder.setReturnType(returnType);
1593 propBuilder.setComment(leafDesc);
1594 toBuilder.addEqualsIdentity(propBuilder);
1595 toBuilder.addHashIdentity(propBuilder);
1596 toBuilder.addToStringProperty(propBuilder);
1601 * Converts <code>node</code> leaf list schema node to getter method of
1602 * <code>typeBuilder</code>.
1604 * @param typeBuilder
1605 * generated type builder to which is <code>node</code> added as
1608 * leaf list schema node which is added to
1609 * <code>typeBuilder</code> as getter method
1610 * @param module module
1611 * @return boolean value
1613 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1614 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1615 * <li>false - other cases</li>
1618 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1619 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1623 final QName nodeName = node.getQName();
1625 final TypeDefinition<?> typeDef = node.getType();
1626 final Module parentModule = findParentModule(schemaContext, node);
1628 Type returnType = null;
1629 if (typeDef.getBaseType() == null) {
1630 if (typeDef instanceof EnumTypeDefinition) {
1631 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1632 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1633 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1634 typeBuilder,module);
1635 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1636 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1637 } else if (typeDef instanceof UnionTypeDefinition) {
1638 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1639 if (genTOBuilder != null) {
1640 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1642 } else if (typeDef instanceof BitsTypeDefinition) {
1643 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1644 returnType = genTOBuilder.toInstance();
1646 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1647 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1650 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1651 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1654 final ParameterizedType listType = Types.listTypeFor(returnType);
1655 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1659 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1660 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1661 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1662 genTOBuilder.getName());
1663 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1665 returnType.setDescription(typedefDescription);
1666 returnType.setReference(typeDef.getReference());
1667 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1668 returnType.setModuleName(parentModule.getName());
1670 genTOBuilder.setTypedef(true);
1671 genTOBuilder.setIsUnion(true);
1672 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1676 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1679 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1680 method.setReturnType(returnType);
1681 method.addParameter(Types.STRING, "defaultValue");
1682 method.setAccessModifier(AccessModifier.PUBLIC);
1683 method.setStatic(true);
1685 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1686 if (types == null) {
1687 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1688 Sets.newHashSet(unionBuilder.toInstance()));
1690 types.add(unionBuilder.toInstance());
1692 return returnType.toInstance();
1695 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1696 final String outerCls = Types.getOuterClassName(genTOBuilder);
1697 final StringBuilder name;
1698 if (outerCls != null) {
1699 name = new StringBuilder(outerCls);
1701 name = new StringBuilder();
1703 name.append(genTOBuilder.getName());
1704 name.append("Builder");
1705 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1706 unionBuilder.setIsUnionBuilder(true);
1707 return unionBuilder;
1710 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1711 final Module module) {
1712 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1716 * Instantiates generated type builder with <code>packageName</code> and
1717 * <code>schemaNode</code>.
1719 * The new builder always implements
1720 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1721 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1722 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1724 * If <code>schemaNode</code> is instance of
1725 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1726 * DataNodeContainer} it can also implement nodes which are specified in
1729 * @param packageName
1730 * string with the name of the package to which
1731 * <code>schemaNode</code> belongs.
1733 * schema node for which is created generated type builder
1735 * parent type (can be null)
1736 * @return generated type builder <code>schemaNode</code>
1738 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1739 final Type parent, final Module module) {
1740 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1741 if (parent == null) {
1742 it.addImplementsType(DATA_OBJECT);
1744 it.addImplementsType(BindingTypes.childOf(parent));
1746 if (!(schemaNode instanceof GroupingDefinition)) {
1747 it.addImplementsType(augmentable(it));
1750 if (schemaNode instanceof DataNodeContainer) {
1751 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1752 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1759 * Wraps the calling of the same overloaded method.
1761 * @param packageName
1762 * string with the package name to which returning generated type
1765 * schema node which provide data about the schema node name
1766 * @return generated type builder for <code>schemaNode</code>
1768 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1769 return addRawInterfaceDefinition(packageName, schemaNode, "");
1773 * Returns reference to generated type builder for specified
1774 * <code>schemaNode</code> with <code>packageName</code>.
1776 * Firstly the generated type builder is searched in
1777 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1778 * found it is created and added to <code>genTypeBuilders</code>.
1780 * @param packageName
1781 * string with the package name to which returning generated type
1784 * schema node which provide data about the schema node name
1786 * return type name prefix
1787 * @return generated type builder for <code>schemaNode</code>
1788 * @throws IllegalArgumentException
1790 * <li>if <code>schemaNode</code> is null</li>
1791 * <li>if <code>packageName</code> is null</li>
1792 * <li>if QName of schema node is null</li>
1793 * <li>if schemaNode name is null</li>
1797 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1798 final String prefix) {
1799 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1800 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1801 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1802 final String schemaNodeName = schemaNode.getQName().getLocalName();
1803 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1806 if (prefix == null) {
1807 genTypeName = BindingMapping.getClassName(schemaNodeName);
1809 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1812 // FIXME: Validation of name conflict
1813 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1814 final Module module = findParentModule(schemaContext, schemaNode);
1815 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1816 newType.addComment(schemaNode.getDescription());
1817 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1818 newType.setReference(schemaNode.getReference());
1819 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1820 newType.setModuleName(module.getName());
1822 if (!genTypeBuilders.containsKey(packageName)) {
1823 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1824 builders.put(genTypeName, newType);
1825 genTypeBuilders.put(packageName, builders);
1827 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1828 if (!builders.containsKey(genTypeName)) {
1829 builders.put(genTypeName, newType);
1836 * Creates the name of the getter method name from <code>localName</code>.
1839 * string with the name of the getter method
1842 * @return string with the name of the getter method for
1843 * <code>methodName</code> in JAVA method format
1845 public static String getterMethodName(final String localName, final Type returnType) {
1846 final StringBuilder method = new StringBuilder();
1847 if (BOOLEAN.equals(returnType)) {
1848 method.append("is");
1850 method.append("get");
1852 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1853 method.append(name);
1854 return method.toString();
1858 * Created a method signature builder as part of
1859 * <code>interfaceBuilder</code>.
1861 * The method signature builder is created for the getter method of
1862 * <code>schemaNodeName</code>. Also <code>comment</code> and
1863 * <code>returnType</code> information are added to the builder.
1865 * @param interfaceBuilder
1866 * generated type builder for which the getter method should be
1868 * @param schemaNodeName
1869 * string with schema node name. The name will be the part of the
1870 * getter method name.
1872 * string with comment for the getter method
1874 * type which represents the return type of the getter method
1876 * status from yang file, for deprecated annotation
1877 * @return method signature builder which represents the getter method of
1878 * <code>interfaceBuilder</code>
1880 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1881 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1882 final MethodSignatureBuilder getMethod = interfaceBuilder
1883 .addMethod(getterMethodName(schemaNodeName, returnType));
1884 if (status == Status.DEPRECATED) {
1885 getMethod.addAnnotation("", "Deprecated");
1887 getMethod.setComment(encodeAngleBrackets(comment));
1888 getMethod.setReturnType(returnType);
1893 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1894 * or to <code>genTOBuilder</code> as property.
1896 * @param basePackageName
1897 * string contains the module package name
1899 * data schema node which should be added as getter method to
1900 * <code>typeBuilder</code> or as a property to
1901 * <code>genTOBuilder</code> if is part of the list key
1902 * @param typeBuilder
1903 * generated type builder for the list schema node
1904 * @param genTOBuilder
1905 * generated TO builder for the list keys
1907 * list of string which contains names of the list keys
1910 * @throws IllegalArgumentException
1912 * <li>if <code>schemaNode</code> equals null</li>
1913 * <li>if <code>typeBuilder</code> equals null</li>
1916 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1917 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1918 final Module module) {
1919 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1920 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1922 if (schemaNode instanceof LeafSchemaNode) {
1923 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1924 final String leafName = leaf.getQName().getLocalName();
1925 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1926 if (listKeys.contains(leafName)) {
1928 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1930 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1933 } else if (!schemaNode.isAddedByUses()) {
1934 if (schemaNode instanceof LeafListSchemaNode) {
1935 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1936 } else if (schemaNode instanceof ContainerSchemaNode) {
1937 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1938 } else if (schemaNode instanceof ChoiceSchemaNode) {
1939 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1940 } else if (schemaNode instanceof ListSchemaNode) {
1941 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1946 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1947 final GeneratedTOBuilder genTOBuilder) {
1948 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1950 if (genTOBuilder != null) {
1951 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1952 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1953 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1958 * Selects the names of the list keys from <code>list</code> and returns
1959 * them as the list of the strings
1962 * of string with names of the list keys
1963 * @return list of string which represents names of the list keys. If the
1964 * <code>list</code> contains no keys then the empty list is
1967 private static List<String> listKeys(final ListSchemaNode list) {
1968 final List<String> listKeys = new ArrayList<>();
1970 final List<QName> keyDefinition = list.getKeyDefinition();
1971 if (keyDefinition != null) {
1972 for (final QName keyDef : keyDefinition) {
1973 listKeys.add(keyDef.getLocalName());
1980 * Generates for the <code>list</code> which contains any list keys special
1981 * generated TO builder.
1983 * @param packageName
1984 * string with package name to which the list belongs
1986 * list schema node which is source of data about the list name
1987 * @return generated TO builder which represents the keys of the
1988 * <code>list</code> or null if <code>list</code> is null or list of
1989 * key definitions is null or empty.
1991 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1992 GeneratedTOBuilder genTOBuilder = null;
1993 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1994 final String listName = list.getQName().getLocalName() + "Key";
1995 final String genTOName = BindingMapping.getClassName(listName);
1996 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1998 return genTOBuilder;
2002 * Builds generated TO builders for <code>typeDef</code> of type
2003 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2004 * also added to <code>typeBuilder</code> as enclosing transfer object.
2006 * If more then one generated TO builder is created for enclosing then all
2007 * of the generated TO builders are added to <code>typeBuilder</code> as
2008 * enclosing transfer objects.
2011 * type definition which can be of type <code>UnionType</code> or
2012 * <code>BitsTypeDefinition</code>
2013 * @param typeBuilder
2014 * generated type builder to which is added generated TO created
2015 * from <code>typeDef</code>
2017 * string with name for generated TO builder
2018 * @param parentModule
2020 * @return generated TO builder for <code>typeDef</code>
2022 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2023 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2024 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2025 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2026 final String packageName = typeBuilder.getFullyQualifiedName();
2027 if (typeDef instanceof UnionTypeDefinition) {
2028 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2029 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
2030 classNameFromLeaf, leaf);
2031 genTOBuilders.addAll(types);
2033 GeneratedTOBuilder resultTOBuilder;
2034 if (types.isEmpty()) {
2035 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2037 resultTOBuilder = types.remove(0);
2038 for (final GeneratedTOBuilder genTOBuilder : types) {
2039 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2042 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2043 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2044 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2045 resultTOBuilder.addHashIdentity(genPropBuilder);
2046 resultTOBuilder.addToStringProperty(genPropBuilder);
2048 } else if (typeDef instanceof BitsTypeDefinition) {
2049 genTOBuilders.add(((TypeProviderImpl) typeProvider).provideGeneratedTOBuilderForBitsTypeDefinition(
2050 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2052 if (!genTOBuilders.isEmpty()) {
2053 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2054 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2056 return genTOBuilders.get(0);
2063 * Adds the implemented types to type builder.
2065 * The method passes through the list of <i>uses</i> in
2066 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2067 * generated type from {@link ModuleContext#groupings
2068 * allGroupings} which is added as <i>implements type</i> to
2069 * <code>builder</code>
2071 * @param dataNodeContainer
2072 * element which contains the list of used YANG groupings
2074 * builder to which are added implemented types according to
2075 * <code>dataNodeContainer</code>
2076 * @return generated type builder with all implemented types
2078 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2079 final GeneratedTypeBuilder builder) {
2080 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2081 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2082 if (genType == null) {
2083 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2084 + builder.getName());
2087 builder.addImplementsType(genType);
2092 private static boolean isNullOrEmpty(final Collection<?> list) {
2093 return list == null || list.isEmpty();
2096 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2097 final StringBuilder sb = new StringBuilder();
2099 if (!isNullOrEmpty(schemaNodes)) {
2100 final SchemaNode node = schemaNodes.iterator().next();
2102 if (node instanceof RpcDefinition) {
2103 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2104 } else if (node instanceof NotificationDefinition) {
2105 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2108 sb.append(NEW_LINE);
2110 if (verboseClassComments) {
2112 sb.append(NEW_LINE);
2113 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2114 sb.append("</pre>");
2115 sb.append(NEW_LINE);
2118 return replaceAllIllegalChars(sb);
2121 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2122 final StringBuilder sb = new StringBuilder();
2123 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2124 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2126 if (!Strings.isNullOrEmpty(formattedDescription)) {
2127 sb.append(formattedDescription);
2128 sb.append(NEW_LINE);
2131 if (verboseClassComments) {
2132 final Module module = findParentModule(schemaContext, schemaNode);
2133 final StringBuilder linkToBuilderClass = new StringBuilder();
2134 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2135 final String className = namespace[namespace.length - 1];
2137 if (hasBuilderClass(schemaNode)) {
2138 linkToBuilderClass.append(className);
2139 linkToBuilderClass.append("Builder");
2143 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2144 sb.append(module.getName());
2146 sb.append(NEW_LINE);
2148 sb.append(NEW_LINE);
2149 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2150 sb.append("</pre>");
2151 sb.append(NEW_LINE);
2152 sb.append("The schema path to identify an instance is");
2153 sb.append(NEW_LINE);
2155 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2157 sb.append(NEW_LINE);
2159 if (hasBuilderClass(schemaNode)) {
2160 sb.append(NEW_LINE);
2161 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2162 sb.append(NEW_LINE);
2164 sb.append(linkToBuilderClass);
2165 sb.append(NEW_LINE);
2166 if (schemaNode instanceof ListSchemaNode) {
2167 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2168 if (keyDef != null && !keyDef.isEmpty()) {
2170 sb.append(className);
2173 sb.append(NEW_LINE);
2178 return replaceAllIllegalChars(sb);
2181 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2182 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2183 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2189 private String createDescription(final Module module) {
2190 final StringBuilder sb = new StringBuilder();
2191 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2192 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2194 if (!Strings.isNullOrEmpty(formattedDescription)) {
2195 sb.append(formattedDescription);
2196 sb.append(NEW_LINE);
2199 if (verboseClassComments) {
2201 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2202 sb.append(module.getName());
2204 sb.append(NEW_LINE);
2206 sb.append(NEW_LINE);
2207 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2208 sb.append("</pre>");
2211 return replaceAllIllegalChars(sb);
2214 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2215 for (final ModuleContext ctx : genCtx.values()) {
2216 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2217 if (result != null) {
2224 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2225 for (final ModuleContext ctx : genCtx.values()) {
2226 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2227 if (result != null) {
2234 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2235 for (final ModuleContext ctx : genCtx.values()) {
2236 final GeneratedTypeBuilder result = ctx.getCase(path);
2237 if (result != null) {
2244 public Map<Module, ModuleContext> getModuleContexts() {
2249 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2250 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2251 return ret.isEmpty() ? "" : ret;
2254 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2255 if (status == Status.DEPRECATED) {
2256 builder.addAnnotation("", "Deprecated");