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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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.HashSet;
51 import java.util.Iterator;
52 import java.util.List;
54 import java.util.Optional;
56 import org.eclipse.jdt.annotation.Nullable;
57 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
58 import org.opendaylight.mdsal.binding.model.api.Constant;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
60 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
61 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
62 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
63 import org.opendaylight.mdsal.binding.model.api.Restrictions;
64 import org.opendaylight.mdsal.binding.model.api.Type;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
74 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
75 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
76 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
77 import org.opendaylight.mdsal.binding.model.util.Types;
78 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
79 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
80 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
81 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
82 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
83 import org.opendaylight.yangtools.yang.common.QName;
84 import org.opendaylight.yangtools.yang.common.QNameModule;
85 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
86 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
87 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
92 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
95 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
96 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.Module;
101 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
102 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
103 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
104 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
105 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
107 import org.opendaylight.yangtools.yang.model.api.Status;
108 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
109 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.UsesNode;
111 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
113 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
114 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
115 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
116 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
117 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
118 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
119 import org.slf4j.Logger;
120 import org.slf4j.LoggerFactory;
122 abstract class AbstractTypeGenerator {
123 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
124 private static final Splitter COLON_SPLITTER = Splitter.on(':');
125 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
126 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
127 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
130 * Comparator based on augment target path.
132 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
133 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
134 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
136 while (thisIt.hasNext()) {
137 if (!otherIt.hasNext()) {
141 final int comp = thisIt.next().compareTo(otherIt.next());
147 return otherIt.hasNext() ? -1 : 0;
151 * Constant with the concrete name of identifier.
153 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
156 * Constant with the concrete name of namespace.
158 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
160 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
163 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
164 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
165 * 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 when creating augmentation builder.
177 private final SchemaContext schemaContext;
180 * Holds renamed elements.
182 private final Map<SchemaNode, JavaTypeName> renames;
184 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
185 final Map<SchemaNode, JavaTypeName> renames) {
186 this.schemaContext = requireNonNull(context);
187 this.typeProvider = requireNonNull(typeProvider);
188 this.renames = requireNonNull(renames);
190 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
191 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
192 for (final Module contextModule : contextModules) {
193 contexts.add(moduleToGenTypes(contextModule));
196 contexts.forEach(this::allAugmentsToGenTypes);
199 final Collection<ModuleContext> moduleContexts() {
200 return genCtx.values();
203 final ModuleContext moduleContext(final QNameModule module) {
204 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
207 final AbstractTypeProvider typeProvider() {
211 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
213 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
215 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
216 Set<? extends SchemaNode> nodes);
218 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
220 private ModuleContext moduleToGenTypes(final Module module) {
221 final ModuleContext context = new ModuleContext(module);
222 genCtx.put(module.getQNameModule(), context);
223 allTypeDefinitionsToGenTypes(context);
224 groupingsToGenTypes(context, module.getGroupings());
225 rpcMethodsToGenType(context);
226 allIdentitiesToGenTypes(context);
227 notificationsToGenType(context);
229 if (!module.getChildNodes().isEmpty()) {
230 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
231 context.addModuleNode(moduleType);
232 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
238 * Converts all extended type definitions of module to the list of
239 * <code>Type</code> objects.
242 * module from which is obtained set of type definitions
243 * @throws IllegalArgumentException
245 * <li>if module is null</li>
246 * <li>if name of module is null</li>
248 * @throws IllegalStateException
249 * if set of type definitions from module is null
251 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
252 final Module module = context.module();
253 checkArgument(module.getName() != null, "Module name cannot be NULL.");
254 final DataNodeIterator it = new DataNodeIterator(module);
255 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
256 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
258 for (final TypeDefinition<?> typedef : typeDefinitions) {
259 if (typedef != null) {
260 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
262 context.addTypedefType(typedef, type);
263 context.addTypeToSchema(type,typedef);
269 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
270 final DataSchemaNode node, final boolean inGrouping) {
271 if (node.isAugmenting() || node.isAddedByUses()) {
274 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
275 annotateDeprecatedIfNecessary(node.getStatus(), genType);
277 final Module module = context.module();
278 genType.setModuleName(module.getName());
279 addCodegenInformation(genType, module, node);
280 genType.setSchemaPath(node.getPath());
281 if (node instanceof DataNodeContainer) {
282 context.addChildNodeType(node, genType);
283 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
284 processUsesAugments((DataNodeContainer) node, context, inGrouping);
289 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
290 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
291 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
292 if (genType != null) {
293 constructGetter(parent, genType, node);
294 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
295 actionsToGenType(context, genType, node, null, inGrouping);
299 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
300 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
301 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
302 if (genType != null) {
303 final ParameterizedType listType = listTypeFor(genType);
304 constructGetter(parent, listType, node);
305 constructNonnull(parent, listType, node);
307 final List<String> listKeys = listKeys(node);
308 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
309 if (genTOBuilder != null) {
310 final Type identifierMarker = identifier(genType);
311 final Type identifiableMarker = identifiable(genTOBuilder);
312 genTOBuilder.addImplementsType(identifierMarker);
313 genType.addImplementsType(identifiableMarker);
316 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
318 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
319 if (!schemaNode.isAugmenting()) {
320 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
325 if (genTOBuilder != null) {
326 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
327 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
328 genTOBuilder.setSUID(prop);
331 typeBuildersToGenTypes(context, genType, genTOBuilder);
335 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
336 final boolean inGrouping) {
337 for (final UsesNode usesNode : node.getUses()) {
338 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
339 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
340 processUsesAugments(augment, context, inGrouping);
346 * Converts all <b>augmentation</b> of the module to the list
347 * <code>Type</code> objects.
350 * module from which is obtained list of all augmentation objects
351 * to iterate over them
352 * @throws IllegalArgumentException
354 * <li>if the module is null</li>
355 * <li>if the name of module is null</li>
357 * @throws IllegalStateException
358 * if set of augmentations from module is null
360 private void allAugmentsToGenTypes(final ModuleContext context) {
361 final Module module = context.module();
362 checkArgument(module != null, "Module reference cannot be NULL.");
363 checkArgument(module.getName() != null, "Module name cannot be NULL.");
364 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
366 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
367 augmentationToGenTypes(context, augment);
372 * Returns list of <code>AugmentationSchema</code> objects. The objects are
373 * sorted according to the length of their target path from the shortest to
377 * module from which is obtained list of all augmentation objects
378 * @return list of sorted <code>AugmentationSchema</code> objects obtained
379 * from <code>module</code>
380 * @throws IllegalArgumentException
382 * @throws IllegalStateException
383 * if set of module augmentations is null
385 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
386 checkArgument(module != null, "Module reference cannot be NULL.");
387 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
389 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
390 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
391 sortedAugmentations.sort(AUGMENT_COMP);
393 return sortedAugmentations;
397 * Create GeneratedTypeBuilder object from module argument.
400 * Module object from which builder will be created
401 * @return <code>GeneratedTypeBuilder</code> which is internal
402 * representation of the module
403 * @throws IllegalArgumentException
406 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
407 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
408 final Module module = context.module();
409 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
410 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
412 addCodegenInformation(moduleDataTypeBuilder, module);
413 return moduleDataTypeBuilder;
416 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
417 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
418 for (final ActionDefinition action : parentSchema.getActions()) {
419 final GeneratedType input;
420 final GeneratedType output;
421 if (action.isAddedByUses()) {
422 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
423 input = context.getChildNode(orig.getInput().getPath()).build();
424 output = context.getChildNode(orig.getOutput().getPath()).build();
426 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
427 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
430 if (!(parentSchema instanceof GroupingDefinition)) {
431 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
432 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
433 // and do not capture an actual instantiation.
434 final QName qname = action.getQName();
435 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
436 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
437 BindingMapping.getClassName(qname)));
438 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
439 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
441 annotateDeprecatedIfNecessary(action.getStatus(), builder);
442 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
443 : action(parent, input, output));
445 addCodegenInformation(builder, context.module(), action);
446 context.addChildNodeType(action, builder);
451 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
452 for (UsesNode uses : parent.getUses()) {
453 final GroupingDefinition grp = findUsedGrouping(uses);
454 final Optional<ActionDefinition> found = grp.getActions().stream()
455 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
456 if (found.isPresent()) {
457 final ActionDefinition result = found.get();
458 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
462 return Optional.empty();
465 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
466 final ContainerSchemaNode schema, final boolean inGrouping) {
467 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
468 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
469 return genType.build();
473 * Converts all <b>RPCs</b> input and output substatements of the module
474 * to the list of <code>Type</code> objects. In addition are to containers
475 * and lists which belong to input or output also part of returning list.
478 * module from which is obtained set of all rpc objects to
480 * @throws IllegalArgumentException
482 * <li>if the module is null</li>
483 * <li>if the name of module is null</li>
485 * @throws IllegalStateException
486 * if set of rpcs from module is null
488 private void rpcMethodsToGenType(final ModuleContext context) {
489 final Module module = context.module();
490 checkArgument(module.getName() != null, "Module name cannot be NULL.");
491 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
492 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
493 if (rpcDefinitions.isEmpty()) {
497 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
498 interfaceBuilder.addImplementsType(RPC_SERVICE);
500 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
502 for (final RpcDefinition rpc : rpcDefinitions) {
504 final String rpcName = BindingMapping.getClassName(rpc.getQName());
505 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
506 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
508 // Do not refer to annotation class, as it may not be available at runtime
509 // FIXME: migrate this to some other annotation type and re-enable
511 // method.addAnnotation("javax.annotation", "CheckReturnValue");
512 addComment(method, rpc);
514 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
515 method.setReturnType(listenableFutureTypeFor(
516 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
520 context.addTopLevelNodeType(interfaceBuilder);
523 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
524 final ContainerSchemaNode schema, final Type type) {
525 processUsesAugments(schema, context, false);
526 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
527 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
529 addImplementedInterfaceFromUses(schema, outType);
530 outType.addImplementsType(type);
531 outType.addImplementsType(augmentable(outType));
532 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
533 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
534 context.addChildNodeType(schema, outType);
535 return outType.build();
539 * Converts all <b>notifications</b> of the module to the list of
540 * <code>Type</code> objects. In addition are to this list added containers
541 * and lists which are part of this notification.
544 * module from which is obtained set of all notification objects
545 * to iterate over them
546 * @throws IllegalArgumentException
548 * <li>if the module equals null</li>
549 * <li>if the name of module equals null</li>
551 * @throws IllegalStateException
552 * if set of notifications from module is null
554 private void notificationsToGenType(final ModuleContext context) {
555 final Module module = context.module();
556 checkArgument(module.getName() != null, "Module name cannot be NULL.");
557 final Set<NotificationDefinition> notifications = module.getNotifications();
558 if (notifications.isEmpty()) {
562 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
563 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
565 for (final NotificationDefinition notification : notifications) {
566 if (notification != null) {
567 processUsesAugments(notification, context, false);
569 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
570 context.modulePackageName(), notification, DATA_OBJECT, context);
571 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
572 notificationInterface.addImplementsType(NOTIFICATION);
573 context.addChildNodeType(notification, notificationInterface);
575 // Notification object
576 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
577 notification.getChildNodes(), false);
579 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
580 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
581 .setReturnType(Types.primitiveVoidType()), notification);
585 addCodegenInformation(listenerInterface, module, "notifications", notifications);
586 context.addTopLevelNodeType(listenerInterface);
590 * Converts all <b>identities</b> of the module to the list of
591 * <code>Type</code> objects.
594 * module from which is obtained set of all identity objects to
596 * @param schemaContext
597 * schema context only used as input parameter for method
598 * {@link BindingGeneratorImpl#identityToGenType}
601 private void allIdentitiesToGenTypes(final ModuleContext context) {
602 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
604 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
605 for (final IdentitySchemaNode identity : schemaIdentities) {
606 identityToGenType(context, identity);
612 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
613 * created transport object builder. If identity contains base identity then
614 * reference to base identity is added to superior identity as its extend.
615 * If identity doesn't contain base identity then only reference to abstract
616 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
617 * BaseIdentity} is added
621 * @param basePackageName
622 * string contains the module package name
624 * IdentitySchemaNode which contains data about identity
626 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
627 if (identity == null) {
631 JavaTypeName name = renames.get(identity);
633 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
634 BindingMapping.getClassName(identity.getQName()));
637 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
638 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
639 if (!baseIdentities.isEmpty()) {
640 for (IdentitySchemaNode baseIdentity : baseIdentities) {
641 JavaTypeName base = renames.get(baseIdentity);
643 final QName qname = baseIdentity.getQName();
644 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
645 BindingMapping.getClassName(qname));
648 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
649 newType.addImplementsType(gto);
652 newType.addImplementsType(BASE_IDENTITY);
655 final Module module = context.module();
656 addCodegenInformation(newType, module, identity);
657 newType.setModuleName(module.getName());
658 newType.setSchemaPath(identity.getPath());
660 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
661 identity.getQName().getLocalName());
663 context.addIdentityType(identity, newType);
666 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
667 final JavaTypeName yangModuleInfo, final String localName) {
668 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
669 new SimpleImmutableEntry<>(yangModuleInfo, localName));
673 * Converts all <b>groupings</b> of the module to the list of
674 * <code>Type</code> objects. Firstly are groupings sorted according mutual
675 * dependencies. At least dependent (independent) groupings are in the list
676 * saved at first positions. For every grouping the record is added to map
677 * {@link ModuleContext#groupings allGroupings}
682 * collection of groupings from which types will be generated
685 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
686 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
687 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
688 // node of grouping is resolved to the method.
689 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
690 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
691 context.addGroupingType(grouping, genType);
692 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
693 groupingsToGenTypes(context, grouping.getGroupings());
694 processUsesAugments(grouping, context, true);
695 actionsToGenType(context, genType, grouping, null, true);
700 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
701 * <code>enumTypeDef</code> item is added to builder with its name and value.
703 * @param enumTypeDef EnumTypeDefinition contains enum data
704 * @param enumName string contains name which will be assigned to enumeration builder
705 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
706 * @param module Module in which type should be generated
707 * @return enumeration builder which contains data from <code>enumTypeDef</code>
709 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
710 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
711 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
712 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
713 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
714 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
715 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
722 * Generates type builder for <code>module</code>.
724 * @param module Module which is source of package name for generated type builder
725 * @param postfix string which is added to the module class name representation as suffix
726 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
727 * @throws IllegalArgumentException if <code>module</code> is null
729 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
730 final Module module = context.module();
731 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
732 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
733 JavaTypeName.create(context.modulePackageName(), moduleName));
735 moduleBuilder.setModuleName(moduleName);
736 addCodegenInformation(moduleBuilder, module);
737 return moduleBuilder;
741 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
742 * In addition there are also generated types for all containers, list and choices which are child of
743 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
745 * @param augmentPackageName string with the name of the package to which the augmentation belongs
746 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
747 * @param module current module
748 * @throws IllegalArgumentException
750 * <li>if <code>augmentPackageName</code> equals null</li>
751 * <li>if <code>augSchema</code> equals null</li>
753 * @throws IllegalStateException
754 * if augment target path is null
756 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
757 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
758 checkState(augSchema.getTargetPath() != null,
759 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
761 processUsesAugments(augSchema, context, false);
762 final SchemaPath targetPath = augSchema.getTargetPath();
763 SchemaNode targetSchemaNode = null;
765 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
766 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
767 if (targetSchemaNode instanceof DerivableSchemaNode) {
768 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
770 if (targetSchemaNode == null) {
771 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
772 + " in module " + context.module().getName());
775 if (targetSchemaNode == null) {
776 throw new IllegalArgumentException("augment target not found: " + targetPath);
779 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
780 if (targetTypeBuilder == null) {
781 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
783 if (targetTypeBuilder == null) {
784 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
787 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
788 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
789 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
792 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
793 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
797 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
798 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
799 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
800 checkState(augSchema.getTargetPath() != null,
801 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
803 processUsesAugments(augSchema, context, inGrouping);
804 final SchemaPath targetPath = augSchema.getTargetPath();
805 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
806 if (targetSchemaNode == null) {
807 throw new IllegalArgumentException("augment target not found: " + targetPath);
810 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
811 if (targetTypeBuilder == null) {
812 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
814 if (targetTypeBuilder == null) {
815 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
818 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
819 if (usesNodeParent instanceof SchemaNode) {
820 addRawAugmentGenTypeDefinition(context,
821 packageNameForAugmentedGeneratedType(context.modulePackageName(),
822 ((SchemaNode) usesNodeParent).getPath()),
823 targetTypeBuilder.build(), augSchema, inGrouping);
825 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
828 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
829 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
833 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
834 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
836 if (targetGrouping instanceof GroupingDefinition) {
837 return (GroupingDefinition) targetGrouping;
840 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
844 * Convenient method to find node added by uses statement.
846 * @param targetPath node path
847 * @param parentUsesNode parent of uses node
848 * @return node from its original location in grouping
850 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
851 SchemaNode result = findUsedGrouping(parentUsesNode);
852 for (final QName node : targetPath.getPathFromRoot()) {
853 if (result instanceof DataNodeContainer) {
854 final QName resultNode = node.withModule(result.getQName().getModule());
855 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
856 } else if (result instanceof ChoiceSchemaNode) {
857 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
860 if (result == null) {
864 if (result instanceof DerivableSchemaNode) {
865 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
866 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
867 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
868 result = originalNode.get();
872 if (result instanceof DataSchemaNode) {
873 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
874 if (resultDataSchemaNode.isAddedByUses()) {
875 // The original node is required, but we have only the copy of
876 // the original node.
877 // Maybe this indicates a bug in Yang parser.
878 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
881 return resultDataSchemaNode;
884 throw new IllegalStateException(
885 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
890 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
891 * of augmented node with serial number as suffix.
893 * @param context current module
894 * @param augmentPackageName string with contains the package name to which the augment belongs
895 * @param basePackageName string with the package name to which the augmented node belongs
896 * @param targetTypeRef target type
897 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
898 * @return generated type builder for augment
900 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
901 final String augmentPackageName, final Type targetTypeRef,
902 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
903 Map<String, GeneratedTypeBuilder> augmentBuilders =
904 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
905 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
908 if (augIdentifier != null) {
909 augTypeName = BindingMapping.getClassName(augIdentifier);
911 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
914 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
915 JavaTypeName.create(augmentPackageName, augTypeName));
917 augTypeBuilder.addImplementsType(DATA_OBJECT);
918 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
919 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
920 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
922 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
923 augmentBuilders.put(augTypeName, augTypeBuilder);
925 if (!augSchema.getChildNodes().isEmpty()) {
926 context.addTypeToAugmentation(augTypeBuilder, augSchema);
929 context.addAugmentType(augTypeBuilder);
930 return augTypeBuilder;
933 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
934 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
935 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
939 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
940 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
941 final QName nodeType = unknownSchemaNode.getNodeType();
942 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
943 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
944 return unknownSchemaNode.getNodeParameter();
951 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
952 * consists from name of augmented node and serial number of its augmentation.
954 * @param builders map of builders which were created in the package to which the augmentation belongs
955 * @param genTypeName string with name of augmented node
956 * @return string with unique name for augmentation builder
958 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
960 if (builders != null) {
961 while (builders.containsKey(genTypeName + index)) {
965 return genTypeName + index;
969 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
970 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
971 * already part of them).
973 * @param module current module
974 * @param parent generated type builder which represents any node. The subnodes of this node are added
975 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
977 * @param childOf parent type
978 * @param schemaNodes set of data schema nodes which are the children of the node for which
979 * <code>typeBuilder</code> was created
980 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
981 * child nodes) could be added to it.
983 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
984 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
985 if (schemaNodes != null && parent != null) {
986 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
987 for (final DataSchemaNode schemaNode : schemaNodes) {
988 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
989 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
997 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1000 * @param module current module
1001 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1002 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1003 * container, choice.
1004 * @param childOf parent type
1005 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1007 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1008 * The getter method could be added to it.
1010 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1011 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1012 final boolean inGrouping) {
1013 if (schemaNodes != null && typeBuilder != null) {
1014 final Type baseInterface = childOf(typeBuilder);
1015 for (final DataSchemaNode schemaNode : schemaNodes) {
1016 if (!schemaNode.isAugmenting()) {
1017 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1025 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1027 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1028 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1029 * @param childOf parent type
1030 * @param module current module
1032 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1033 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1034 if (node != null && typeBuilder != null) {
1035 if (node instanceof LeafSchemaNode) {
1036 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1037 } else if (node instanceof LeafListSchemaNode) {
1038 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1039 } else if (node instanceof ContainerSchemaNode) {
1040 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1041 } else if (node instanceof ListSchemaNode) {
1042 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1043 } else if (node instanceof ChoiceSchemaNode) {
1044 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1046 // TODO: anyxml not yet supported
1047 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1048 typeBuilder.getFullyQualifiedName());
1054 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1055 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1056 * and names of all parents node.
1058 * @param context current module
1059 * @param basePackageName string with the module package name
1060 * @param parent parent type
1061 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1063 * @throws IllegalArgumentException
1065 * <li>if <code>basePackageName</code> is null</li>
1066 * <li>if <code>choiceNode</code> is null</li>
1069 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1070 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1071 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1073 if (!choiceNode.isAddedByUses()) {
1074 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1075 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1076 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1077 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1078 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1079 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1081 final GeneratedType choiceType = choiceTypeBuilder.build();
1082 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1084 constructGetter(parent, choiceType, choiceNode);
1089 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1090 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1091 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1092 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1094 * @param context current module context
1095 * @param refChoiceType type which represents superior <i>case</i>
1096 * @param choiceNode choice case node which is mapped to generated type
1097 * @throws IllegalArgumentException
1099 * <li>if <code>refChoiceType</code> equals null</li>
1100 * <li>if <code>caseNodes</code> equals null</li>
1103 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1104 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1105 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1106 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1108 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1109 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1110 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1111 caseTypeBuilder.addImplementsType(refChoiceType);
1112 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1113 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1114 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1115 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1116 if (caseChildNodes != null) {
1117 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1119 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1120 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1122 if (parent instanceof AugmentationSchemaNode) {
1123 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1124 final SchemaPath targetPath = augSchema.getTargetPath();
1125 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1126 if (targetSchemaNode instanceof DataSchemaNode
1127 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1128 if (targetSchemaNode instanceof DerivableSchemaNode) {
1129 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1132 if (targetSchemaNode == null) {
1133 throw new IllegalStateException(
1134 "Failed to find target node from grouping for augmentation " + augSchema
1135 + " in module " + context.module().getName());
1138 parent = targetSchemaNode;
1141 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1142 Type childOfType = findChildNodeByPath(parent.getPath());
1143 if (childOfType == null) {
1144 childOfType = findGroupingByPath(parent.getPath());
1146 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1148 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1153 processUsesAugments(caseNode, context, inGrouping);
1158 * Generates list of generated types for all the cases of a choice which are added to the choice through
1161 * @param module current module
1162 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1163 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1164 * of the augmenting choice will belong to pcg2.
1165 * @param targetType Type which represents target choice
1166 * @param targetNode node which represents target choice
1167 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1169 * @throws IllegalArgumentException
1171 * <li>if <code>basePackageName</code> is null</li>
1172 * <li>if <code>targetType</code> is null</li>
1173 * <li>if <code>augmentedNodes</code> is null</li>
1176 // FIXME: nullness rules need to untangled in this method
1177 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1178 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1179 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1180 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1181 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1182 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1184 for (final DataSchemaNode caseNode : augmentedNodes) {
1185 if (caseNode != null) {
1186 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1187 caseTypeBuilder.addImplementsType(targetType);
1189 CaseSchemaNode node = null;
1190 final String caseLocalName = caseNode.getQName().getLocalName();
1191 if (caseNode instanceof CaseSchemaNode) {
1192 node = (CaseSchemaNode) caseNode;
1193 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1194 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1195 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1196 if (dataSchemaNode instanceof ChoiceSchemaNode
1197 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1198 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1203 node = findNamedCase(targetNode, caseLocalName);
1205 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1206 if (childNodes != null) {
1207 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1210 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1211 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1216 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1217 final SchemaPath nodePath = targetNode.getPath();
1218 final SchemaPath parentSp = nodePath.getParent();
1219 if (parentSp.getParent() == null) {
1220 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1223 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1224 GeneratedTypeBuilder childOfType = null;
1225 if (parent instanceof CaseSchemaNode) {
1226 childOfType = findCaseByPath(parent.getPath());
1227 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1228 childOfType = findChildNodeByPath(parent.getPath());
1229 } else if (parent instanceof GroupingDefinition) {
1230 childOfType = findGroupingByPath(parent.getPath());
1233 if (childOfType == null) {
1234 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1240 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1241 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1242 return cases.isEmpty() ? null : cases.get(0);
1245 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1246 // New parser with encapsulated type
1247 if (leaf.getPath().equals(type.getPath())) {
1251 // Embedded type definition with new parser. Also takes care of the old parser with bits
1252 if (leaf.getPath().equals(type.getPath().getParent())) {
1259 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1260 final List<PatternConstraint> patternConstraints) {
1261 if (!patternConstraints.isEmpty()) {
1262 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1263 .append(BindingMapping.getPropertyName(leafName));
1264 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1265 typeProvider.resolveRegExpressions(patternConstraints));
1270 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1272 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1273 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1274 * @param module Module in which type was defined
1275 * @return boolean value
1277 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1279 * <li>true - in other cases</li>
1282 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1283 final ModuleContext context, final boolean inGrouping) {
1284 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1288 final Module parentModule = findParentModule(schemaContext, leaf);
1289 Type returnType = null;
1291 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1292 if (isInnerType(leaf, typeDef)) {
1293 if (typeDef instanceof EnumTypeDefinition) {
1294 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1295 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1296 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1297 typeBuilder, context);
1298 if (enumBuilder != null) {
1299 returnType = enumBuilder.toInstance(typeBuilder);
1301 typeProvider.putReferencedType(leaf.getPath(), returnType);
1302 } else if (typeDef instanceof UnionTypeDefinition) {
1303 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1304 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1305 // Store the inner type within the union so that we can find the reference for it
1306 context.addInnerTypedefType(typeDef.getPath(), returnType);
1307 } else if (typeDef instanceof BitsTypeDefinition) {
1308 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1310 if (genTOBuilder != null) {
1311 returnType = genTOBuilder.build();
1314 // It is constrained version of already declared type (inner declared type exists,
1315 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1316 // In order to get proper class we need to look up closest derived type
1317 // and apply restrictions from leaf type
1318 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1319 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1320 restrictions, inGrouping);
1321 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1324 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1325 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1326 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1329 if (returnType == null) {
1333 if (typeDef instanceof EnumTypeDefinition) {
1334 typeProvider.putReferencedType(leaf.getPath(), returnType);
1337 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1338 processContextRefExtension(leaf, getter, parentModule);
1342 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1343 // Returns DerivedType in case of new parser.
1344 final TypeDefinition<?> baseType = typeDef.getBaseType();
1345 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1348 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1349 final Module module) {
1350 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1351 final QName nodeType = node.getNodeType();
1352 if ("context-reference".equals(nodeType.getLocalName())) {
1353 final String nodeParam = node.getNodeParameter();
1354 IdentitySchemaNode identity = null;
1355 String basePackageName = null;
1356 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1357 final Iterator<String> iterator = splittedElement.iterator();
1358 final int length = Iterables.size(splittedElement);
1360 identity = findIdentityByName(module.getIdentities(), iterator.next());
1361 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1362 } else if (length == 2) {
1363 final String prefix = iterator.next();
1364 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1365 if (dependentModule == null) {
1366 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1369 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1370 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1372 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1375 if (identity == null) {
1376 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1380 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1381 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1382 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1383 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1388 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1389 for (final IdentitySchemaNode id : identities) {
1390 if (id.getQName().getLocalName().equals(name)) {
1397 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1398 for (final ModuleImport imp : imports) {
1399 if (imp.getPrefix().equals(prefix)) {
1400 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1406 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1407 final boolean isReadOnly) {
1408 if (leaf != null && toBuilder != null) {
1410 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1411 if (typeDef instanceof UnionTypeDefinition) {
1412 // GeneratedType for this type definition should have be already created
1413 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1414 returnType = mc.getTypedefs().get(typeDef.getPath());
1415 if (returnType == null) {
1416 // This may still be an inner type, try to find it
1417 returnType = mc.getInnerType(typeDef.getPath());
1419 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1420 // Annonymous enumeration (already generated, since it is inherited via uses).
1421 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1422 QName qname = originalLeaf.getQName();
1423 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1425 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1427 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1433 * Converts <code>leaf</code> schema node to property of generated TO builder.
1435 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1436 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1437 * @param returnType property type
1438 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1439 * @return boolean value
1441 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1442 * name equals null or if leaf is added by <i>uses</i>.</li>
1443 * <li>true - other cases</li>
1446 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1447 final Type returnType, final boolean isReadOnly) {
1448 if (returnType == null) {
1451 final String leafName = leaf.getQName().getLocalName();
1452 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1453 propBuilder.setReadOnly(isReadOnly);
1454 propBuilder.setReturnType(returnType);
1455 addComment(propBuilder, leaf);
1457 toBuilder.addEqualsIdentity(propBuilder);
1458 toBuilder.addHashIdentity(propBuilder);
1459 toBuilder.addToStringProperty(propBuilder);
1464 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1466 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1467 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1468 * @param module module
1469 * @return boolean value
1471 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1472 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1473 * <li>false - other cases</li>
1476 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1477 final ModuleContext context, final boolean inGrouping) {
1478 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1482 final QName nodeName = node.getQName();
1484 final TypeDefinition<?> typeDef = node.getType();
1485 final Module parentModule = findParentModule(schemaContext, node);
1487 Type returnType = null;
1488 if (typeDef.getBaseType() == null) {
1489 if (typeDef instanceof EnumTypeDefinition) {
1490 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1491 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1492 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1493 typeBuilder, context);
1494 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1495 typeProvider.putReferencedType(node.getPath(), returnType);
1496 } else if (typeDef instanceof UnionTypeDefinition) {
1497 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1498 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1499 } else if (typeDef instanceof BitsTypeDefinition) {
1500 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1501 node, parentModule);
1502 returnType = genTOBuilder.build();
1504 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1505 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1506 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1509 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1510 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1511 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1514 constructGetter(typeBuilder, listTypeFor(returnType), node);
1518 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1519 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1520 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1521 returnTypeBuilder.setIsUnion(true);
1522 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1523 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1524 returnTypeBuilder.setModuleName(parentModule.getName());
1525 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1527 genTOBuilder.setTypedef(true);
1528 genTOBuilder.setIsUnion(true);
1529 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1531 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1535 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1536 final GeneratedTransferObject returnType, final Module parentModule) {
1537 // Append enclosing path hierarchy without dots
1538 final StringBuilder sb = new StringBuilder();
1539 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1540 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1541 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1542 unionBuilder.setIsUnionBuilder(true);
1544 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1545 method.setReturnType(returnType);
1546 method.addParameter(Types.STRING, "defaultValue");
1547 method.setAccessModifier(AccessModifier.PUBLIC);
1548 method.setStatic(true);
1550 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1551 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1554 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1555 final SchemaNode schemaNode) {
1556 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1559 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1560 final SchemaNode schemaNode, final Type baseInterface) {
1561 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1562 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1566 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1567 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1568 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1569 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1570 * If <code>schemaNode</code> is instance of
1571 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1572 * which are specified in <i>uses</i>.
1574 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1575 * @param schemaNode schema node for which is created generated type builder
1576 * @param parent parent type (can be null)
1577 * @return generated type builder <code>schemaNode</code>
1579 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1580 final Type baseInterface, final ModuleContext context) {
1581 JavaTypeName name = renames.get(schemaNode);
1583 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1586 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1588 it.addImplementsType(baseInterface);
1589 if (!(schemaNode instanceof GroupingDefinition)) {
1590 it.addImplementsType(augmentable(it));
1592 if (schemaNode instanceof DataNodeContainer) {
1593 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1594 groupingsToGenTypes(context, containerSchema.getGroupings());
1595 addImplementedInterfaceFromUses(containerSchema, it);
1602 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1603 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1604 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1606 * @param packageName string with the package name to which returning generated type builder belongs
1607 * @param schemaNode schema node which provide data about the schema node name
1608 * @param prefix return type name prefix
1609 * @return generated type builder for <code>schemaNode</code>
1610 * @throws IllegalArgumentException
1612 * <li>if <code>schemaNode</code> is null</li>
1613 * <li>if <code>packageName</code> is null</li>
1614 * <li>if QName of schema node is null</li>
1615 * <li>if schemaNode name is null</li>
1618 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1619 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1620 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1621 final String schemaNodeName = schemaNode.getQName().getLocalName();
1622 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1624 // FIXME: Validation of name conflict
1625 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1626 final Module module = findParentModule(schemaContext, schemaNode);
1627 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1628 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1630 addCodegenInformation(newType, module, schemaNode);
1631 newType.setSchemaPath(schemaNode.getPath());
1632 newType.setModuleName(module.getName());
1634 final String packageName = identifier.packageName();
1635 final String simpleName = identifier.simpleName();
1636 if (!genTypeBuilders.containsKey(packageName)) {
1637 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1638 builders.put(simpleName, newType);
1639 genTypeBuilders.put(packageName, builders);
1641 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1642 if (!builders.containsKey(simpleName)) {
1643 builders.put(simpleName, newType);
1650 * Creates the name of the getter method name from <code>localName</code>.
1652 * @param localName string with the name of the getter method
1653 * @param returnType return type
1654 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1656 public static String getterMethodName(final String localName, final Type returnType) {
1657 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1661 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1662 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1663 * and <code>returnType</code> information are added to the builder.
1665 * @param interfaceBuilder generated type builder for which the getter method should be created
1666 * @param returnType type which represents the return type of the getter method
1667 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1668 * @param comment string with comment for the getter method
1669 * @param status status from yang file, for deprecated annotation
1670 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1672 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1673 final SchemaNode node) {
1674 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1675 getterMethodName(node.getQName().getLocalName(), returnType));
1676 getMethod.setReturnType(returnType);
1678 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1679 addComment(getMethod, node);
1684 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1685 final ListSchemaNode node) {
1686 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1687 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1688 getMethod.setReturnType(returnType).setDefault(true);
1689 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1693 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1696 * @param basePackageName string contains the module package name
1697 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1698 * or as a property to <code>genTOBuilder</code> if is part of the list key
1699 * @param typeBuilder generated type builder for the list schema node
1700 * @param genTOBuilder generated TO builder for the list keys
1701 * @param listKeys list of string which contains names of the list keys
1702 * @param module current module
1703 * @throws IllegalArgumentException
1705 * <li>if <code>schemaNode</code> equals null</li>
1706 * <li>if <code>typeBuilder</code> equals null</li>
1709 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1710 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1711 final List<String> listKeys, final boolean inGrouping) {
1712 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1713 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1715 if (schemaNode instanceof LeafSchemaNode) {
1716 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1717 final String leafName = leaf.getQName().getLocalName();
1718 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1719 if (listKeys.contains(leafName)) {
1721 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1723 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1726 } else if (!schemaNode.isAddedByUses()) {
1727 if (schemaNode instanceof LeafListSchemaNode) {
1728 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1729 } else if (schemaNode instanceof ContainerSchemaNode) {
1730 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1731 (ContainerSchemaNode) schemaNode, inGrouping);
1732 } else if (schemaNode instanceof ChoiceSchemaNode) {
1733 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1734 } else if (schemaNode instanceof ListSchemaNode) {
1735 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1740 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1741 final GeneratedTOBuilder genTOBuilder) {
1742 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1744 if (genTOBuilder != null) {
1745 final GeneratedTransferObject genTO = genTOBuilder.build();
1746 // Add Identifiable.getKey() for items
1747 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1748 .addAnnotation(OVERRIDE_ANNOTATION);
1749 context.addGeneratedTOBuilder(genTOBuilder);
1754 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1756 * @param list of string with names of the list keys
1757 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1758 * an empty list is returned.
1760 private static List<String> listKeys(final ListSchemaNode list) {
1761 final List<String> listKeys = new ArrayList<>();
1763 final List<QName> keyDefinition = list.getKeyDefinition();
1764 if (keyDefinition != null) {
1765 for (final QName keyDef : keyDefinition) {
1766 listKeys.add(keyDef.getLocalName());
1773 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1775 * @param packageName string with package name to which the list belongs
1776 * @param list list schema node which is source of data about the list name
1777 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1778 * null or list of key definitions is null or empty.
1780 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1781 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1782 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1783 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1784 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1790 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1791 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1792 * enclosing transfer objects.
1794 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1795 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1796 * @param leaf string with name for generated TO builder
1797 * @param parentModule parent module
1798 * @return generated TO builder for <code>typeDef</code>
1800 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1801 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1802 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1803 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1805 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1806 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1807 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1808 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1809 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1811 for (GeneratedTOBuilder builder : types) {
1812 if (builder.isUnion()) {
1813 final GeneratedTransferObject type = builder.build();
1814 createUnionBuilder(builder, typeBuilder, type, parentModule);
1818 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1822 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1823 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1824 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1827 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1828 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1829 * @param leaf string with name for generated TO builder
1830 * @param parentModule parent module
1831 * @return generated TO builder for <code>typeDef</code>
1833 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1834 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1835 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1836 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1837 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1838 return genTOBuilder;
1842 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1843 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1844 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1845 * to <code>builder</code>
1847 * @param dataNodeContainer element which contains the list of used YANG groupings
1848 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1849 * @return generated type builder with all implemented types
1851 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1852 final GeneratedTypeBuilder builder) {
1853 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1854 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1855 if (genType == null) {
1856 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1857 + builder.getName());
1860 builder.addImplementsType(genType.build());
1865 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1866 for (final ModuleContext ctx : genCtx.values()) {
1867 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1868 if (result != null) {
1875 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1876 for (final ModuleContext ctx : genCtx.values()) {
1877 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1878 if (result != null) {
1885 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1886 for (final ModuleContext ctx : genCtx.values()) {
1887 final GeneratedTypeBuilder result = ctx.getCase(path);
1888 if (result != null) {
1895 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1896 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1897 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1900 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1901 if (status == Status.DEPRECATED) {
1902 builder.addAnnotation(DEPRECATED_ANNOTATION);