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.ContainerSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
107 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
110 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
111 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
112 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
113 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.Module;
118 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
119 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
120 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
121 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
122 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
123 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
124 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
127 import org.opendaylight.yangtools.yang.model.api.UsesNode;
128 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
129 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
130 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
131 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
132 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
133 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
134 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
135 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
136 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
137 import org.slf4j.Logger;
138 import org.slf4j.LoggerFactory;
140 abstract class AbstractTypeGenerator {
141 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
142 private static final Splitter COLON_SPLITTER = Splitter.on(':');
143 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
144 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
145 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
148 * Comparator based on augment target path.
150 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
151 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
152 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
154 while (thisIt.hasNext()) {
155 if (!otherIt.hasNext()) {
159 final int comp = thisIt.next().compareTo(otherIt.next());
165 return otherIt.hasNext() ? -1 : 0;
169 * Constant with the concrete name of identifier.
171 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
174 * Constant with the concrete name of namespace.
176 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
178 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
181 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
182 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
183 * for schema node specified in key part.
185 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
188 * Provide methods for converting YANG types to JAVA types.
190 private final AbstractTypeProvider typeProvider;
193 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
195 private final @NonNull EffectiveModelContext schemaContext;
198 * Holds renamed elements.
200 private final Map<SchemaNode, JavaTypeName> renames;
202 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
203 final Map<SchemaNode, JavaTypeName> renames) {
204 this.schemaContext = requireNonNull(context);
205 this.typeProvider = requireNonNull(typeProvider);
206 this.renames = requireNonNull(renames);
208 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
209 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
210 for (final Module contextModule : contextModules) {
211 contexts.add(moduleToGenTypes(contextModule));
214 contexts.forEach(this::allAugmentsToGenTypes);
217 final @NonNull EffectiveModelContext schemaContext() {
218 return schemaContext;
221 final Collection<ModuleContext> moduleContexts() {
222 return genCtx.values();
225 final ModuleContext moduleContext(final QNameModule module) {
226 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
229 final AbstractTypeProvider typeProvider() {
233 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
235 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
237 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
238 Collection<? extends SchemaNode> nodes);
240 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
242 private ModuleContext moduleToGenTypes(final Module module) {
243 final ModuleContext context = new ModuleContext(module);
244 genCtx.put(module.getQNameModule(), context);
245 allTypeDefinitionsToGenTypes(context);
246 groupingsToGenTypes(context, module.getGroupings());
247 allIdentitiesToGenTypes(context);
249 if (!module.getChildNodes().isEmpty()) {
250 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
251 context.addModuleNode(moduleType);
252 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
255 // Resolve RPCs and notifications only after we have created instantiated tree
256 rpcMethodsToGenType(context);
257 notificationsToGenType(context);
262 * Converts all extended type definitions of module to the list of
263 * <code>Type</code> objects.
266 * module from which is obtained set of type definitions
267 * @throws IllegalArgumentException
269 * <li>if module is null</li>
270 * <li>if name of module is null</li>
272 * @throws IllegalStateException
273 * if set of type definitions from module is null
275 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
276 final Module module = context.module();
277 checkArgument(module.getName() != null, "Module name cannot be NULL.");
279 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
280 if (typedef != null) {
281 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
283 context.addTypedefType(typedef, type);
284 context.addTypeToSchema(type,typedef);
290 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
291 final DataSchemaNode node, final boolean inGrouping) {
292 if (node.isAugmenting() || node.isAddedByUses()) {
295 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
296 addConcreteInterfaceMethods(genType);
297 annotateDeprecatedIfNecessary(node, genType);
299 final Module module = context.module();
300 genType.setModuleName(module.getName());
301 addCodegenInformation(genType, module, node);
302 genType.setSchemaPath(node.getPath());
303 if (node instanceof DataNodeContainer) {
304 context.addChildNodeType(node, genType);
305 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
306 processUsesAugments((DataNodeContainer) node, context, inGrouping);
311 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
312 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
313 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
314 if (genType != null) {
315 constructGetter(parent, genType, node);
316 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
317 actionsToGenType(context, genType, node, null, inGrouping);
318 notificationsToGenType(context, genType, node, null, inGrouping);
322 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
323 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
324 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
325 if (genType != null) {
326 final List<String> listKeys = listKeys(node);
327 final GeneratedTOBuilder keyTypeBuilder;
328 if (!listKeys.isEmpty()) {
329 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
330 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
331 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
332 .addImplementsType(identifier(genType));
333 genType.addImplementsType(identifiable(keyTypeBuilder));
335 keyTypeBuilder = null;
338 // Decide whether to generate a List or a Map
339 final ParameterizedType listType;
340 if (keyTypeBuilder != null && !node.isUserOrdered()) {
341 listType = mapTypeFor(keyTypeBuilder, genType);
343 listType = listTypeFor(genType);
346 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
347 constructNonnull(parent, listType, node);
349 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
350 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
352 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
353 if (!schemaNode.isAugmenting()) {
354 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
359 if (keyTypeBuilder != null) {
360 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
361 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
362 keyTypeBuilder.setSUID(prop);
365 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
369 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
370 final boolean inGrouping) {
371 for (final UsesNode usesNode : node.getUses()) {
372 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
373 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
374 processUsesAugments(augment, context, inGrouping);
380 * Converts all <b>augmentation</b> of the module to the list
381 * <code>Type</code> objects.
384 * module from which is obtained list of all augmentation objects
385 * to iterate over them
386 * @throws IllegalArgumentException
388 * <li>if the module is null</li>
389 * <li>if the name of module is null</li>
391 * @throws IllegalStateException
392 * if set of augmentations from module is null
394 private void allAugmentsToGenTypes(final ModuleContext context) {
395 final Module module = context.module();
396 checkArgument(module != null, "Module reference cannot be NULL.");
397 checkArgument(module.getName() != null, "Module name cannot be NULL.");
398 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
400 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
401 augmentationToGenTypes(context, augment);
406 * Returns list of <code>AugmentationSchema</code> objects. The objects are
407 * sorted according to the length of their target path from the shortest to
411 * module from which is obtained list of all augmentation objects
412 * @return list of sorted <code>AugmentationSchema</code> objects obtained
413 * from <code>module</code>
414 * @throws IllegalArgumentException
416 * @throws IllegalStateException
417 * if set of module augmentations is null
419 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
420 checkArgument(module != null, "Module reference cannot be NULL.");
421 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
423 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
424 sortedAugmentations.sort(AUGMENT_COMP);
426 return sortedAugmentations;
430 * Create GeneratedTypeBuilder object from module argument.
433 * Module object from which builder will be created
434 * @return <code>GeneratedTypeBuilder</code> which is internal
435 * representation of the module
436 * @throws IllegalArgumentException
439 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
440 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
441 final Module module = context.module();
442 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
443 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
444 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
445 // top level DataRoot object
446 if (module.getUses().size() > 1) {
447 narrowImplementedInterface(moduleDataTypeBuilder);
450 addCodegenInformation(moduleDataTypeBuilder, module);
451 return moduleDataTypeBuilder;
454 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
455 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
456 for (final ActionDefinition action : parentSchema.getActions()) {
457 if (action.isAugmenting()) {
461 final GeneratedType input;
462 final GeneratedType output;
463 if (action.isAddedByUses()) {
464 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
465 // Original definition may live in a different module, make sure we account for that
466 final ModuleContext origContext = moduleContext(
467 orig.getPath().getPathFromRoot().iterator().next().getModule());
468 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
469 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
471 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
472 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
475 if (!(parentSchema instanceof GroupingDefinition)) {
476 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
477 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
478 // and do not capture an actual instantiation.
479 final QName qname = action.getQName();
480 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
481 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
482 BindingMapping.getClassName(qname)));
483 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
485 annotateDeprecatedIfNecessary(action, builder);
486 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
487 : action(parent, input, output));
489 addCodegenInformation(builder, context.module(), action);
490 context.addChildNodeType(action, builder);
495 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
496 final QName qname = action.getQName();
497 for (UsesNode uses : parent.getUses()) {
498 final GroupingDefinition grp = uses.getSourceGrouping();
499 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
501 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
502 if (found.isPresent()) {
503 final ActionDefinition result = found.get();
504 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
508 return Optional.empty();
511 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
512 final ContainerSchemaNode schema, final boolean inGrouping) {
513 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
514 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
515 return genType.build();
519 * Converts all <b>RPCs</b> input and output substatements of the module
520 * to the list of <code>Type</code> objects. In addition are to containers
521 * and lists which belong to input or output also part of returning list.
524 * module from which is obtained set of all rpc objects to
526 * @throws IllegalArgumentException
528 * <li>if the module is null</li>
529 * <li>if the name of module is null</li>
531 * @throws IllegalStateException
532 * if set of rpcs from module is null
534 private void rpcMethodsToGenType(final ModuleContext context) {
535 final Module module = context.module();
536 checkArgument(module.getName() != null, "Module name cannot be NULL.");
537 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
538 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
539 if (rpcDefinitions.isEmpty()) {
543 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
544 interfaceBuilder.addImplementsType(RPC_SERVICE);
546 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
548 for (final RpcDefinition rpc : rpcDefinitions) {
550 final String rpcName = BindingMapping.getClassName(rpc.getQName());
551 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
552 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
554 // Do not refer to annotation class, as it may not be available at runtime
555 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
556 addComment(method, rpc);
558 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
559 method.setReturnType(listenableFutureTypeFor(
560 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
564 context.addTopLevelNodeType(interfaceBuilder);
567 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
568 final ContainerSchemaNode schema, final Type type) {
569 processUsesAugments(schema, context, false);
570 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
571 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
573 addImplementedInterfaceFromUses(schema, outType);
574 outType.addImplementsType(type);
575 outType.addImplementsType(augmentable(outType));
576 addConcreteInterfaceMethods(outType);
577 annotateDeprecatedIfNecessary(rpc, outType);
578 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
579 context.addChildNodeType(schema, outType);
580 return outType.build();
584 * Converts all <b>notifications</b> of the module to the list of
585 * <code>Type</code> objects. In addition are to this list added containers
586 * and lists which are part of this notification.
589 * module from which is obtained set of all notification objects
590 * to iterate over them
591 * @throws IllegalArgumentException
593 * <li>if the module equals null</li>
594 * <li>if the name of module equals null</li>
596 * @throws IllegalStateException
597 * if set of notifications from module is null
599 private void notificationsToGenType(final ModuleContext context) {
600 final Module module = context.module();
601 checkArgument(module.getName() != null, "Module name cannot be NULL.");
602 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
603 if (notifications.isEmpty()) {
607 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
608 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
610 for (final NotificationDefinition notification : notifications) {
611 if (notification != null) {
612 processUsesAugments(notification, context, false);
614 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
615 context.modulePackageName(), notification, DATA_OBJECT, context);
616 addConcreteInterfaceMethods(notificationInterface);
617 annotateDeprecatedIfNecessary(notification, notificationInterface);
618 notificationInterface.addImplementsType(NOTIFICATION);
619 context.addChildNodeType(notification, notificationInterface);
621 // Notification object
622 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
623 notification.getChildNodes(), false);
625 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
626 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
627 .setReturnType(primitiveVoidType()), notification);
631 addCodegenInformation(listenerInterface, module, "notifications", notifications);
632 context.addTopLevelNodeType(listenerInterface);
635 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
636 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
637 final boolean inGrouping) {
638 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
639 if (notifications.isEmpty()) {
643 for (NotificationDefinition notif : notifications) {
644 if (notif.isAugmenting()) {
647 if (parentSchema instanceof GroupingDefinition) {
648 // Notifications cannot be really established, as they lack instantiation context, which would be
649 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
653 processUsesAugments(notif, context, false);
655 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
656 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
657 addConcreteInterfaceMethods(notifInterface);
658 annotateDeprecatedIfNecessary(notif, notifInterface);
660 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
661 : instanceNotification(notifInterface, parent));
662 context.addChildNodeType(notif, notifInterface);
664 // Notification object
665 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
670 * Converts all <b>identities</b> of the module to the list of
671 * <code>Type</code> objects.
674 * module from which is obtained set of all identity objects to
676 * @param schemaContext
677 * schema context only used as input parameter for method
678 * {@link BindingGeneratorImpl#identityToGenType}
681 private void allIdentitiesToGenTypes(final ModuleContext context) {
682 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
684 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
685 for (final IdentitySchemaNode identity : schemaIdentities) {
686 identityToGenType(context, identity);
692 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
693 * created transport object builder. If identity contains base identity then
694 * reference to base identity is added to superior identity as its extend.
695 * If identity doesn't contain base identity then only reference to abstract
696 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
697 * BaseIdentity} is added
701 * @param basePackageName
702 * string contains the module package name
704 * IdentitySchemaNode which contains data about identity
706 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
707 if (identity == null) {
711 JavaTypeName name = renames.get(identity);
713 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
714 BindingMapping.getClassName(identity.getQName()));
717 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
718 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
719 if (!baseIdentities.isEmpty()) {
720 for (IdentitySchemaNode baseIdentity : baseIdentities) {
721 JavaTypeName base = renames.get(baseIdentity);
723 final QName qname = baseIdentity.getQName();
724 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
725 BindingMapping.getClassName(qname));
728 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
729 newType.addImplementsType(gto);
732 newType.addImplementsType(BASE_IDENTITY);
735 final Module module = context.module();
736 addCodegenInformation(newType, module, identity);
737 newType.setModuleName(module.getName());
738 newType.setSchemaPath(identity.getPath());
740 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
742 context.addIdentityType(identity, newType);
745 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
746 final JavaTypeName yangModuleInfo, final String localName) {
747 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
748 new SimpleImmutableEntry<>(yangModuleInfo, localName));
752 * Converts all <b>groupings</b> of the module to the list of
753 * <code>Type</code> objects. Firstly are groupings sorted according mutual
754 * dependencies. At least dependent (independent) groupings are in the list
755 * saved at first positions. For every grouping the record is added to map
756 * {@link ModuleContext#groupings allGroupings}
761 * collection of groupings from which types will be generated
764 private void groupingsToGenTypes(final ModuleContext context,
765 final Collection<? extends GroupingDefinition> groupings) {
766 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
767 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
768 // node of grouping is resolved to the method.
769 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
770 narrowImplementedInterface(genType);
771 annotateDeprecatedIfNecessary(grouping, genType);
772 context.addGroupingType(grouping, genType);
773 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
774 groupingsToGenTypes(context, grouping.getGroupings());
775 processUsesAugments(grouping, context, true);
776 actionsToGenType(context, genType, grouping, null, true);
777 notificationsToGenType(context, genType, grouping, null, true);
782 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
783 * <code>enumTypeDef</code> item is added to builder with its name and value.
785 * @param enumTypeDef EnumTypeDefinition contains enum data
786 * @param enumName string contains name which will be assigned to enumeration builder
787 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
788 * @param module Module in which type should be generated
789 * @return enumeration builder which contains data from <code>enumTypeDef</code>
791 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
792 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
793 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
794 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
795 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
796 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
797 context.addTypeToSchema(ret, enumTypeDef);
798 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
803 * Generates type builder for <code>module</code>.
805 * @param module Module which is source of package name for generated type builder
806 * @param postfix string which is added to the module class name representation as suffix
807 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
808 * @throws IllegalArgumentException if <code>module</code> is null
810 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
811 final Module module = context.module();
812 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
813 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
814 JavaTypeName.create(context.modulePackageName(), moduleName));
816 moduleBuilder.setModuleName(moduleName);
817 addCodegenInformation(moduleBuilder, module);
818 return moduleBuilder;
822 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
823 * In addition there are also generated types for all containers, list and choices which are child of
824 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
826 * @param augmentPackageName string with the name of the package to which the augmentation belongs
827 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
828 * @param module current module
829 * @throws IllegalArgumentException
831 * <li>if <code>augmentPackageName</code> equals null</li>
832 * <li>if <code>augSchema</code> equals null</li>
834 * @throws IllegalStateException
835 * if augment target path is null
837 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
838 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
839 checkState(augSchema.getTargetPath() != null,
840 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
842 processUsesAugments(augSchema, context, false);
843 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
844 SchemaNode targetSchemaNode = null;
846 // FIXME: can we use findDataSchemaNode() instead?
847 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
848 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
849 if (targetSchemaNode instanceof DerivableSchemaNode) {
850 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
852 if (targetSchemaNode == null) {
853 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
854 + " in module " + context.module().getName());
857 if (targetSchemaNode == null) {
858 throw new IllegalArgumentException("augment target not found: " + targetPath);
861 if (targetSchemaNode instanceof ChoiceSchemaNode) {
862 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
863 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
864 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
865 augSchema.getChildNodes(), null, false);
869 final JavaTypeName targetName;
870 if (targetSchemaNode instanceof CaseSchemaNode) {
871 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
872 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
873 targetName = builder.getIdentifier();
875 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
876 if (builder == null) {
877 targetName = findAliasByPath(targetSchemaNode.getPath());
878 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
880 targetName = builder.getIdentifier();
884 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
887 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
888 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
889 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
890 checkState(augSchema.getTargetPath() != null,
891 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
893 processUsesAugments(augSchema, context, inGrouping);
894 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
895 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
896 if (targetSchemaNode == null) {
897 throw new IllegalArgumentException("augment target not found: " + targetPath);
900 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
901 if (targetTypeBuilder == null) {
902 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
904 if (targetTypeBuilder == null) {
905 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
908 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
909 if (usesNodeParent instanceof SchemaNode) {
910 addRawAugmentGenTypeDefinition(context,
911 packageNameForAugmentedGeneratedType(context.modulePackageName(),
912 ((SchemaNode) usesNodeParent).getPath()),
913 targetTypeBuilder.build(), augSchema, inGrouping);
915 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
918 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
919 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
924 * Convenient method to find node added by uses statement.
926 * @param targetPath node path
927 * @param parentUsesNode parent of uses node
928 * @return node from its original location in grouping
930 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
931 final UsesNode parentUsesNode) {
932 SchemaNode result = parentUsesNode.getSourceGrouping();
933 for (final QName node : targetPath.getNodeIdentifiers()) {
934 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
935 if (result instanceof DataNodeContainer) {
936 final QName resultNode = node.bindTo(result.getQName().getModule());
938 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
940 if (result instanceof ActionNodeContainer) {
941 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
943 if (found == null && result instanceof NotificationNodeContainer) {
944 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
948 } else if (result instanceof ChoiceSchemaNode) {
949 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
950 } else if (result instanceof ActionDefinition) {
951 final ActionDefinition action = (ActionDefinition) result;
952 final QName resultNode = node.bindTo(result.getQName().getModule());
954 final ContainerSchemaNode input = action.getInput();
955 final ContainerSchemaNode output = action.getOutput();
956 if (resultNode.equals(input.getQName())) {
958 } else if (resultNode.equals(output.getQName())) {
963 } else if (result != null) {
964 throw new IllegalStateException("Cannot handle " + result);
967 if (result == null) {
971 if (result instanceof DerivableSchemaNode) {
972 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
973 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
974 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
975 result = originalNode.get();
979 if (result instanceof DataSchemaNode) {
980 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
981 if (resultDataSchemaNode.isAddedByUses()) {
982 // The original node is required, but we have only the copy of
983 // the original node.
984 // Maybe this indicates a bug in Yang parser.
985 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
988 return resultDataSchemaNode;
991 throw new IllegalStateException(
992 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
997 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
998 * of augmented node with serial number as suffix.
1000 * @param context current module
1001 * @param augmentPackageName string with contains the package name to which the augment belongs
1002 * @param basePackageName string with the package name to which the augmented node belongs
1003 * @param targetTypeRef target type
1004 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1005 * @return generated type builder for augment
1007 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1008 final String augmentPackageName, final Type targetTypeRef,
1009 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1010 Map<String, GeneratedTypeBuilder> augmentBuilders =
1011 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1012 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1015 if (augIdentifier != null) {
1016 augTypeName = BindingMapping.getClassName(augIdentifier);
1018 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1021 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1022 JavaTypeName.create(augmentPackageName, augTypeName));
1024 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1025 addConcreteInterfaceMethods(augTypeBuilder);
1027 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1028 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1030 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1031 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1032 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1034 augmentBuilders.put(augTypeName, augTypeBuilder);
1036 if (!augSchema.getChildNodes().isEmpty()) {
1037 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1040 context.addAugmentType(augTypeBuilder);
1041 return augTypeBuilder;
1044 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1045 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1046 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1050 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1051 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1052 final QName nodeType = unknownSchemaNode.getNodeType();
1053 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1054 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1055 return unknownSchemaNode.getNodeParameter();
1062 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1063 * consists from name of augmented node and serial number of its augmentation.
1065 * @param builders map of builders which were created in the package to which the augmentation belongs
1066 * @param genTypeName string with name of augmented node
1067 * @return string with unique name for augmentation builder
1069 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1071 if (builders != null) {
1072 while (builders.containsKey(genTypeName + index)) {
1076 return genTypeName + index;
1080 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1081 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1082 * already part of them).
1084 * @param module current module
1085 * @param parent generated type builder which represents any node. The subnodes of this node are added
1086 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1087 * container, choice.
1088 * @param childOf parent type
1089 * @param schemaNodes set of data schema nodes which are the children of the node for which
1090 * <code>typeBuilder</code> was created
1091 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1092 * child nodes) could be added to it.
1094 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1095 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1096 final boolean inGrouping) {
1097 if (schemaNodes != null && parent != null) {
1098 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1099 for (final DataSchemaNode schemaNode : schemaNodes) {
1100 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1101 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1109 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1112 * @param module current module
1113 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1114 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1115 * container, choice.
1116 * @param childOf parent type
1117 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1119 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1120 * The getter method could be added to it.
1122 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1123 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1124 final boolean inGrouping) {
1125 if (schemaNodes != null && typeBuilder != null) {
1126 final Type baseInterface = childOf(typeBuilder);
1127 for (final DataSchemaNode schemaNode : schemaNodes) {
1128 if (!schemaNode.isAugmenting()) {
1129 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1137 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1139 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1140 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1141 * @param childOf parent type
1142 * @param module current module
1144 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1145 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1146 if (node != null && typeBuilder != null) {
1147 if (node instanceof LeafSchemaNode) {
1148 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1149 } else if (node instanceof LeafListSchemaNode) {
1150 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1151 } else if (node instanceof ContainerSchemaNode) {
1152 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1153 } else if (node instanceof ListSchemaNode) {
1154 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1155 } else if (node instanceof ChoiceSchemaNode) {
1156 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1157 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1158 opaqueToGeneratedType(context, typeBuilder, node);
1160 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1161 typeBuilder.getFullyQualifiedName());
1167 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1168 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1169 * and names of all parents node.
1171 * @param context current module
1172 * @param basePackageName string with the module package name
1173 * @param parent parent type
1174 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1176 * @throws IllegalArgumentException
1178 * <li>if <code>basePackageName</code> is null</li>
1179 * <li>if <code>choiceNode</code> is null</li>
1182 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1183 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1184 if (!choiceNode.isAddedByUses()) {
1185 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1186 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1187 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1188 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1189 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1190 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1192 final GeneratedType choiceType = choiceTypeBuilder.build();
1193 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1195 constructGetter(parent, choiceType, choiceNode);
1199 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1200 final DataSchemaNode anyNode) {
1201 if (!anyNode.isAddedByUses()) {
1202 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1203 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1204 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1205 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1206 defaultImplementedInterace(anyxmlTypeBuilder);
1207 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1208 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1210 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1215 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1216 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1217 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1218 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1220 * @param context current module context
1221 * @param refChoiceType type which represents superior <i>case</i>
1222 * @param choiceNode choice case node which is mapped to generated type
1223 * @throws IllegalArgumentException
1225 * <li>if <code>refChoiceType</code> equals null</li>
1226 * <li>if <code>caseNodes</code> equals null</li>
1229 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1230 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1231 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1232 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1234 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1235 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1236 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1237 caseTypeBuilder.addImplementsType(refChoiceType);
1238 addConcreteInterfaceMethods(caseTypeBuilder);
1239 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1240 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1241 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1242 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1243 if (caseChildNodes != null) {
1244 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1246 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1247 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1249 if (parent instanceof AugmentationSchemaNode) {
1250 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1251 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1252 // FIXME: can we use findDataSchemaNode?
1253 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1254 targetPath.getNodeIdentifiers());
1255 if (targetSchemaNode instanceof DataSchemaNode
1256 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1261 if (targetSchemaNode == null) {
1262 throw new IllegalStateException(
1263 "Failed to find target node from grouping for augmentation " + augSchema
1264 + " in module " + context.module().getName());
1267 parent = targetSchemaNode;
1270 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1271 Type childOfType = findChildNodeByPath(parent.getPath());
1272 if (childOfType == null) {
1273 childOfType = findGroupingByPath(parent.getPath());
1275 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1277 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1282 processUsesAugments(caseNode, context, inGrouping);
1287 * Generates list of generated types for all the cases of a choice which are added to the choice through
1290 * @param module current module
1291 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1292 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1293 * of the augmenting choice will belong to pcg2.
1294 * @param targetType Type which represents target choice
1295 * @param targetNode node which represents target choice
1296 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1298 * @throws IllegalArgumentException
1300 * <li>if <code>basePackageName</code> is null</li>
1301 * <li>if <code>targetType</code> is null</li>
1302 * <li>if <code>augmentedNodes</code> is null</li>
1305 // FIXME: nullness rules need to untangled in this method
1306 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1307 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1308 final Type targetType, final ChoiceSchemaNode targetNode,
1309 final Iterable<? extends DataSchemaNode> augmentedNodes,
1310 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1311 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1312 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1314 for (final DataSchemaNode caseNode : augmentedNodes) {
1315 if (caseNode != null) {
1316 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1317 caseTypeBuilder.addImplementsType(targetType);
1318 addConcreteInterfaceMethods(caseTypeBuilder);
1320 CaseSchemaNode node = null;
1321 final String caseLocalName = caseNode.getQName().getLocalName();
1322 if (caseNode instanceof CaseSchemaNode) {
1323 node = (CaseSchemaNode) caseNode;
1324 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1325 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1326 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1327 if (dataSchemaNode instanceof ChoiceSchemaNode
1328 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1329 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1334 node = findNamedCase(targetNode, caseLocalName);
1336 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1337 if (childNodes != null) {
1338 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1341 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1342 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1347 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1348 final SchemaPath nodePath = targetNode.getPath();
1349 final SchemaPath parentSp = nodePath.getParent();
1350 if (parentSp.getParent() == null) {
1351 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1354 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1355 GeneratedTypeBuilder childOfType = null;
1356 if (parent instanceof CaseSchemaNode) {
1357 childOfType = findCaseByPath(parent.getPath());
1358 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1359 childOfType = findChildNodeByPath(parent.getPath());
1360 } else if (parent instanceof GroupingDefinition) {
1361 childOfType = findGroupingByPath(parent.getPath());
1364 if (childOfType == null) {
1365 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1371 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1372 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1373 return cases.isEmpty() ? null : cases.get(0);
1376 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1377 // New parser with encapsulated type
1378 if (leaf.getPath().equals(type.getPath())) {
1382 // Embedded type definition with new parser. Also takes care of the old parser with bits
1383 if (leaf.getPath().equals(type.getPath().getParent())) {
1390 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1391 final List<PatternConstraint> patternConstraints) {
1392 if (!patternConstraints.isEmpty()) {
1393 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1394 .append(BindingMapping.getPropertyName(leafName));
1395 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1396 typeProvider.resolveRegExpressions(patternConstraints));
1401 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1403 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1404 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1405 * @param module Module in which type was defined
1406 * @return boolean value
1408 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1410 * <li>true - in other cases</li>
1413 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1414 final ModuleContext context, final boolean inGrouping) {
1415 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1419 final Module parentModule = findParentModule(schemaContext, leaf);
1420 Type returnType = null;
1422 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1423 if (isInnerType(leaf, typeDef)) {
1424 if (typeDef instanceof EnumTypeDefinition) {
1425 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1426 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1427 typeProvider.putReferencedType(leaf.getPath(), returnType);
1428 } else if (typeDef instanceof UnionTypeDefinition) {
1429 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1430 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1431 // Store the inner type within the union so that we can find the reference for it
1432 context.addInnerTypedefType(typeDef.getPath(), returnType);
1433 } else if (typeDef instanceof BitsTypeDefinition) {
1434 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1436 if (genTOBuilder != null) {
1437 returnType = genTOBuilder.build();
1440 // It is constrained version of already declared type (inner declared type exists, only for special
1441 // cases (Enum, Union, Bits), which were already checked.
1442 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1444 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1445 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1446 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1447 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1448 final SchemaNode leafrefTarget =
1449 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1450 if (leafrefTarget instanceof TypedDataSchemaNode) {
1451 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1454 if (returnType == null) {
1455 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1456 restrictions, inGrouping);
1459 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1462 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1463 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1464 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1467 if (returnType == null) {
1471 if (typeDef instanceof EnumTypeDefinition) {
1472 typeProvider.putReferencedType(leaf.getPath(), returnType);
1475 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1476 processContextRefExtension(leaf, getter, parentModule);
1480 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1481 // Returns DerivedType in case of new parser.
1482 final TypeDefinition<?> baseType = typeDef.getBaseType();
1483 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1486 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1487 final Module module) {
1488 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1489 final QName nodeType = node.getNodeType();
1490 if ("context-reference".equals(nodeType.getLocalName())) {
1491 final String nodeParam = node.getNodeParameter();
1492 IdentitySchemaNode identity = null;
1493 String basePackageName = null;
1494 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1495 final Iterator<String> iterator = splittedElement.iterator();
1496 final int length = Iterables.size(splittedElement);
1498 identity = findIdentityByName(module.getIdentities(), iterator.next());
1499 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1500 } else if (length == 2) {
1501 final String prefix = iterator.next();
1502 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1503 if (dependentModule == null) {
1504 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1507 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1508 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1510 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1513 if (identity == null) {
1514 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1518 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1519 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1520 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1521 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1526 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1527 final String name) {
1528 for (final IdentitySchemaNode id : identities) {
1529 if (id.getQName().getLocalName().equals(name)) {
1536 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1537 for (final ModuleImport imp : imports) {
1538 if (imp.getPrefix().equals(prefix)) {
1539 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1545 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1546 final boolean isReadOnly) {
1547 if (leaf != null && toBuilder != null) {
1549 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1550 if (typeDef instanceof UnionTypeDefinition) {
1551 // GeneratedType for this type definition should have be already created
1552 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1553 returnType = mc.getTypedefs().get(typeDef.getPath());
1554 if (returnType == null) {
1555 // This may still be an inner type, try to find it
1556 returnType = mc.getInnerType(typeDef.getPath());
1558 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1559 // Annonymous enumeration (already generated, since it is inherited via uses).
1560 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1561 QName qname = originalLeaf.getQName();
1562 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1564 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1566 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1572 * Converts <code>leaf</code> schema node to property of generated TO builder.
1574 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1575 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1576 * @param returnType property type
1577 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1578 * @return boolean value
1580 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1581 * name equals null or if leaf is added by <i>uses</i>.</li>
1582 * <li>true - other cases</li>
1585 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1586 final Type returnType, final boolean isReadOnly) {
1587 if (returnType == null) {
1590 final String leafName = leaf.getQName().getLocalName();
1591 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1592 propBuilder.setReadOnly(isReadOnly);
1593 propBuilder.setReturnType(returnType);
1594 addComment(propBuilder, leaf);
1596 toBuilder.addEqualsIdentity(propBuilder);
1597 toBuilder.addHashIdentity(propBuilder);
1598 toBuilder.addToStringProperty(propBuilder);
1603 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1605 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1606 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1607 * @param module module
1608 * @return boolean value
1610 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1611 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1612 * <li>false - other cases</li>
1615 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1616 final ModuleContext context, final boolean inGrouping) {
1617 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1621 final QName nodeName = node.getQName();
1623 final TypeDefinition<?> typeDef = node.getType();
1624 final Module parentModule = findParentModule(schemaContext, node);
1626 Type returnType = null;
1627 if (typeDef.getBaseType() == null) {
1628 if (typeDef instanceof EnumTypeDefinition) {
1629 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1630 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1631 typeProvider.putReferencedType(node.getPath(), returnType);
1632 } else if (typeDef instanceof UnionTypeDefinition) {
1633 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1634 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1635 } else if (typeDef instanceof BitsTypeDefinition) {
1636 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1637 node, parentModule);
1638 returnType = genTOBuilder.build();
1640 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1641 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1642 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1645 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1646 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1647 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1650 constructGetter(typeBuilder, listTypeFor(returnType), node);
1654 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1655 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1656 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1657 returnTypeBuilder.setIsUnion(true);
1658 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1659 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1660 returnTypeBuilder.setModuleName(parentModule.getName());
1661 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1663 genTOBuilder.setTypedef(true);
1664 genTOBuilder.setIsUnion(true);
1665 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1667 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1671 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1672 final GeneratedTransferObject returnType, final Module parentModule) {
1673 // Append enclosing path hierarchy without dots
1674 final StringBuilder sb = new StringBuilder();
1675 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1676 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1677 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1678 unionBuilder.setIsUnionBuilder(true);
1680 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1681 method.setReturnType(returnType);
1682 method.addParameter(STRING, "defaultValue");
1683 method.setAccessModifier(AccessModifier.PUBLIC);
1684 method.setStatic(true);
1686 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1687 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1690 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1691 final SchemaNode schemaNode) {
1692 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1695 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1696 final SchemaNode schemaNode, final Type baseInterface) {
1697 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1698 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1702 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1703 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1704 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1705 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1706 * If <code>schemaNode</code> is instance of
1707 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1708 * which are specified in <i>uses</i>.
1710 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1711 * @param schemaNode schema node for which is created generated type builder
1712 * @param parent parent type (can be null)
1713 * @return generated type builder <code>schemaNode</code>
1715 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1716 final Type baseInterface, final ModuleContext context) {
1717 JavaTypeName name = renames.get(schemaNode);
1719 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1722 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1723 it.addImplementsType(baseInterface);
1724 if (!(schemaNode instanceof GroupingDefinition)) {
1725 it.addImplementsType(augmentable(it));
1727 if (schemaNode instanceof DataNodeContainer) {
1728 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1729 groupingsToGenTypes(context, containerSchema.getGroupings());
1730 addImplementedInterfaceFromUses(containerSchema, it);
1737 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1738 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1739 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1741 * @param packageName string with the package name to which returning generated type builder belongs
1742 * @param schemaNode schema node which provide data about the schema node name
1743 * @param prefix return type name prefix
1744 * @return generated type builder for <code>schemaNode</code>
1745 * @throws IllegalArgumentException
1747 * <li>if <code>schemaNode</code> is null</li>
1748 * <li>if <code>packageName</code> is null</li>
1749 * <li>if QName of schema node is null</li>
1750 * <li>if schemaNode name is null</li>
1753 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1754 final SchemaNode schemaNode) {
1755 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1756 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1757 final String schemaNodeName = schemaNode.getQName().getLocalName();
1758 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1760 // FIXME: Validation of name conflict
1761 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1762 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1764 final Module module = context.module();
1765 addCodegenInformation(newType, module, schemaNode);
1766 newType.setSchemaPath(schemaNode.getPath());
1767 newType.setModuleName(module.getName());
1769 final String packageName = identifier.packageName();
1770 final String simpleName = identifier.simpleName();
1771 if (!genTypeBuilders.containsKey(packageName)) {
1772 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1773 builders.put(simpleName, newType);
1774 genTypeBuilders.put(packageName, builders);
1776 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1777 if (!builders.containsKey(simpleName)) {
1778 builders.put(simpleName, newType);
1785 * Creates the name of the getter method name from <code>localName</code>.
1787 * @param localName string with the name of the getter method
1788 * @param returnType return type
1789 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1791 public static String getterMethodName(final String localName, final Type returnType) {
1792 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1796 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1797 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1798 * and <code>returnType</code> information are added to the builder.
1800 * @param interfaceBuilder generated type builder for which the getter method should be created
1801 * @param returnType type which represents the return type of the getter method
1802 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1803 * @param comment string with comment for the getter method
1804 * @param status status from yang file, for deprecated annotation
1805 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1807 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1808 final SchemaNode node) {
1809 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1810 getterMethodName(node.getQName().getLocalName(), returnType));
1811 getMethod.setReturnType(returnType);
1813 annotateDeprecatedIfNecessary(node, getMethod);
1814 addComment(getMethod, node);
1819 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1820 final ListSchemaNode node) {
1821 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1822 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1823 getMethod.setReturnType(returnType).setDefault(true);
1824 annotateDeprecatedIfNecessary(node, getMethod);
1828 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1831 * @param basePackageName string contains the module package name
1832 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1833 * or as a property to <code>genTOBuilder</code> if is part of the list key
1834 * @param typeBuilder generated type builder for the list schema node
1835 * @param genTOBuilder generated TO builder for the list keys
1836 * @param listKeys list of string which contains names of the list keys
1837 * @param module current module
1838 * @throws IllegalArgumentException
1840 * <li>if <code>schemaNode</code> equals null</li>
1841 * <li>if <code>typeBuilder</code> equals null</li>
1844 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1845 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1846 final List<String> listKeys, final boolean inGrouping) {
1847 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1848 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1850 if (schemaNode instanceof LeafSchemaNode) {
1851 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1852 final String leafName = leaf.getQName().getLocalName();
1853 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1854 if (listKeys.contains(leafName)) {
1856 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1858 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1861 } else if (!schemaNode.isAddedByUses()) {
1862 if (schemaNode instanceof LeafListSchemaNode) {
1863 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1864 } else if (schemaNode instanceof ContainerSchemaNode) {
1865 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1866 (ContainerSchemaNode) schemaNode, inGrouping);
1867 } else if (schemaNode instanceof ChoiceSchemaNode) {
1868 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1869 } else if (schemaNode instanceof ListSchemaNode) {
1870 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1871 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1872 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1877 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1878 final GeneratedTOBuilder genTOBuilder) {
1879 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1881 if (genTOBuilder != null) {
1882 final GeneratedTransferObject genTO = genTOBuilder.build();
1883 // Add Identifiable.getKey() for items
1884 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1885 .addAnnotation(OVERRIDE_ANNOTATION);
1886 context.addGeneratedTOBuilder(genTOBuilder);
1891 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1893 * @param list of string with names of the list keys
1894 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1895 * an empty list is returned.
1897 private static List<String> listKeys(final ListSchemaNode list) {
1898 final List<QName> keyDefinition = list.getKeyDefinition();
1899 switch (keyDefinition.size()) {
1901 return Collections.emptyList();
1903 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1905 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1906 for (final QName keyDef : keyDefinition) {
1907 listKeys.add(keyDef.getLocalName());
1914 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1915 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1916 * enclosing transfer objects.
1918 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1919 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1920 * @param leaf string with name for generated TO builder
1921 * @param parentModule parent module
1922 * @return generated TO builder for <code>typeDef</code>
1924 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1925 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1926 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1927 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1929 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1930 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1931 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1932 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1933 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1935 for (GeneratedTOBuilder builder : types) {
1936 if (builder.isUnion()) {
1937 final GeneratedTransferObject type = builder.build();
1938 createUnionBuilder(builder, typeBuilder, type, parentModule);
1942 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1946 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1947 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1948 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1951 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1952 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1953 * @param leaf string with name for generated TO builder
1954 * @param parentModule parent module
1955 * @return generated TO builder for <code>typeDef</code>
1957 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1958 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1959 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1960 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1961 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1962 return genTOBuilder;
1966 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1967 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1968 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1969 * to <code>builder</code>
1971 * @param dataNodeContainer element which contains the list of used YANG groupings
1972 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1973 * @return generated type builder with all implemented types
1975 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1976 final GeneratedTypeBuilder builder) {
1977 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1978 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1979 if (genType == null) {
1980 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1981 + " is not resolved for " + builder.getFullyQualifiedName());
1984 builder.addImplementsType(genType.build());
1989 private JavaTypeName findAliasByPath(final SchemaPath path) {
1990 for (final ModuleContext ctx : genCtx.values()) {
1991 final JavaTypeName result = ctx.getAlias(path);
1992 if (result != null) {
1999 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2000 for (final ModuleContext ctx : genCtx.values()) {
2001 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2002 if (result != null) {
2009 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2010 for (final ModuleContext ctx : genCtx.values()) {
2011 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2012 if (result != null) {
2019 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2020 for (final ModuleContext ctx : genCtx.values()) {
2021 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2022 if (result != null) {
2029 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2030 for (final ModuleContext ctx : genCtx.values()) {
2031 final GeneratedTypeBuilder result = ctx.getCase(path);
2032 if (result != null) {
2039 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2040 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2041 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2044 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2045 switch (node.getStatus()) {
2047 // FIXME: we really want to use a pre-made annotation
2048 builder.addAnnotation(DEPRECATED_ANNOTATION);
2051 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2057 throw new IllegalStateException("Unhandled status in " + node);
2061 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2062 defaultImplementedInterace(typeBuilder);
2064 typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2065 .setAccessModifier(AccessModifier.PUBLIC)
2067 .setReturnType(primitiveIntType());
2068 typeBuilder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
2069 .setAccessModifier(AccessModifier.PUBLIC)
2071 .setReturnType(primitiveBooleanType());
2072 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2073 .setAccessModifier(AccessModifier.PUBLIC)
2075 .setReturnType(STRING);
2078 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2079 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2082 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2083 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2086 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2087 final Type classType) {
2088 final MethodSignatureBuilder ret = typeBuilder
2089 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2090 .setAccessModifier(AccessModifier.PUBLIC)
2091 .setReturnType(classType(classType));
2092 ret.addAnnotation(OVERRIDE_ANNOTATION);