2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
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.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
34 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
35 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
36 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
38 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
39 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
40 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
42 import com.google.common.base.Splitter;
43 import com.google.common.collect.Iterables;
44 import com.google.common.collect.Sets;
45 import java.util.AbstractMap.SimpleImmutableEntry;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Optional;
55 import org.eclipse.jdt.annotation.Nullable;
56 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
57 import org.opendaylight.mdsal.binding.model.api.Constant;
58 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
60 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
61 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
62 import org.opendaylight.mdsal.binding.model.api.Restrictions;
63 import org.opendaylight.mdsal.binding.model.api.Type;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
73 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
74 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
75 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
76 import org.opendaylight.mdsal.binding.model.util.Types;
77 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
78 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
79 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
80 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
81 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.common.QNameModule;
84 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
85 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
94 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
95 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
101 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
102 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
103 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
104 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
106 import org.opendaylight.yangtools.yang.model.api.Status;
107 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
108 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.UsesNode;
110 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
111 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
113 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
114 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
115 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
116 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
117 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
121 abstract class AbstractTypeGenerator {
122 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
123 private static final Splitter COLON_SPLITTER = Splitter.on(':');
124 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
125 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
126 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
129 * Comparator based on augment target path.
131 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
132 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
133 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
135 while (thisIt.hasNext()) {
136 if (!otherIt.hasNext()) {
140 final int comp = thisIt.next().compareTo(otherIt.next());
146 return otherIt.hasNext() ? -1 : 0;
150 * Constant with the concrete name of identifier.
152 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
155 * Constant with the concrete name of namespace.
157 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
159 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
162 * Outer key represents the package name. Outer value represents map of all
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder for schema node specified in key part.
167 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
170 * Provide methods for converting YANG types to JAVA types.
172 private final AbstractTypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element
176 * when creating augmentation builder
178 private final SchemaContext schemaContext;
181 * Holds renamed elements.
183 private final Map<SchemaNode, JavaTypeName> renames;
185 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
186 final Map<SchemaNode, JavaTypeName> renames) {
187 this.schemaContext = requireNonNull(context);
188 this.typeProvider = requireNonNull(typeProvider);
189 this.renames = requireNonNull(renames);
191 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
192 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
193 for (final Module contextModule : contextModules) {
194 contexts.add(moduleToGenTypes(contextModule));
197 contexts.forEach(this::allAugmentsToGenTypes);
200 final Collection<ModuleContext> moduleContexts() {
201 return genCtx.values();
204 final ModuleContext moduleContext(final QNameModule module) {
205 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
208 final AbstractTypeProvider typeProvider() {
212 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
214 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
216 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
217 Set<? extends SchemaNode> nodes);
219 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
221 private ModuleContext moduleToGenTypes(final Module module) {
222 final ModuleContext context = new ModuleContext(module);
223 genCtx.put(module.getQNameModule(), context);
224 allTypeDefinitionsToGenTypes(context);
225 groupingsToGenTypes(context, module.getGroupings());
226 rpcMethodsToGenType(context);
227 allIdentitiesToGenTypes(context);
228 notificationsToGenType(context);
230 if (!module.getChildNodes().isEmpty()) {
231 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
232 context.addModuleNode(moduleType);
233 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
239 * Converts all extended type definitions of module to the list of
240 * <code>Type</code> objects.
243 * module from which is obtained set of type definitions
244 * @throws IllegalArgumentException
246 * <li>if module is null</li>
247 * <li>if name of module is null</li>
249 * @throws IllegalStateException
250 * if set of type definitions from module is null
252 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
253 final Module module = context.module();
254 checkArgument(module.getName() != null, "Module name cannot be NULL.");
255 final DataNodeIterator it = new DataNodeIterator(module);
256 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
257 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
259 for (final TypeDefinition<?> typedef : typeDefinitions) {
260 if (typedef != null) {
261 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
263 context.addTypedefType(typedef, type);
264 context.addTypeToSchema(type,typedef);
270 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
271 final DataSchemaNode node, final boolean inGrouping) {
272 if (node.isAugmenting() || node.isAddedByUses()) {
275 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
276 annotateDeprecatedIfNecessary(node.getStatus(), genType);
278 final Module module = context.module();
279 genType.setModuleName(module.getName());
280 addCodegenInformation(genType, module, node);
281 genType.setSchemaPath(node.getPath());
282 if (node instanceof DataNodeContainer) {
283 context.addChildNodeType(node, genType);
284 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
285 processUsesAugments((DataNodeContainer) node, context, inGrouping);
290 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
291 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
292 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
293 if (genType != null) {
294 constructGetter(parent, genType, node);
295 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
296 actionsToGenType(context, genType, node, null, inGrouping);
300 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
301 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
302 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
303 if (genType != null) {
304 constructGetter(parent, listTypeFor(genType), node);
306 final List<String> listKeys = listKeys(node);
307 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
308 if (genTOBuilder != null) {
309 final Type identifierMarker = identifier(genType);
310 final Type identifiableMarker = identifiable(genTOBuilder);
311 genTOBuilder.addImplementsType(identifierMarker);
312 genType.addImplementsType(identifiableMarker);
315 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
317 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
318 if (!schemaNode.isAugmenting()) {
319 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
324 if (genTOBuilder != null) {
325 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
326 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
327 genTOBuilder.setSUID(prop);
330 typeBuildersToGenTypes(context, genType, genTOBuilder);
334 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
335 final boolean inGrouping) {
336 for (final UsesNode usesNode : node.getUses()) {
337 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
338 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
339 processUsesAugments(augment, context, inGrouping);
345 * Converts all <b>augmentation</b> of the module to the list
346 * <code>Type</code> objects.
349 * module from which is obtained list of all augmentation objects
350 * to iterate over them
351 * @throws IllegalArgumentException
353 * <li>if the module is null</li>
354 * <li>if the name of module is null</li>
356 * @throws IllegalStateException
357 * if set of augmentations from module is null
359 private void allAugmentsToGenTypes(final ModuleContext context) {
360 final Module module = context.module();
361 checkArgument(module != null, "Module reference cannot be NULL.");
362 checkArgument(module.getName() != null, "Module name cannot be NULL.");
363 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
365 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
366 augmentationToGenTypes(context, augment);
371 * Returns list of <code>AugmentationSchema</code> objects. The objects are
372 * sorted according to the length of their target path from the shortest to
376 * module from which is obtained list of all augmentation objects
377 * @return list of sorted <code>AugmentationSchema</code> objects obtained
378 * from <code>module</code>
379 * @throws IllegalArgumentException
381 * @throws IllegalStateException
382 * if set of module augmentations is null
384 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
385 checkArgument(module != null, "Module reference cannot be NULL.");
386 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
388 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
389 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
390 sortedAugmentations.sort(AUGMENT_COMP);
392 return sortedAugmentations;
396 * Create GeneratedTypeBuilder object from module argument.
399 * Module object from which builder will be created
400 * @return <code>GeneratedTypeBuilder</code> which is internal
401 * representation of the module
402 * @throws IllegalArgumentException
405 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
406 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
407 final Module module = context.module();
408 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
409 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
411 addCodegenInformation(moduleDataTypeBuilder, module);
412 return moduleDataTypeBuilder;
415 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
416 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
417 for (final ActionDefinition action : parentSchema.getActions()) {
418 final GeneratedType input;
419 final GeneratedType output;
420 if (action.isAddedByUses()) {
421 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
422 input = context.getChildNode(orig.getInput().getPath()).build();
423 output = context.getChildNode(orig.getOutput().getPath()).build();
425 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
426 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
429 if (!(parentSchema instanceof GroupingDefinition)) {
430 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
431 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
432 // and do not capture an actual instantiation.
433 final QName qname = action.getQName();
434 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
435 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
436 BindingMapping.getClassName(qname)));
437 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
438 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
440 annotateDeprecatedIfNecessary(action.getStatus(), builder);
441 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
442 : action(parent, input, output));
444 addCodegenInformation(builder, context.module(), action);
445 context.addChildNodeType(action, builder);
450 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
451 for (UsesNode uses : parent.getUses()) {
452 final GroupingDefinition grp = findUsedGrouping(uses);
453 final Optional<ActionDefinition> found = grp.getActions().stream()
454 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
455 if (found.isPresent()) {
456 final ActionDefinition result = found.get();
457 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
461 return Optional.empty();
464 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
465 final ContainerSchemaNode schema, final boolean inGrouping) {
466 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
467 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
468 return genType.build();
472 * Converts all <b>RPCs</b> input and output substatements of the module
473 * to the list of <code>Type</code> objects. In addition are to containers
474 * and lists which belong to input or output also part of returning list.
477 * module from which is obtained set of all rpc objects to
479 * @throws IllegalArgumentException
481 * <li>if the module is null</li>
482 * <li>if the name of module is null</li>
484 * @throws IllegalStateException
485 * if set of rpcs from module is null
487 private void rpcMethodsToGenType(final ModuleContext context) {
488 final Module module = context.module();
489 checkArgument(module.getName() != null, "Module name cannot be NULL.");
490 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
491 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
492 if (rpcDefinitions.isEmpty()) {
496 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
497 interfaceBuilder.addImplementsType(RPC_SERVICE);
499 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
501 for (final RpcDefinition rpc : rpcDefinitions) {
503 final String rpcName = BindingMapping.getClassName(rpc.getQName());
504 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
505 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
507 // Do not refer to annotation class, as it may not be available at runtime
508 method.addAnnotation("javax.annotation", "CheckReturnValue");
509 addComment(method, rpc);
511 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
512 method.setReturnType(listenableFutureTypeFor(
513 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
517 context.addTopLevelNodeType(interfaceBuilder);
520 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
521 final ContainerSchemaNode schema, final Type type) {
522 processUsesAugments(schema, context, false);
523 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
524 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
526 addImplementedInterfaceFromUses(schema, outType);
527 outType.addImplementsType(type);
528 outType.addImplementsType(augmentable(outType));
529 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
530 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
531 context.addChildNodeType(schema, outType);
532 return outType.build();
536 * Converts all <b>notifications</b> of the module to the list of
537 * <code>Type</code> objects. In addition are to this list added containers
538 * and lists which are part of this notification.
541 * module from which is obtained set of all notification objects
542 * to iterate over them
543 * @throws IllegalArgumentException
545 * <li>if the module equals null</li>
546 * <li>if the name of module equals null</li>
548 * @throws IllegalStateException
549 * if set of notifications from module is null
551 private void notificationsToGenType(final ModuleContext context) {
552 final Module module = context.module();
553 checkArgument(module.getName() != null, "Module name cannot be NULL.");
554 final Set<NotificationDefinition> notifications = module.getNotifications();
555 if (notifications.isEmpty()) {
559 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
560 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
562 for (final NotificationDefinition notification : notifications) {
563 if (notification != null) {
564 processUsesAugments(notification, context, false);
566 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
567 context.modulePackageName(), notification, DATA_OBJECT, context);
568 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
569 notificationInterface.addImplementsType(NOTIFICATION);
570 context.addChildNodeType(notification, notificationInterface);
572 // Notification object
573 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
574 notification.getChildNodes(), false);
576 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
577 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
578 .setReturnType(Types.primitiveVoidType()), notification);
582 addCodegenInformation(listenerInterface, module, "notifications", notifications);
583 context.addTopLevelNodeType(listenerInterface);
587 * Converts all <b>identities</b> of the module to the list of
588 * <code>Type</code> objects.
591 * module from which is obtained set of all identity objects to
593 * @param schemaContext
594 * schema context only used as input parameter for method
595 * {@link BindingGeneratorImpl#identityToGenType}
598 private void allIdentitiesToGenTypes(final ModuleContext context) {
599 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
601 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
602 for (final IdentitySchemaNode identity : schemaIdentities) {
603 identityToGenType(context, identity);
609 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
610 * created transport object builder. If identity contains base identity then
611 * reference to base identity is added to superior identity as its extend.
612 * If identity doesn't contain base identity then only reference to abstract
613 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
614 * BaseIdentity} is added
618 * @param basePackageName
619 * string contains the module package name
621 * IdentitySchemaNode which contains data about identity
623 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
624 if (identity == null) {
628 JavaTypeName name = renames.get(identity);
630 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
631 BindingMapping.getClassName(identity.getQName()));
634 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
635 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
636 if (!baseIdentities.isEmpty()) {
637 for (IdentitySchemaNode baseIdentity : baseIdentities) {
638 JavaTypeName base = renames.get(baseIdentity);
640 final QName qname = baseIdentity.getQName();
641 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
642 BindingMapping.getClassName(qname));
645 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
646 newType.addImplementsType(gto);
649 newType.addImplementsType(BASE_IDENTITY);
652 final Module module = context.module();
653 addCodegenInformation(newType, module, identity);
654 newType.setModuleName(module.getName());
655 newType.setSchemaPath(identity.getPath());
657 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
658 identity.getQName().getLocalName());
660 context.addIdentityType(identity, newType);
663 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
664 final JavaTypeName yangModuleInfo, final String localName) {
665 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
666 new SimpleImmutableEntry<>(yangModuleInfo, localName));
670 * Converts all <b>groupings</b> of the module to the list of
671 * <code>Type</code> objects. Firstly are groupings sorted according mutual
672 * dependencies. At least dependent (independent) groupings are in the list
673 * saved at first positions. For every grouping the record is added to map
674 * {@link ModuleContext#groupings allGroupings}
679 * collection of groupings from which types will be generated
682 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
683 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
684 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
685 // node of grouping is resolved to the method.
686 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
687 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
688 context.addGroupingType(grouping, genType);
689 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
690 groupingsToGenTypes(context, grouping.getGroupings());
691 processUsesAugments(grouping, context, true);
692 actionsToGenType(context, genType, grouping, null, true);
697 * Adds enumeration builder created from <code>enumTypeDef</code> to
698 * <code>typeBuilder</code>.
700 * Each <code>enumTypeDef</code> item is added to builder with its name and
704 * EnumTypeDefinition contains enum data
706 * string contains name which will be assigned to enumeration
709 * GeneratedTypeBuilder to which will be enum builder assigned
711 * Module in which type should be generated
712 * @return enumeration builder which contains data from
713 * <code>enumTypeDef</code>
715 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
716 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
717 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
718 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
719 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
720 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
721 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
728 * Generates type builder for <code>module</code>.
731 * Module which is source of package name for generated type
734 * string which is added to the module class name representation
736 * @return instance of GeneratedTypeBuilder which represents
737 * <code>module</code>.
738 * @throws IllegalArgumentException
739 * if <code>module</code> is null
741 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
742 final Module module = context.module();
743 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
744 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
745 JavaTypeName.create(context.modulePackageName(), moduleName));
747 moduleBuilder.setModuleName(moduleName);
748 addCodegenInformation(moduleBuilder, module);
749 return moduleBuilder;
753 * Converts <code>augSchema</code> to list of <code>Type</code> which
754 * contains generated type for augmentation. In addition there are also
755 * generated types for all containers, list and choices which are child of
756 * <code>augSchema</code> node or a generated types for cases are added if
757 * augmented node is choice.
759 * @param augmentPackageName
760 * string with the name of the package to which the augmentation
763 * AugmentationSchema which is contains data about augmentation
764 * (target path, childs...)
767 * @throws IllegalArgumentException
769 * <li>if <code>augmentPackageName</code> equals null</li>
770 * <li>if <code>augSchema</code> equals null</li>
772 * @throws IllegalStateException
773 * if augment target path is null
775 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
776 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
777 checkState(augSchema.getTargetPath() != null,
778 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
780 processUsesAugments(augSchema, context, false);
781 final SchemaPath targetPath = augSchema.getTargetPath();
782 SchemaNode targetSchemaNode = null;
784 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
785 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
786 if (targetSchemaNode instanceof DerivableSchemaNode) {
787 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
789 if (targetSchemaNode == null) {
790 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
791 + " in module " + context.module().getName());
794 if (targetSchemaNode == null) {
795 throw new IllegalArgumentException("augment target not found: " + targetPath);
798 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
799 if (targetTypeBuilder == null) {
800 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
802 if (targetTypeBuilder == null) {
803 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
806 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
807 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
808 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
811 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
812 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
816 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
817 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
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, context, inGrouping);
823 final SchemaPath targetPath = augSchema.getTargetPath();
824 final 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 ChoiceSchemaNode)) {
838 if (usesNodeParent instanceof SchemaNode) {
839 addRawAugmentGenTypeDefinition(context,
840 packageNameForAugmentedGeneratedType(context.modulePackageName(),
841 ((SchemaNode) usesNodeParent).getPath()),
842 targetTypeBuilder.build(), augSchema, inGrouping);
844 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
847 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
848 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
852 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
853 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
855 if (targetGrouping instanceof GroupingDefinition) {
856 return (GroupingDefinition) targetGrouping;
859 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
863 * Convenient method to find node added by uses statement.
867 * @param parentUsesNode
868 * parent of uses node
869 * @return node from its original location in grouping
871 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
872 SchemaNode result = findUsedGrouping(parentUsesNode);
873 for (final QName node : targetPath.getPathFromRoot()) {
874 if (result instanceof DataNodeContainer) {
875 final QName resultNode = node.withModule(result.getQName().getModule());
876 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
877 } else if (result instanceof ChoiceSchemaNode) {
878 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
881 if (result == null) {
885 if (result instanceof DerivableSchemaNode) {
886 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
887 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
888 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
889 result = originalNode.get();
893 if (result instanceof DataSchemaNode) {
894 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
895 if (resultDataSchemaNode.isAddedByUses()) {
896 // The original node is required, but we have only the copy of
897 // the original node.
898 // Maybe this indicates a bug in Yang parser.
899 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
902 return resultDataSchemaNode;
905 throw new IllegalStateException(
906 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
911 * Returns a generated type builder for an augmentation.
913 * The name of the type builder is equal to the name of augmented node with
914 * serial number as suffix.
918 * @param augmentPackageName
919 * string with contains the package name to which the augment
921 * @param basePackageName
922 * string with the package name to which the augmented node
924 * @param targetTypeRef
927 * augmentation schema which contains data about the child nodes
928 * and uses of augment
929 * @return generated type builder for augment
931 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
932 final String augmentPackageName, final Type targetTypeRef,
933 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
934 Map<String, GeneratedTypeBuilder> augmentBuilders =
935 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
936 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
939 if (augIdentifier != null) {
940 augTypeName = BindingMapping.getClassName(augIdentifier);
942 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
945 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
946 JavaTypeName.create(augmentPackageName, augTypeName));
948 augTypeBuilder.addImplementsType(DATA_OBJECT);
949 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
950 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
951 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
953 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
954 augmentBuilders.put(augTypeName, augTypeBuilder);
956 if (!augSchema.getChildNodes().isEmpty()) {
957 context.addTypeToAugmentation(augTypeBuilder, augSchema);
960 context.addAugmentType(augTypeBuilder);
961 return augTypeBuilder;
964 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
965 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
966 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
972 * @param unknownSchemaNodes
973 * @return nodeParameter of UnknownSchemaNode
975 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
976 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
977 final QName nodeType = unknownSchemaNode.getNodeType();
978 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
979 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
980 return unknownSchemaNode.getNodeParameter();
987 * Returns first unique name for the augment generated type builder. The
988 * generated type builder name for augment consists from name of augmented
989 * node and serial number of its augmentation.
992 * map of builders which were created in the package to which the
993 * augmentation belongs
995 * string with name of augmented node
996 * @return string with unique name for augmentation builder
998 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1000 if (builders != null) {
1001 while (builders.containsKey(genTypeName + index)) {
1005 return genTypeName + index;
1009 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1010 * node for which <code>typeBuilder</code> was created.
1012 * The subnodes aren't mapped to the methods if they are part of grouping or
1013 * augment (in this case are already part of them).
1018 * generated type builder which represents any node. The subnodes
1019 * of this node are added to the <code>typeBuilder</code> as
1020 * methods. The subnode can be of type leaf, leaf-list, list,
1021 * container, choice.
1024 * @param schemaNodes
1025 * set of data schema nodes which are the children of the node
1026 * for which <code>typeBuilder</code> was created
1027 * @return generated type builder which is the same builder as input
1028 * parameter. The getter methods (representing child nodes) could be
1031 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1032 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1033 if (schemaNodes != null && parent != null) {
1034 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1035 for (final DataSchemaNode schemaNode : schemaNodes) {
1036 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1037 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1045 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1046 * node for which <code>typeBuilder</code> was created.
1050 * @param typeBuilder
1051 * generated type builder which represents any node. The subnodes
1052 * of this node are added to the <code>typeBuilder</code> as
1053 * methods. The subnode can be of type leaf, leaf-list, list,
1054 * container, choice.
1057 * @param schemaNodes
1058 * set of data schema nodes which are the children of the node
1059 * for which <code>typeBuilder</code> was created
1060 * @return generated type builder which is the same object as the input
1061 * parameter <code>typeBuilder</code>. The getter method could be
1064 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1065 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1066 final boolean inGrouping) {
1067 if (schemaNodes != null && typeBuilder != null) {
1068 final Type baseInterface = childOf(typeBuilder);
1069 for (final DataSchemaNode schemaNode : schemaNodes) {
1070 if (!schemaNode.isAugmenting()) {
1071 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1079 * Adds to <code>typeBuilder</code> a method which is derived from
1080 * <code>schemaNode</code>.
1083 * data schema node which is added to <code>typeBuilder</code> as
1085 * @param typeBuilder
1086 * generated type builder to which is <code>schemaNode</code>
1087 * added as a method.
1093 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1094 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1095 if (node != null && typeBuilder != null) {
1096 if (node instanceof LeafSchemaNode) {
1097 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1098 } else if (node instanceof LeafListSchemaNode) {
1099 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1100 } else if (node instanceof ContainerSchemaNode) {
1101 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1102 } else if (node instanceof ListSchemaNode) {
1103 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1104 } else if (node instanceof ChoiceSchemaNode) {
1105 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1107 // TODO: anyxml not yet supported
1108 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1109 typeBuilder.getFullyQualifiedName());
1115 * Converts <code>choiceNode</code> to the list of generated types for
1116 * choice and its cases.
1118 * The package names for choice and for its cases are created as
1119 * concatenation of the module package (<code>basePackageName</code>) and
1120 * names of all parents node.
1124 * @param basePackageName
1125 * string with the module package name
1129 * choice node which is mapped to generated type. Also child
1130 * nodes - cases are mapped to generated types.
1131 * @throws IllegalArgumentException
1133 * <li>if <code>basePackageName</code> is null</li>
1134 * <li>if <code>choiceNode</code> is null</li>
1137 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1138 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1139 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1141 if (!choiceNode.isAddedByUses()) {
1142 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1143 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1144 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1145 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1146 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1147 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1149 final GeneratedType choiceType = choiceTypeBuilder.build();
1150 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1152 constructGetter(parent, choiceType, choiceNode);
1157 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1159 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1160 * The package names for the builder is created as concatenation of the module package and names of all parents
1161 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1162 * and <i>choice</i> type
1165 * current module context
1166 * @param refChoiceType
1167 * type which represents superior <i>case</i>
1169 * choice case node which is mapped to generated type
1170 * @throws IllegalArgumentException
1172 * <li>if <code>refChoiceType</code> equals null</li>
1173 * <li>if <code>caseNodes</code> equals null</li>
1176 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1177 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1178 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1179 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1181 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1182 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1183 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1184 caseTypeBuilder.addImplementsType(refChoiceType);
1185 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1186 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1187 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1188 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1189 if (caseChildNodes != null) {
1190 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1192 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1193 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1195 if (parent instanceof AugmentationSchemaNode) {
1196 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1197 final SchemaPath targetPath = augSchema.getTargetPath();
1198 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1199 if (targetSchemaNode instanceof DataSchemaNode
1200 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1201 if (targetSchemaNode instanceof DerivableSchemaNode) {
1202 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1205 if (targetSchemaNode == null) {
1206 throw new IllegalStateException(
1207 "Failed to find target node from grouping for augmentation " + augSchema
1208 + " in module " + context.module().getName());
1211 parent = targetSchemaNode;
1214 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1215 Type childOfType = findChildNodeByPath(parent.getPath());
1216 if (childOfType == null) {
1217 childOfType = findGroupingByPath(parent.getPath());
1219 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1221 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1226 processUsesAugments(caseNode, context, inGrouping);
1231 * Generates list of generated types for all the cases of a choice which are
1232 * added to the choice through the augment.
1236 * @param basePackageName
1237 * string contains name of package to which augment belongs. If
1238 * an augmented choice is from an other package (pcg1) than an
1239 * augmenting choice (pcg2) then case's of the augmenting choice
1240 * will belong to pcg2.
1242 * Type which represents target choice
1244 * node which represents target choice
1245 * @param augmentedNodes
1246 * set of choice case nodes for which is checked if are/aren't
1247 * added to choice through augmentation
1248 * @throws IllegalArgumentException
1250 * <li>if <code>basePackageName</code> is null</li>
1251 * <li>if <code>targetType</code> is null</li>
1252 * <li>if <code>augmentedNodes</code> is null</li>
1255 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1256 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1257 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1258 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1259 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1261 for (final DataSchemaNode caseNode : augmentedNodes) {
1262 if (caseNode != null) {
1263 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1264 caseTypeBuilder.addImplementsType(targetType);
1266 CaseSchemaNode node = null;
1267 final String caseLocalName = caseNode.getQName().getLocalName();
1268 if (caseNode instanceof CaseSchemaNode) {
1269 node = (CaseSchemaNode) caseNode;
1270 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1271 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1272 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1273 if (dataSchemaNode instanceof ChoiceSchemaNode
1274 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1275 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1280 node = findNamedCase(targetNode, caseLocalName);
1282 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1283 if (childNodes != null) {
1284 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1287 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1288 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1293 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1294 final SchemaPath nodePath = targetNode.getPath();
1295 final SchemaPath parentSp = nodePath.getParent();
1296 if (parentSp.getParent() == null) {
1297 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1300 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1301 GeneratedTypeBuilder childOfType = null;
1302 if (parent instanceof CaseSchemaNode) {
1303 childOfType = findCaseByPath(parent.getPath());
1304 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1305 childOfType = findChildNodeByPath(parent.getPath());
1306 } else if (parent instanceof GroupingDefinition) {
1307 childOfType = findGroupingByPath(parent.getPath());
1310 if (childOfType == null) {
1311 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1317 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1318 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1319 return cases.isEmpty() ? null : cases.get(0);
1322 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1323 // New parser with encapsulated type
1324 if (leaf.getPath().equals(type.getPath())) {
1328 // Embedded type definition with new parser. Also takes care of the old parser with bits
1329 if (leaf.getPath().equals(type.getPath().getParent())) {
1336 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1337 final List<PatternConstraint> patternConstraints) {
1338 if (!patternConstraints.isEmpty()) {
1339 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1340 .append(BindingMapping.getPropertyName(leafName));
1341 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1342 typeProvider.resolveRegExpressions(patternConstraints));
1347 * Converts <code>leaf</code> to the getter method which is added to
1348 * <code>typeBuilder</code>.
1350 * @param typeBuilder
1351 * generated type builder to which is added getter method as
1352 * <code>leaf</code> mapping
1354 * leaf schema node which is mapped as getter method which is
1355 * added to <code>typeBuilder</code>
1357 * Module in which type was defined
1358 * @return boolean value
1360 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1362 * <li>true - in other cases</li>
1365 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1366 final ModuleContext context, final boolean inGrouping) {
1367 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1371 final Module parentModule = findParentModule(schemaContext, leaf);
1372 Type returnType = null;
1374 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1375 if (isInnerType(leaf, typeDef)) {
1376 if (typeDef instanceof EnumTypeDefinition) {
1377 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1378 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1379 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1380 typeBuilder, context);
1381 if (enumBuilder != null) {
1382 returnType = enumBuilder.toInstance(typeBuilder);
1384 typeProvider.putReferencedType(leaf.getPath(), returnType);
1385 } else if (typeDef instanceof UnionTypeDefinition) {
1386 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1387 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1388 // Store the inner type within the union so that we can find the reference for it
1389 context.addInnerTypedefType(typeDef.getPath(), returnType);
1390 } else if (typeDef instanceof BitsTypeDefinition) {
1391 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1393 if (genTOBuilder != null) {
1394 returnType = genTOBuilder.build();
1397 // It is constrained version of already declared type (inner declared type exists,
1398 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1399 // In order to get proper class we need to look up closest derived type
1400 // and apply restrictions from leaf type
1401 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1402 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1403 restrictions, inGrouping);
1404 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1407 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1408 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1409 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1412 if (returnType == null) {
1416 if (typeDef instanceof EnumTypeDefinition) {
1417 typeProvider.putReferencedType(leaf.getPath(), returnType);
1420 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1421 processContextRefExtension(leaf, getter, parentModule);
1425 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1426 // Returns DerivedType in case of new parser.
1427 final TypeDefinition<?> baseType = typeDef.getBaseType();
1428 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1431 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1432 final Module module) {
1433 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1434 final QName nodeType = node.getNodeType();
1435 if ("context-reference".equals(nodeType.getLocalName())) {
1436 final String nodeParam = node.getNodeParameter();
1437 IdentitySchemaNode identity = null;
1438 String basePackageName = null;
1439 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1440 final Iterator<String> iterator = splittedElement.iterator();
1441 final int length = Iterables.size(splittedElement);
1443 identity = findIdentityByName(module.getIdentities(), iterator.next());
1444 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1445 } else if (length == 2) {
1446 final String prefix = iterator.next();
1447 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1448 if (dependentModule == null) {
1449 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1452 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1453 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1455 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1458 if (identity == null) {
1459 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1463 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1464 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1465 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1466 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1471 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1472 for (final IdentitySchemaNode id : identities) {
1473 if (id.getQName().getLocalName().equals(name)) {
1480 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1481 for (final ModuleImport imp : imports) {
1482 if (imp.getPrefix().equals(prefix)) {
1483 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1489 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1490 final boolean isReadOnly) {
1491 if (leaf != null && toBuilder != null) {
1493 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1494 if (typeDef instanceof UnionTypeDefinition) {
1495 // GeneratedType for this type definition should have be already created
1496 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1497 returnType = mc.getTypedefs().get(typeDef.getPath());
1498 if (returnType == null) {
1499 // This may still be an inner type, try to find it
1500 returnType = mc.getInnerType(typeDef.getPath());
1502 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1503 // Annonymous enumeration (already generated, since it is inherited via uses).
1504 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1505 QName qname = originalLeaf.getQName();
1506 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1508 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1510 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1516 * Converts <code>leaf</code> schema node to property of generated TO
1520 * generated TO builder to which is <code>leaf</code> added as
1523 * leaf schema node which is added to <code>toBuilder</code> as
1528 * boolean value which says if leaf property is|isn't read only
1529 * @return boolean value
1531 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1532 * name equals null or if leaf is added by <i>uses</i>.</li>
1533 * <li>true - other cases</li>
1536 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1537 final Type returnType, final boolean isReadOnly) {
1538 if (returnType == null) {
1541 final String leafName = leaf.getQName().getLocalName();
1542 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1543 propBuilder.setReadOnly(isReadOnly);
1544 propBuilder.setReturnType(returnType);
1545 addComment(propBuilder, leaf);
1547 toBuilder.addEqualsIdentity(propBuilder);
1548 toBuilder.addHashIdentity(propBuilder);
1549 toBuilder.addToStringProperty(propBuilder);
1554 * Converts <code>node</code> leaf list schema node to getter method of
1555 * <code>typeBuilder</code>.
1557 * @param typeBuilder
1558 * generated type builder to which is <code>node</code> added as
1561 * leaf list schema node which is added to
1562 * <code>typeBuilder</code> as getter method
1563 * @param module module
1564 * @return boolean value
1566 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1567 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1568 * <li>false - other cases</li>
1571 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1572 final ModuleContext context, final boolean inGrouping) {
1573 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1577 final QName nodeName = node.getQName();
1579 final TypeDefinition<?> typeDef = node.getType();
1580 final Module parentModule = findParentModule(schemaContext, node);
1582 Type returnType = null;
1583 if (typeDef.getBaseType() == null) {
1584 if (typeDef instanceof EnumTypeDefinition) {
1585 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1586 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1587 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1588 typeBuilder, context);
1589 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1590 typeProvider.putReferencedType(node.getPath(), returnType);
1591 } else if (typeDef instanceof UnionTypeDefinition) {
1592 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1593 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1594 } else if (typeDef instanceof BitsTypeDefinition) {
1595 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1596 node, parentModule);
1597 returnType = genTOBuilder.build();
1599 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1600 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1601 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1604 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1605 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1606 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1609 final ParameterizedType listType = listTypeFor(returnType);
1610 constructGetter(typeBuilder, listType, node);
1614 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1615 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1616 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1617 returnTypeBuilder.setIsUnion(true);
1618 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1619 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1620 returnTypeBuilder.setModuleName(parentModule.getName());
1621 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1623 genTOBuilder.setTypedef(true);
1624 genTOBuilder.setIsUnion(true);
1625 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1627 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1631 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1632 final GeneratedTransferObject returnType, final Module parentModule) {
1633 // Append enclosing path hierarchy without dots
1634 final StringBuilder sb = new StringBuilder();
1635 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1636 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1637 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1638 unionBuilder.setIsUnionBuilder(true);
1640 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1641 method.setReturnType(returnType);
1642 method.addParameter(Types.STRING, "defaultValue");
1643 method.setAccessModifier(AccessModifier.PUBLIC);
1644 method.setStatic(true);
1646 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1647 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1648 if (types == null) {
1649 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1651 types.add(unionBuilderType);
1655 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1656 final SchemaNode schemaNode) {
1657 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1660 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1661 final SchemaNode schemaNode, final Type baseInterface) {
1662 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1663 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1667 * Instantiates generated type builder with <code>packageName</code> and
1668 * <code>schemaNode</code>.
1670 * The new builder always implements
1671 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1672 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1673 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1675 * If <code>schemaNode</code> is instance of
1676 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1677 * DataNodeContainer} it can also implement nodes which are specified in
1680 * @param packageName
1681 * string with the name of the package to which
1682 * <code>schemaNode</code> belongs.
1684 * schema node for which is created generated type builder
1686 * parent type (can be null)
1687 * @return generated type builder <code>schemaNode</code>
1689 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1690 final Type baseInterface, final ModuleContext context) {
1691 JavaTypeName name = renames.get(schemaNode);
1693 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1696 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1698 it.addImplementsType(baseInterface);
1699 if (!(schemaNode instanceof GroupingDefinition)) {
1700 it.addImplementsType(augmentable(it));
1702 if (schemaNode instanceof DataNodeContainer) {
1703 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1704 groupingsToGenTypes(context, containerSchema.getGroupings());
1705 addImplementedInterfaceFromUses(containerSchema, it);
1712 * Wraps the calling of the same overloaded method.
1714 * @param packageName
1715 * string with the package name to which returning generated type
1718 * schema node which provide data about the schema node name
1719 * @return generated type builder for <code>schemaNode</code>
1721 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1722 final String prefix) {
1723 return addRawInterfaceDefinition(
1724 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1725 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1729 * Returns reference to generated type builder for specified
1730 * <code>schemaNode</code> with <code>packageName</code>.
1732 * Firstly the generated type builder is searched in
1733 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1734 * found it is created and added to <code>genTypeBuilders</code>.
1736 * @param packageName
1737 * string with the package name to which returning generated type
1740 * schema node which provide data about the schema node name
1742 * return type name prefix
1743 * @return generated type builder for <code>schemaNode</code>
1744 * @throws IllegalArgumentException
1746 * <li>if <code>schemaNode</code> is null</li>
1747 * <li>if <code>packageName</code> is null</li>
1748 * <li>if QName of schema node is null</li>
1749 * <li>if schemaNode name is null</li>
1753 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1754 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1755 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1756 final String schemaNodeName = schemaNode.getQName().getLocalName();
1757 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1759 // FIXME: Validation of name conflict
1760 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1761 final Module module = findParentModule(schemaContext, schemaNode);
1762 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1763 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1765 addCodegenInformation(newType, module, schemaNode);
1766 newType.setSchemaPath(schemaNode.getPath());
1767 newType.setModuleName(module.getName());
1769 final String packageName = identifier.packageName();
1770 final String simpleName = identifier.simpleName();
1771 if (!genTypeBuilders.containsKey(packageName)) {
1772 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1773 builders.put(simpleName, newType);
1774 genTypeBuilders.put(packageName, builders);
1776 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1777 if (!builders.containsKey(simpleName)) {
1778 builders.put(simpleName, newType);
1785 * Creates the name of the getter method name from <code>localName</code>.
1788 * string with the name of the getter method
1791 * @return string with the name of the getter method for
1792 * <code>methodName</code> in JAVA method format
1794 public static String getterMethodName(final String localName, final Type returnType) {
1795 final StringBuilder method = new StringBuilder();
1796 if (BOOLEAN.equals(returnType)) {
1797 method.append("is");
1799 method.append("get");
1801 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1802 method.append(name);
1803 return method.toString();
1807 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1809 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1810 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1812 * @param interfaceBuilder generated type builder for which the getter method should be created
1813 * @param returnType type which represents the return type of the getter method
1814 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1815 * @param comment string with comment for the getter method
1816 * @param status status from yang file, for deprecated annotation
1817 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1819 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1820 final SchemaNode node) {
1821 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1822 getterMethodName(node.getQName().getLocalName(), returnType));
1823 getMethod.setReturnType(returnType);
1825 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1826 if (!returnType.getPackageName().isEmpty()) {
1827 // The return type has a package, so it's not a primitive type
1828 getMethod.addAnnotation("javax.annotation", "Nullable");
1830 addComment(getMethod, node);
1836 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1837 * or to <code>genTOBuilder</code> as property.
1839 * @param basePackageName
1840 * string contains the module package name
1842 * data schema node which should be added as getter method to
1843 * <code>typeBuilder</code> or as a property to
1844 * <code>genTOBuilder</code> if is part of the list key
1845 * @param typeBuilder
1846 * generated type builder for the list schema node
1847 * @param genTOBuilder
1848 * generated TO builder for the list keys
1850 * list of string which contains names of the list keys
1853 * @throws IllegalArgumentException
1855 * <li>if <code>schemaNode</code> equals null</li>
1856 * <li>if <code>typeBuilder</code> equals null</li>
1859 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1860 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1861 final List<String> listKeys, final boolean inGrouping) {
1862 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1863 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1865 if (schemaNode instanceof LeafSchemaNode) {
1866 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1867 final String leafName = leaf.getQName().getLocalName();
1868 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1869 if (listKeys.contains(leafName)) {
1871 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1873 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1876 } else if (!schemaNode.isAddedByUses()) {
1877 if (schemaNode instanceof LeafListSchemaNode) {
1878 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1879 } else if (schemaNode instanceof ContainerSchemaNode) {
1880 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1881 (ContainerSchemaNode) schemaNode, inGrouping);
1882 } else if (schemaNode instanceof ChoiceSchemaNode) {
1883 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1884 } else if (schemaNode instanceof ListSchemaNode) {
1885 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1890 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1891 final GeneratedTOBuilder genTOBuilder) {
1892 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1894 if (genTOBuilder != null) {
1895 final GeneratedTransferObject genTO = genTOBuilder.build();
1896 // Add Identifiable.getKey() for items
1897 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1898 .addAnnotation(OVERRIDE_ANNOTATION);
1899 context.addGeneratedTOBuilder(genTOBuilder);
1904 * Selects the names of the list keys from <code>list</code> and returns
1905 * them as the list of the strings
1908 * of string with names of the list keys
1909 * @return list of string which represents names of the list keys. If the
1910 * <code>list</code> contains no keys then the empty list is
1913 private static List<String> listKeys(final ListSchemaNode list) {
1914 final List<String> listKeys = new ArrayList<>();
1916 final List<QName> keyDefinition = list.getKeyDefinition();
1917 if (keyDefinition != null) {
1918 for (final QName keyDef : keyDefinition) {
1919 listKeys.add(keyDef.getLocalName());
1926 * Generates for the <code>list</code> which contains any list keys special
1927 * generated TO builder.
1929 * @param packageName
1930 * string with package name to which the list belongs
1932 * list schema node which is source of data about the list name
1933 * @return generated TO builder which represents the keys of the
1934 * <code>list</code> or null if <code>list</code> is null or list of
1935 * key definitions is null or empty.
1937 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1938 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1939 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1940 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1941 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1947 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1949 * If more then one generated TO builder is created for enclosing then all
1950 * of the generated TO builders are added to <code>typeBuilder</code> as
1951 * enclosing transfer objects.
1954 * type definition which can be of type <code>UnionType</code> or
1955 * <code>BitsTypeDefinition</code>
1956 * @param typeBuilder
1957 * generated type builder to which is added generated TO created
1958 * from <code>typeDef</code>
1960 * string with name for generated TO builder
1961 * @param parentModule
1963 * @return generated TO builder for <code>typeDef</code>
1965 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1966 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1967 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1968 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1971 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1972 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1973 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1974 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1975 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1977 for (GeneratedTOBuilder builder : types) {
1978 if (builder.isUnion()) {
1979 final GeneratedTransferObject type = builder.build();
1980 createUnionBuilder(builder, typeBuilder, type, parentModule);
1984 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1988 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1989 * also added to <code>typeBuilder</code> as enclosing transfer object.
1991 * If more then one generated TO builder is created for enclosing then all
1992 * of the generated TO builders are added to <code>typeBuilder</code> as
1993 * enclosing transfer objects.
1996 * type definition which can be of type <code>UnionType</code> or
1997 * <code>BitsTypeDefinition</code>
1998 * @param typeBuilder
1999 * generated type builder to which is added generated TO created
2000 * from <code>typeDef</code>
2002 * string with name for generated TO builder
2003 * @param parentModule
2005 * @return generated TO builder for <code>typeDef</code>
2007 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
2008 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2009 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
2010 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
2011 typeDef, parentModule.getName());
2012 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2013 return genTOBuilder;
2018 * Adds the implemented types to type builder.
2020 * The method passes through the list of <i>uses</i> in
2021 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2022 * generated type from {@link ModuleContext#groupings
2023 * allGroupings} which is added as <i>implements type</i> to
2024 * <code>builder</code>
2026 * @param dataNodeContainer
2027 * element which contains the list of used YANG groupings
2029 * builder to which are added implemented types according to
2030 * <code>dataNodeContainer</code>
2031 * @return generated type builder with all implemented types
2033 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2034 final GeneratedTypeBuilder builder) {
2035 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2036 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
2037 if (genType == null) {
2038 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2039 + builder.getName());
2042 builder.addImplementsType(genType.build());
2047 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2048 for (final ModuleContext ctx : genCtx.values()) {
2049 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2050 if (result != null) {
2057 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2058 for (final ModuleContext ctx : genCtx.values()) {
2059 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2060 if (result != null) {
2067 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2068 for (final ModuleContext ctx : genCtx.values()) {
2069 final GeneratedTypeBuilder result = ctx.getCase(path);
2070 if (result != null) {
2077 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2078 if (status == Status.DEPRECATED) {
2079 builder.addAnnotation(DEPRECATED_ANNOTATION);