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.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.mapTypeFor;
45 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveBooleanType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
47 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
48 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
50 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
51 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
53 import com.google.common.base.Splitter;
54 import com.google.common.collect.Iterables;
55 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
56 import java.util.AbstractMap.SimpleImmutableEntry;
57 import java.util.ArrayList;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.Comparator;
61 import java.util.HashMap;
62 import java.util.HashSet;
63 import java.util.Iterator;
64 import java.util.List;
66 import java.util.Optional;
67 import org.eclipse.jdt.annotation.NonNull;
68 import org.eclipse.jdt.annotation.Nullable;
69 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
70 import org.opendaylight.mdsal.binding.model.api.Constant;
71 import org.opendaylight.mdsal.binding.model.api.DefaultType;
72 import org.opendaylight.mdsal.binding.model.api.Enumeration;
73 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
74 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
75 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
76 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
77 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
78 import org.opendaylight.mdsal.binding.model.api.Restrictions;
79 import org.opendaylight.mdsal.binding.model.api.Type;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
87 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
88 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
89 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
90 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
91 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
92 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
93 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
94 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
95 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
96 import org.opendaylight.yangtools.yang.common.QName;
97 import org.opendaylight.yangtools.yang.common.QNameModule;
98 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
99 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
106 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
108 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
111 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
112 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
113 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
114 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.Module;
120 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
121 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
122 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
123 import org.opendaylight.yangtools.yang.model.api.OutputSchemaNode;
124 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
125 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
127 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
128 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
129 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.UsesNode;
131 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
132 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
133 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
134 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
135 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
136 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
137 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
138 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
139 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
140 import org.slf4j.Logger;
141 import org.slf4j.LoggerFactory;
143 abstract class AbstractTypeGenerator {
144 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
145 private static final Splitter COLON_SPLITTER = Splitter.on(':');
146 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
147 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
148 private static final JavaTypeName CHECK_RETURN_VALUE_ANNOTATION =
149 // Do not refer to annotation class, as it may not be available at runtime
150 JavaTypeName.create("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
151 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
154 * Comparator based on augment target path.
156 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
157 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
158 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
160 while (thisIt.hasNext()) {
161 if (!otherIt.hasNext()) {
165 final int comp = thisIt.next().compareTo(otherIt.next());
171 return otherIt.hasNext() ? -1 : 0;
175 * Constant with the concrete name of identifier.
177 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
180 * Constant with the concrete name of namespace.
182 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
184 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
187 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
188 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
189 * for schema node specified in key part.
191 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
194 * Provide methods for converting YANG types to JAVA types.
196 private final AbstractTypeProvider typeProvider;
199 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
201 private final @NonNull EffectiveModelContext schemaContext;
204 * Holds renamed elements.
206 private final Map<SchemaNode, JavaTypeName> renames;
208 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
209 final Map<SchemaNode, JavaTypeName> renames) {
210 this.schemaContext = requireNonNull(context);
211 this.typeProvider = requireNonNull(typeProvider);
212 this.renames = requireNonNull(renames);
214 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
215 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
216 for (final Module contextModule : contextModules) {
217 contexts.add(moduleToGenTypes(contextModule));
220 contexts.forEach(this::allAugmentsToGenTypes);
223 final @NonNull EffectiveModelContext schemaContext() {
224 return schemaContext;
227 final Collection<ModuleContext> moduleContexts() {
228 return genCtx.values();
231 final ModuleContext moduleContext(final QNameModule module) {
232 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
235 final AbstractTypeProvider typeProvider() {
239 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
241 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
243 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
244 Collection<? extends SchemaNode> nodes);
246 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
248 abstract void addRpcMethodComment(TypeMemberBuilder<?> genType, RpcDefinition node);
250 private ModuleContext moduleToGenTypes(final Module module) {
251 final ModuleContext context = new ModuleContext(module);
252 genCtx.put(module.getQNameModule(), context);
253 allTypeDefinitionsToGenTypes(context);
254 groupingsToGenTypes(context, module.getGroupings());
255 allIdentitiesToGenTypes(context);
257 if (!module.getChildNodes().isEmpty()) {
258 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
259 context.addModuleNode(moduleType);
260 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
263 // Resolve RPCs and notifications only after we have created instantiated tree
264 rpcMethodsToGenType(context);
265 notificationsToGenType(context);
270 * Converts all extended type definitions of module to the list of
271 * <code>Type</code> objects.
274 * module from which is obtained set of type definitions
275 * @throws IllegalArgumentException
277 * <li>if module is null</li>
278 * <li>if name of module is null</li>
280 * @throws IllegalStateException
281 * if set of type definitions from module is null
283 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
284 final Module module = context.module();
285 checkArgument(module.getName() != null, "Module name cannot be NULL.");
287 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
288 if (typedef != null) {
289 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
291 context.addTypedefType(typedef, type);
292 context.addTypeToSchema(type,typedef);
298 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
299 final DataSchemaNode node, final boolean inGrouping) {
300 if (node.isAugmenting() || node.isAddedByUses()) {
303 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
304 addConcreteInterfaceMethods(genType);
305 annotateDeprecatedIfNecessary(node, genType);
307 final Module module = context.module();
308 genType.setModuleName(module.getName());
309 addCodegenInformation(genType, module, node);
310 genType.setSchemaPath(node.getPath());
311 if (node instanceof DataNodeContainer) {
312 context.addChildNodeType(node, genType);
313 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
314 processUsesAugments((DataNodeContainer) node, context, inGrouping);
319 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
320 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
321 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
322 if (genType != null) {
323 constructGetter(parent, genType, node);
324 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
325 actionsToGenType(context, genType, node, null, inGrouping);
326 notificationsToGenType(context, genType, node, null, inGrouping);
330 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
331 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
332 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
333 if (genType != null) {
334 final List<String> listKeys = listKeys(node);
335 final GeneratedTOBuilder keyTypeBuilder;
336 if (!listKeys.isEmpty()) {
337 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
338 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
339 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
340 .addImplementsType(identifier(genType));
341 genType.addImplementsType(identifiable(keyTypeBuilder));
343 keyTypeBuilder = null;
346 // Decide whether to generate a List or a Map
347 final ParameterizedType listType;
348 if (keyTypeBuilder != null && !node.isUserOrdered()) {
349 listType = mapTypeFor(keyTypeBuilder, genType);
351 listType = listTypeFor(genType);
354 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
355 constructNonnull(parent, listType, node);
357 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
358 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
360 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
361 if (!schemaNode.isAugmenting()) {
362 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
367 if (keyTypeBuilder != null) {
368 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
369 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
370 keyTypeBuilder.setSUID(prop);
373 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
377 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
378 final boolean inGrouping) {
379 for (final UsesNode usesNode : node.getUses()) {
380 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
381 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
382 processUsesAugments(augment, context, inGrouping);
388 * Converts all <b>augmentation</b> of the module to the list
389 * <code>Type</code> objects.
392 * module from which is obtained list of all augmentation objects
393 * to iterate over them
394 * @throws IllegalArgumentException
396 * <li>if the module is null</li>
397 * <li>if the name of module is null</li>
399 * @throws IllegalStateException
400 * if set of augmentations from module is null
402 private void allAugmentsToGenTypes(final ModuleContext context) {
403 final Module module = context.module();
404 checkArgument(module != null, "Module reference cannot be NULL.");
405 checkArgument(module.getName() != null, "Module name cannot be NULL.");
406 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
408 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
409 augmentationToGenTypes(context, augment);
414 * Returns list of <code>AugmentationSchema</code> objects. The objects are
415 * sorted according to the length of their target path from the shortest to
419 * module from which is obtained list of all augmentation objects
420 * @return list of sorted <code>AugmentationSchema</code> objects obtained
421 * from <code>module</code>
422 * @throws IllegalArgumentException
424 * @throws IllegalStateException
425 * if set of module augmentations is null
427 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
428 checkArgument(module != null, "Module reference cannot be NULL.");
429 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
431 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
432 sortedAugmentations.sort(AUGMENT_COMP);
434 return sortedAugmentations;
438 * Create GeneratedTypeBuilder object from module argument.
441 * Module object from which builder will be created
442 * @return <code>GeneratedTypeBuilder</code> which is internal
443 * representation of the module
444 * @throws IllegalArgumentException
447 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
448 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
449 final Module module = context.module();
450 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
451 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
452 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
453 // top level DataRoot object
454 if (module.getUses().size() > 1) {
455 narrowImplementedInterface(moduleDataTypeBuilder);
458 addCodegenInformation(moduleDataTypeBuilder, module);
459 return moduleDataTypeBuilder;
462 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
463 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
464 for (final ActionDefinition action : parentSchema.getActions()) {
465 if (action.isAugmenting()) {
469 final GeneratedType input;
470 final GeneratedType output;
471 if (action.isAddedByUses()) {
472 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
473 // Original definition may live in a different module, make sure we account for that
474 final ModuleContext origContext = moduleContext(
475 orig.getPath().getPathFromRoot().iterator().next().getModule());
476 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
477 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
479 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
480 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
483 if (!(parentSchema instanceof GroupingDefinition)) {
484 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
485 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
486 // and do not capture an actual instantiation.
487 final QName qname = action.getQName();
488 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
489 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
490 BindingMapping.getClassName(qname)));
491 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
493 annotateDeprecatedIfNecessary(action, builder);
494 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
495 : action(parent, input, output));
497 addCodegenInformation(builder, context.module(), action);
498 context.addChildNodeType(action, builder);
503 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
504 final QName qname = action.getQName();
505 for (UsesNode uses : parent.getUses()) {
506 final GroupingDefinition grp = uses.getSourceGrouping();
507 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
509 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
510 if (found.isPresent()) {
511 final ActionDefinition result = found.get();
512 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
516 return Optional.empty();
519 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
520 final ContainerLike schema, final boolean inGrouping) {
521 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
522 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
523 return genType.build();
527 * Converts all <b>RPCs</b> input and output substatements of the module
528 * to the list of <code>Type</code> objects. In addition are to containers
529 * and lists which belong to input or output also part of returning list.
532 * module from which is obtained set of all rpc objects to
534 * @throws IllegalArgumentException
536 * <li>if the module is null</li>
537 * <li>if the name of module is null</li>
539 * @throws IllegalStateException
540 * if set of rpcs from module is null
542 private void rpcMethodsToGenType(final ModuleContext context) {
543 final Module module = context.module();
544 checkArgument(module.getName() != null, "Module name cannot be NULL.");
545 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
546 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
547 if (rpcDefinitions.isEmpty()) {
551 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
552 interfaceBuilder.addImplementsType(RPC_SERVICE);
554 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
556 for (final RpcDefinition rpc : rpcDefinitions) {
558 final String rpcName = BindingMapping.getClassName(rpc.getQName());
559 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
560 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
562 // Do not refer to annotation class, as it may not be available at runtime
563 method.addAnnotation(CHECK_RETURN_VALUE_ANNOTATION);
564 addRpcMethodComment(method, rpc);
566 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
567 method.setReturnType(listenableFutureTypeFor(
568 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
572 context.addTopLevelNodeType(interfaceBuilder);
575 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
576 final ContainerLike schema, final Type type) {
577 processUsesAugments(schema, context, false);
578 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
579 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
581 addImplementedInterfaceFromUses(schema, outType);
582 outType.addImplementsType(type);
583 outType.addImplementsType(augmentable(outType));
584 addConcreteInterfaceMethods(outType);
585 annotateDeprecatedIfNecessary(rpc, outType);
586 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
587 context.addChildNodeType(schema, outType);
588 return outType.build();
592 * Converts all <b>notifications</b> of the module to the list of
593 * <code>Type</code> objects. In addition are to this list added containers
594 * and lists which are part of this notification.
597 * module from which is obtained set of all notification objects
598 * to iterate over them
599 * @throws IllegalArgumentException
601 * <li>if the module equals null</li>
602 * <li>if the name of module equals null</li>
604 * @throws IllegalStateException
605 * if set of notifications from module is null
607 private void notificationsToGenType(final ModuleContext context) {
608 final Module module = context.module();
609 checkArgument(module.getName() != null, "Module name cannot be NULL.");
610 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
611 if (notifications.isEmpty()) {
615 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
616 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
618 for (final NotificationDefinition notification : notifications) {
619 if (notification != null) {
620 processUsesAugments(notification, context, false);
622 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
623 context.modulePackageName(), notification, DATA_OBJECT, context);
624 addConcreteInterfaceMethods(notificationInterface);
625 annotateDeprecatedIfNecessary(notification, notificationInterface);
626 notificationInterface.addImplementsType(NOTIFICATION);
627 context.addChildNodeType(notification, notificationInterface);
629 // Notification object
630 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
631 notification.getChildNodes(), false);
633 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
634 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
635 .setReturnType(primitiveVoidType()), notification);
639 addCodegenInformation(listenerInterface, module, "notifications", notifications);
640 context.addTopLevelNodeType(listenerInterface);
643 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
644 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
645 final boolean inGrouping) {
646 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
647 if (notifications.isEmpty()) {
651 for (NotificationDefinition notif : notifications) {
652 if (notif.isAugmenting()) {
655 if (parentSchema instanceof GroupingDefinition) {
656 // Notifications cannot be really established, as they lack instantiation context, which would be
657 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
661 processUsesAugments(notif, context, false);
663 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
664 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
665 addConcreteInterfaceMethods(notifInterface);
666 annotateDeprecatedIfNecessary(notif, notifInterface);
668 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
669 : instanceNotification(notifInterface, parent));
670 context.addChildNodeType(notif, notifInterface);
672 // Notification object
673 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
678 * Converts all <b>identities</b> of the module to the list of
679 * <code>Type</code> objects.
682 * module from which is obtained set of all identity objects to
684 * @param schemaContext
685 * schema context only used as input parameter for method
686 * {@link BindingGeneratorImpl#identityToGenType}
689 private void allIdentitiesToGenTypes(final ModuleContext context) {
690 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
692 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
693 for (final IdentitySchemaNode identity : schemaIdentities) {
694 identityToGenType(context, identity);
700 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
701 * created transport object builder. If identity contains base identity then
702 * reference to base identity is added to superior identity as its extend.
703 * If identity doesn't contain base identity then only reference to abstract
704 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
705 * BaseIdentity} is added
709 * @param basePackageName
710 * string contains the module package name
712 * IdentitySchemaNode which contains data about identity
714 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
715 if (identity == null) {
719 JavaTypeName name = renames.get(identity);
721 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
722 BindingMapping.getClassName(identity.getQName()));
725 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
726 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
727 if (!baseIdentities.isEmpty()) {
728 for (IdentitySchemaNode baseIdentity : baseIdentities) {
729 JavaTypeName base = renames.get(baseIdentity);
731 final QName qname = baseIdentity.getQName();
732 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
733 BindingMapping.getClassName(qname));
736 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
737 newType.addImplementsType(gto);
740 newType.addImplementsType(BASE_IDENTITY);
743 final Module module = context.module();
744 addCodegenInformation(newType, module, identity);
745 newType.setModuleName(module.getName());
746 newType.setSchemaPath(identity.getPath());
748 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
750 context.addIdentityType(identity, newType);
753 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
754 final JavaTypeName yangModuleInfo, final String localName) {
755 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
756 new SimpleImmutableEntry<>(yangModuleInfo, localName));
760 * Converts all <b>groupings</b> of the module to the list of
761 * <code>Type</code> objects. Firstly are groupings sorted according mutual
762 * dependencies. At least dependent (independent) groupings are in the list
763 * saved at first positions. For every grouping the record is added to map
764 * {@link ModuleContext#groupings allGroupings}
769 * collection of groupings from which types will be generated
772 private void groupingsToGenTypes(final ModuleContext context,
773 final Collection<? extends GroupingDefinition> groupings) {
774 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
775 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
776 // node of grouping is resolved to the method.
777 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
778 narrowImplementedInterface(genType);
779 annotateDeprecatedIfNecessary(grouping, genType);
780 context.addGroupingType(grouping, genType);
781 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
782 groupingsToGenTypes(context, grouping.getGroupings());
783 processUsesAugments(grouping, context, true);
784 actionsToGenType(context, genType, grouping, null, true);
785 notificationsToGenType(context, genType, grouping, null, true);
790 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
791 * <code>enumTypeDef</code> item is added to builder with its name and value.
793 * @param enumTypeDef EnumTypeDefinition contains enum data
794 * @param enumName string contains name which will be assigned to enumeration builder
795 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
796 * @param module Module in which type should be generated
797 * @return enumeration builder which contains data from <code>enumTypeDef</code>
799 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
800 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
801 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
802 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
803 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
804 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
805 context.addTypeToSchema(ret, enumTypeDef);
806 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
811 * Generates type builder for <code>module</code>.
813 * @param module Module which is source of package name for generated type builder
814 * @param postfix string which is added to the module class name representation as suffix
815 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
816 * @throws IllegalArgumentException if <code>module</code> is null
818 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
819 final Module module = context.module();
820 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
821 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
822 JavaTypeName.create(context.modulePackageName(), moduleName));
824 moduleBuilder.setModuleName(moduleName);
825 addCodegenInformation(moduleBuilder, module);
826 return moduleBuilder;
830 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
831 * In addition there are also generated types for all containers, list and choices which are child of
832 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
834 * @param augmentPackageName string with the name of the package to which the augmentation belongs
835 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
836 * @param module current module
837 * @throws IllegalArgumentException
839 * <li>if <code>augmentPackageName</code> equals null</li>
840 * <li>if <code>augSchema</code> equals null</li>
842 * @throws IllegalStateException
843 * if augment target path is null
845 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
846 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
847 checkState(augSchema.getTargetPath() != null,
848 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
850 processUsesAugments(augSchema, context, false);
851 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
852 SchemaNode targetSchemaNode = null;
854 // FIXME: can we use findDataSchemaNode() instead?
855 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
856 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
857 if (targetSchemaNode instanceof DerivableSchemaNode) {
858 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
860 if (targetSchemaNode == null) {
861 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
862 + " in module " + context.module().getName());
865 if (targetSchemaNode == null) {
866 throw new IllegalArgumentException("augment target not found: " + targetPath);
869 if (targetSchemaNode instanceof ChoiceSchemaNode) {
870 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
871 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
872 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
873 augSchema.getChildNodes(), null, false);
877 final JavaTypeName targetName;
878 if (targetSchemaNode instanceof CaseSchemaNode) {
879 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
880 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
881 targetName = builder.getIdentifier();
883 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
884 if (builder == null) {
885 targetName = findAliasByPath(targetSchemaNode.getPath());
886 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
888 targetName = builder.getIdentifier();
892 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
895 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
896 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
897 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
898 checkState(augSchema.getTargetPath() != null,
899 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
901 processUsesAugments(augSchema, context, inGrouping);
902 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
903 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
904 if (targetSchemaNode == null) {
905 throw new IllegalArgumentException("augment target not found: " + targetPath);
908 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
909 if (targetTypeBuilder == null) {
910 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
912 if (targetTypeBuilder == null) {
913 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
916 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
917 if (usesNodeParent instanceof SchemaNode) {
918 addRawAugmentGenTypeDefinition(context,
919 packageNameForAugmentedGeneratedType(context.modulePackageName(),
920 ((SchemaNode) usesNodeParent).getPath()),
921 targetTypeBuilder.build(), augSchema, inGrouping);
923 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
926 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
927 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
932 * Convenient method to find node added by uses statement.
934 * @param targetPath node path
935 * @param parentUsesNode parent of uses node
936 * @return node from its original location in grouping
938 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
939 final UsesNode parentUsesNode) {
940 SchemaNode result = parentUsesNode.getSourceGrouping();
941 for (final QName node : targetPath.getNodeIdentifiers()) {
942 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
943 if (result instanceof DataNodeContainer) {
944 final QName resultNode = node.bindTo(result.getQName().getModule());
946 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
948 if (result instanceof ActionNodeContainer) {
949 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
951 if (found == null && result instanceof NotificationNodeContainer) {
952 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
956 } else if (result instanceof ChoiceSchemaNode) {
957 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
958 } else if (result instanceof ActionDefinition) {
959 final ActionDefinition action = (ActionDefinition) result;
960 final QName resultNode = node.bindTo(result.getQName().getModule());
962 final InputSchemaNode input = action.getInput();
963 final OutputSchemaNode output = action.getOutput();
964 if (resultNode.equals(input.getQName())) {
966 } else if (resultNode.equals(output.getQName())) {
971 } else if (result != null) {
972 throw new IllegalStateException("Cannot handle " + result);
975 if (result == null) {
979 if (result instanceof DerivableSchemaNode) {
980 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
981 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
982 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
983 result = originalNode.get();
987 if (result instanceof DataSchemaNode) {
988 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
989 if (resultDataSchemaNode.isAddedByUses()) {
990 // The original node is required, but we have only the copy of
991 // the original node.
992 // Maybe this indicates a bug in Yang parser.
993 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
996 return resultDataSchemaNode;
999 throw new IllegalStateException(
1000 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
1005 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
1006 * of augmented node with serial number as suffix.
1008 * @param context current module
1009 * @param augmentPackageName string with contains the package name to which the augment belongs
1010 * @param basePackageName string with the package name to which the augmented node belongs
1011 * @param targetTypeRef target type
1012 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1013 * @return generated type builder for augment
1015 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1016 final String augmentPackageName, final Type targetTypeRef,
1017 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1018 Map<String, GeneratedTypeBuilder> augmentBuilders =
1019 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1020 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1023 if (augIdentifier != null) {
1024 augTypeName = BindingMapping.getClassName(augIdentifier);
1026 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1029 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1030 JavaTypeName.create(augmentPackageName, augTypeName));
1032 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1033 addConcreteInterfaceMethods(augTypeBuilder);
1035 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1036 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1038 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1039 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1040 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1042 augmentBuilders.put(augTypeName, augTypeBuilder);
1044 if (!augSchema.getChildNodes().isEmpty()) {
1045 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1048 context.addAugmentType(augTypeBuilder);
1049 return augTypeBuilder;
1052 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1053 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1054 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1058 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1059 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1060 final QName nodeType = unknownSchemaNode.getNodeType();
1061 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1062 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1063 return unknownSchemaNode.getNodeParameter();
1070 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1071 * consists from name of augmented node and serial number of its augmentation.
1073 * @param builders map of builders which were created in the package to which the augmentation belongs
1074 * @param genTypeName string with name of augmented node
1075 * @return string with unique name for augmentation builder
1077 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1079 if (builders != null) {
1080 while (builders.containsKey(genTypeName + index)) {
1084 return genTypeName + index;
1088 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1089 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1090 * already part of them).
1092 * @param module current module
1093 * @param parent generated type builder which represents any node. The subnodes of this node are added
1094 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1095 * container, choice.
1096 * @param childOf parent type
1097 * @param schemaNodes set of data schema nodes which are the children of the node for which
1098 * <code>typeBuilder</code> was created
1099 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1100 * child nodes) could be added to it.
1102 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1103 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1104 final boolean inGrouping) {
1105 if (schemaNodes != null && parent != null) {
1106 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1107 for (final DataSchemaNode schemaNode : schemaNodes) {
1108 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1109 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1117 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1120 * @param module current module
1121 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1122 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1123 * container, choice.
1124 * @param childOf parent type
1125 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1127 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1128 * The getter method could be added to it.
1130 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1131 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1132 final boolean inGrouping) {
1133 if (schemaNodes != null && typeBuilder != null) {
1134 final Type baseInterface = childOf(typeBuilder);
1135 for (final DataSchemaNode schemaNode : schemaNodes) {
1136 if (!schemaNode.isAugmenting()) {
1137 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1145 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1147 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1148 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1149 * @param childOf parent type
1150 * @param module current module
1152 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1153 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1154 if (node != null && typeBuilder != null) {
1155 if (node instanceof LeafSchemaNode) {
1156 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1157 } else if (node instanceof LeafListSchemaNode) {
1158 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1159 } else if (node instanceof ContainerSchemaNode) {
1160 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1161 } else if (node instanceof ListSchemaNode) {
1162 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1163 } else if (node instanceof ChoiceSchemaNode) {
1164 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1165 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1166 opaqueToGeneratedType(context, typeBuilder, node);
1168 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1169 typeBuilder.getFullyQualifiedName());
1175 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1176 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1177 * and names of all parents node.
1179 * @param context current module
1180 * @param basePackageName string with the module package name
1181 * @param parent parent type
1182 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1184 * @throws IllegalArgumentException
1186 * <li>if <code>basePackageName</code> is null</li>
1187 * <li>if <code>choiceNode</code> is null</li>
1190 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1191 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1192 if (!choiceNode.isAddedByUses()) {
1193 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1194 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1195 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1196 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1197 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1198 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1200 final GeneratedType choiceType = choiceTypeBuilder.build();
1201 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1203 constructGetter(parent, choiceType, choiceNode);
1207 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1208 final DataSchemaNode anyNode) {
1209 if (!anyNode.isAddedByUses()) {
1210 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1211 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1212 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1213 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1214 defaultImplementedInterace(anyxmlTypeBuilder);
1215 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1216 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1218 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1223 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1224 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1225 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1226 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1228 * @param context current module context
1229 * @param refChoiceType type which represents superior <i>case</i>
1230 * @param choiceNode choice case node which is mapped to generated type
1231 * @throws IllegalArgumentException
1233 * <li>if <code>refChoiceType</code> equals null</li>
1234 * <li>if <code>caseNodes</code> equals null</li>
1237 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1238 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1239 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1240 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1242 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1243 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1244 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1245 caseTypeBuilder.addImplementsType(refChoiceType);
1246 addConcreteInterfaceMethods(caseTypeBuilder);
1247 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1248 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1249 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1250 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1251 if (caseChildNodes != null) {
1252 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1254 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1255 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1257 if (parent instanceof AugmentationSchemaNode) {
1258 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1259 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1260 // FIXME: can we use findDataSchemaNode?
1261 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1262 targetPath.getNodeIdentifiers());
1263 if (targetSchemaNode instanceof DataSchemaNode
1264 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1265 if (targetSchemaNode instanceof DerivableSchemaNode) {
1266 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1269 if (targetSchemaNode == null) {
1270 throw new IllegalStateException(
1271 "Failed to find target node from grouping for augmentation " + augSchema
1272 + " in module " + context.module().getName());
1275 parent = targetSchemaNode;
1278 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1279 Type childOfType = findChildNodeByPath(parent.getPath());
1280 if (childOfType == null) {
1281 childOfType = findGroupingByPath(parent.getPath());
1283 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1285 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1290 processUsesAugments(caseNode, context, inGrouping);
1295 * Generates list of generated types for all the cases of a choice which are added to the choice through
1298 * @param module current module
1299 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1300 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1301 * of the augmenting choice will belong to pcg2.
1302 * @param targetType Type which represents target choice
1303 * @param targetNode node which represents target choice
1304 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1306 * @throws IllegalArgumentException
1308 * <li>if <code>basePackageName</code> is null</li>
1309 * <li>if <code>targetType</code> is null</li>
1310 * <li>if <code>augmentedNodes</code> is null</li>
1313 // FIXME: nullness rules need to untangled in this method
1314 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1315 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1316 final Type targetType, final ChoiceSchemaNode targetNode,
1317 final Iterable<? extends DataSchemaNode> augmentedNodes,
1318 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1319 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1320 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1322 for (final DataSchemaNode caseNode : augmentedNodes) {
1323 if (caseNode != null) {
1324 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1325 caseTypeBuilder.addImplementsType(targetType);
1326 addConcreteInterfaceMethods(caseTypeBuilder);
1328 CaseSchemaNode node = null;
1329 final String caseLocalName = caseNode.getQName().getLocalName();
1330 if (caseNode instanceof CaseSchemaNode) {
1331 node = (CaseSchemaNode) caseNode;
1332 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1333 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1334 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1335 if (dataSchemaNode instanceof ChoiceSchemaNode
1336 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1337 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1342 node = findNamedCase(targetNode, caseLocalName);
1344 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1345 if (childNodes != null) {
1346 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1349 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1350 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1355 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1356 final SchemaPath nodePath = targetNode.getPath();
1357 final SchemaPath parentSp = nodePath.getParent();
1358 if (parentSp.getParent() == null) {
1359 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1362 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1363 GeneratedTypeBuilder childOfType = null;
1364 if (parent instanceof CaseSchemaNode) {
1365 childOfType = findCaseByPath(parent.getPath());
1366 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1367 childOfType = findChildNodeByPath(parent.getPath());
1368 } else if (parent instanceof GroupingDefinition) {
1369 childOfType = findGroupingByPath(parent.getPath());
1372 if (childOfType == null) {
1373 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1379 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1380 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1381 return cases.isEmpty() ? null : cases.get(0);
1384 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1385 // New parser with encapsulated type
1386 if (leaf.getPath().equals(type.getPath())) {
1390 // Embedded type definition with new parser. Also takes care of the old parser with bits
1391 if (leaf.getPath().equals(type.getPath().getParent())) {
1398 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1399 final List<PatternConstraint> patternConstraints) {
1400 if (!patternConstraints.isEmpty()) {
1401 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1402 .append(BindingMapping.getPropertyName(leafName));
1403 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1404 typeProvider.resolveRegExpressions(patternConstraints));
1409 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1411 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1412 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1413 * @param module Module in which type was defined
1414 * @return boolean value
1416 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1418 * <li>true - in other cases</li>
1421 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1422 final ModuleContext context, final boolean inGrouping) {
1423 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1427 final Module parentModule = findParentModule(schemaContext, leaf);
1428 Type returnType = null;
1430 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1431 if (isInnerType(leaf, typeDef)) {
1432 if (typeDef instanceof EnumTypeDefinition) {
1433 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1434 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1435 typeProvider.putReferencedType(leaf.getPath(), returnType);
1436 } else if (typeDef instanceof UnionTypeDefinition) {
1437 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1438 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1439 // Store the inner type within the union so that we can find the reference for it
1440 context.addInnerTypedefType(typeDef.getPath(), returnType);
1441 } else if (typeDef instanceof BitsTypeDefinition) {
1442 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1444 if (genTOBuilder != null) {
1445 returnType = genTOBuilder.build();
1448 // It is constrained version of already declared type (inner declared type exists, only for special
1449 // cases (Enum, Union, Bits), which were already checked.
1450 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1452 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1453 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1454 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1455 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1456 final SchemaNode leafrefTarget =
1457 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1458 if (leafrefTarget instanceof TypedDataSchemaNode) {
1459 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1462 if (returnType == null) {
1463 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1464 restrictions, inGrouping);
1467 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1470 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1471 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1472 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1475 if (returnType == null) {
1479 if (typeDef instanceof EnumTypeDefinition) {
1480 typeProvider.putReferencedType(leaf.getPath(), returnType);
1483 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1484 processContextRefExtension(leaf, getter, parentModule);
1488 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1489 // Returns DerivedType in case of new parser.
1490 final TypeDefinition<?> baseType = typeDef.getBaseType();
1491 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1494 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1495 final Module module) {
1496 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1497 final QName nodeType = node.getNodeType();
1498 if ("context-reference".equals(nodeType.getLocalName())) {
1499 final String nodeParam = node.getNodeParameter();
1500 IdentitySchemaNode identity = null;
1501 String basePackageName = null;
1502 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1503 final Iterator<String> iterator = splittedElement.iterator();
1504 final int length = Iterables.size(splittedElement);
1506 identity = findIdentityByName(module.getIdentities(), iterator.next());
1507 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1508 } else if (length == 2) {
1509 final String prefix = iterator.next();
1510 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1511 if (dependentModule == null) {
1512 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1515 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1516 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1518 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1521 if (identity == null) {
1522 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1526 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1527 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1528 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1529 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1534 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1535 final String name) {
1536 for (final IdentitySchemaNode id : identities) {
1537 if (id.getQName().getLocalName().equals(name)) {
1544 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1545 for (final ModuleImport imp : imports) {
1546 if (imp.getPrefix().equals(prefix)) {
1547 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1553 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1554 final boolean isReadOnly) {
1555 if (leaf != null && toBuilder != null) {
1557 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1558 if (typeDef instanceof UnionTypeDefinition) {
1559 // GeneratedType for this type definition should have be already created
1560 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1561 returnType = mc.getTypedefs().get(typeDef.getPath());
1562 if (returnType == null) {
1563 // This may still be an inner type, try to find it
1564 returnType = mc.getInnerType(typeDef.getPath());
1566 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1567 // Annonymous enumeration (already generated, since it is inherited via uses).
1568 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1569 QName qname = originalLeaf.getQName();
1570 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1572 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1574 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1580 * Converts <code>leaf</code> schema node to property of generated TO builder.
1582 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1583 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1584 * @param returnType property type
1585 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1586 * @return boolean value
1588 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1589 * name equals null or if leaf is added by <i>uses</i>.</li>
1590 * <li>true - other cases</li>
1593 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1594 final Type returnType, final boolean isReadOnly) {
1595 if (returnType == null) {
1598 final String leafName = leaf.getQName().getLocalName();
1599 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1600 propBuilder.setReadOnly(isReadOnly);
1601 propBuilder.setReturnType(returnType);
1602 addComment(propBuilder, leaf);
1604 toBuilder.addEqualsIdentity(propBuilder);
1605 toBuilder.addHashIdentity(propBuilder);
1606 toBuilder.addToStringProperty(propBuilder);
1611 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1613 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1614 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1615 * @param module module
1616 * @return boolean value
1618 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1619 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1620 * <li>false - other cases</li>
1623 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1624 final ModuleContext context, final boolean inGrouping) {
1625 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1629 final QName nodeName = node.getQName();
1631 final TypeDefinition<?> typeDef = node.getType();
1632 final Module parentModule = findParentModule(schemaContext, node);
1634 Type returnType = null;
1635 if (typeDef.getBaseType() == null) {
1636 if (typeDef instanceof EnumTypeDefinition) {
1637 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1638 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1639 typeProvider.putReferencedType(node.getPath(), returnType);
1640 } else if (typeDef instanceof UnionTypeDefinition) {
1641 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1642 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1643 } else if (typeDef instanceof BitsTypeDefinition) {
1644 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1645 node, parentModule);
1646 returnType = genTOBuilder.build();
1648 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1649 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1650 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1653 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1654 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1655 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1658 constructGetter(typeBuilder, listTypeFor(returnType), node);
1662 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1663 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1664 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1665 returnTypeBuilder.setIsUnion(true);
1666 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1667 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1668 returnTypeBuilder.setModuleName(parentModule.getName());
1669 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1671 genTOBuilder.setTypedef(true);
1672 genTOBuilder.setIsUnion(true);
1673 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1675 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1679 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1680 final GeneratedTransferObject returnType, final Module parentModule) {
1681 // Append enclosing path hierarchy without dots
1682 final StringBuilder sb = new StringBuilder();
1683 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1684 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1685 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1686 unionBuilder.setIsUnionBuilder(true);
1688 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1689 method.setReturnType(returnType);
1690 method.addParameter(STRING, "defaultValue");
1691 method.setAccessModifier(AccessModifier.PUBLIC);
1692 method.setStatic(true);
1694 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1695 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1698 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1699 final SchemaNode schemaNode) {
1700 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1703 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1704 final SchemaNode schemaNode, final Type baseInterface) {
1705 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1706 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1710 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1711 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1712 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1713 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1714 * If <code>schemaNode</code> is instance of
1715 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1716 * which are specified in <i>uses</i>.
1718 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1719 * @param schemaNode schema node for which is created generated type builder
1720 * @param parent parent type (can be null)
1721 * @return generated type builder <code>schemaNode</code>
1723 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1724 final Type baseInterface, final ModuleContext context) {
1725 JavaTypeName name = renames.get(schemaNode);
1727 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1730 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1731 it.addImplementsType(baseInterface);
1732 if (!(schemaNode instanceof GroupingDefinition)) {
1733 it.addImplementsType(augmentable(it));
1735 if (schemaNode instanceof DataNodeContainer) {
1736 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1737 groupingsToGenTypes(context, containerSchema.getGroupings());
1738 addImplementedInterfaceFromUses(containerSchema, it);
1745 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1746 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1747 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1749 * @param packageName string with the package name to which returning generated type builder belongs
1750 * @param schemaNode schema node which provide data about the schema node name
1751 * @param prefix return type name prefix
1752 * @return generated type builder for <code>schemaNode</code>
1753 * @throws IllegalArgumentException
1755 * <li>if <code>schemaNode</code> is null</li>
1756 * <li>if <code>packageName</code> is null</li>
1757 * <li>if QName of schema node is null</li>
1758 * <li>if schemaNode name is null</li>
1761 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1762 final SchemaNode schemaNode) {
1763 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1764 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1765 final String schemaNodeName = schemaNode.getQName().getLocalName();
1766 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1768 // FIXME: Validation of name conflict
1769 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1770 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1772 final Module module = context.module();
1773 addCodegenInformation(newType, module, schemaNode);
1774 newType.setSchemaPath(schemaNode.getPath());
1775 newType.setModuleName(module.getName());
1777 final String packageName = identifier.packageName();
1778 final String simpleName = identifier.simpleName();
1779 if (!genTypeBuilders.containsKey(packageName)) {
1780 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1781 builders.put(simpleName, newType);
1782 genTypeBuilders.put(packageName, builders);
1784 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1785 if (!builders.containsKey(simpleName)) {
1786 builders.put(simpleName, newType);
1793 * Creates the name of the getter method name from <code>localName</code>.
1795 * @param localName string with the name of the getter method
1796 * @param returnType return type
1797 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1799 public static String getterMethodName(final String localName, final Type returnType) {
1800 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1804 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1805 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1806 * and <code>returnType</code> information are added to the builder.
1808 * @param interfaceBuilder generated type builder for which the getter method should be created
1809 * @param returnType type which represents the return type of the getter method
1810 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1811 * @param comment string with comment for the getter method
1812 * @param status status from yang file, for deprecated annotation
1813 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1815 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1816 final SchemaNode node) {
1817 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1818 getterMethodName(node.getQName().getLocalName(), returnType));
1819 getMethod.setReturnType(returnType);
1821 annotateDeprecatedIfNecessary(node, getMethod);
1822 addComment(getMethod, node);
1827 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1828 final ListSchemaNode node) {
1829 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1830 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1831 getMethod.setReturnType(returnType).setDefault(true);
1832 annotateDeprecatedIfNecessary(node, getMethod);
1836 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1839 * @param basePackageName string contains the module package name
1840 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1841 * or as a property to <code>genTOBuilder</code> if is part of the list key
1842 * @param typeBuilder generated type builder for the list schema node
1843 * @param genTOBuilder generated TO builder for the list keys
1844 * @param listKeys list of string which contains names of the list keys
1845 * @param module current module
1846 * @throws IllegalArgumentException
1848 * <li>if <code>schemaNode</code> equals null</li>
1849 * <li>if <code>typeBuilder</code> equals null</li>
1852 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1853 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1854 final List<String> listKeys, final boolean inGrouping) {
1855 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1856 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1858 if (schemaNode instanceof LeafSchemaNode) {
1859 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1860 final String leafName = leaf.getQName().getLocalName();
1861 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1862 if (listKeys.contains(leafName)) {
1864 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1866 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1869 } else if (!schemaNode.isAddedByUses()) {
1870 if (schemaNode instanceof LeafListSchemaNode) {
1871 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1872 } else if (schemaNode instanceof ContainerSchemaNode) {
1873 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1874 (ContainerSchemaNode) schemaNode, inGrouping);
1875 } else if (schemaNode instanceof ChoiceSchemaNode) {
1876 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1877 } else if (schemaNode instanceof ListSchemaNode) {
1878 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1879 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1880 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1885 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1886 final GeneratedTOBuilder genTOBuilder) {
1887 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1889 if (genTOBuilder != null) {
1890 final GeneratedTransferObject genTO = genTOBuilder.build();
1891 // Add Identifiable.getKey() for items
1892 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1893 .addAnnotation(OVERRIDE_ANNOTATION);
1894 context.addGeneratedTOBuilder(genTOBuilder);
1899 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1901 * @param list of string with names of the list keys
1902 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1903 * an empty list is returned.
1905 private static List<String> listKeys(final ListSchemaNode list) {
1906 final List<QName> keyDefinition = list.getKeyDefinition();
1907 switch (keyDefinition.size()) {
1909 return Collections.emptyList();
1911 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1913 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1914 for (final QName keyDef : keyDefinition) {
1915 listKeys.add(keyDef.getLocalName());
1922 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1923 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1924 * enclosing transfer objects.
1926 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1927 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1928 * @param leaf string with name for generated TO builder
1929 * @param parentModule parent module
1930 * @return generated TO builder for <code>typeDef</code>
1932 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1933 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1934 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1935 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1937 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1938 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1939 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1940 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1941 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1943 for (GeneratedTOBuilder builder : types) {
1944 if (builder.isUnion()) {
1945 final GeneratedTransferObject type = builder.build();
1946 createUnionBuilder(builder, typeBuilder, type, parentModule);
1950 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1954 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1955 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1956 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1959 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1960 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1961 * @param leaf string with name for generated TO builder
1962 * @param parentModule parent module
1963 * @return generated TO builder for <code>typeDef</code>
1965 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1966 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1967 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1968 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1969 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1970 return genTOBuilder;
1974 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1975 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1976 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1977 * to <code>builder</code>
1979 * @param dataNodeContainer element which contains the list of used YANG groupings
1980 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1981 * @return generated type builder with all implemented types
1983 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1984 final GeneratedTypeBuilder builder) {
1985 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1986 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1987 if (genType == null) {
1988 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1989 + " is not resolved for " + builder.getFullyQualifiedName());
1992 builder.addImplementsType(genType.build());
1997 private JavaTypeName findAliasByPath(final SchemaPath path) {
1998 for (final ModuleContext ctx : genCtx.values()) {
1999 final JavaTypeName result = ctx.getAlias(path);
2000 if (result != null) {
2007 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2008 for (final ModuleContext ctx : genCtx.values()) {
2009 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2010 if (result != null) {
2017 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2018 for (final ModuleContext ctx : genCtx.values()) {
2019 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2020 if (result != null) {
2027 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2028 for (final ModuleContext ctx : genCtx.values()) {
2029 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2030 if (result != null) {
2037 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2038 for (final ModuleContext ctx : genCtx.values()) {
2039 final GeneratedTypeBuilder result = ctx.getCase(path);
2040 if (result != null) {
2047 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2048 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2049 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2052 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2053 switch (node.getStatus()) {
2055 // FIXME: we really want to use a pre-made annotation
2056 builder.addAnnotation(DEPRECATED_ANNOTATION);
2059 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2065 throw new IllegalStateException("Unhandled status in " + node);
2069 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2070 defaultImplementedInterace(typeBuilder);
2072 typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2073 .setAccessModifier(AccessModifier.PUBLIC)
2075 .setReturnType(primitiveIntType());
2076 typeBuilder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
2077 .setAccessModifier(AccessModifier.PUBLIC)
2079 .setReturnType(primitiveBooleanType());
2080 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2081 .setAccessModifier(AccessModifier.PUBLIC)
2083 .setReturnType(STRING);
2086 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2087 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2090 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2091 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2094 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2095 final Type classType) {
2096 final MethodSignatureBuilder ret = typeBuilder
2097 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2098 .setAccessModifier(AccessModifier.PUBLIC)
2099 .setReturnType(classType(classType));
2100 ret.addAnnotation(OVERRIDE_ANNOTATION);