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.primitiveVoidType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
51 import com.google.common.base.Splitter;
52 import com.google.common.collect.Iterables;
53 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
54 import java.util.AbstractMap.SimpleImmutableEntry;
55 import java.util.ArrayList;
56 import java.util.Collection;
57 import java.util.Collections;
58 import java.util.Comparator;
59 import java.util.HashMap;
60 import java.util.HashSet;
61 import java.util.Iterator;
62 import java.util.List;
64 import java.util.Optional;
65 import org.eclipse.jdt.annotation.NonNull;
66 import org.eclipse.jdt.annotation.Nullable;
67 import org.opendaylight.mdsal.binding.generator.util.BaseYangTypes;
68 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
69 import org.opendaylight.mdsal.binding.model.api.Constant;
70 import org.opendaylight.mdsal.binding.model.api.DefaultType;
71 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
72 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
73 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
74 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
75 import org.opendaylight.mdsal.binding.model.api.Restrictions;
76 import org.opendaylight.mdsal.binding.model.api.Type;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
86 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
87 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
88 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
89 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
90 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
91 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
92 import org.opendaylight.yangtools.yang.common.QName;
93 import org.opendaylight.yangtools.yang.common.QNameModule;
94 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
95 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
103 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
106 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
107 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
108 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.Module;
113 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
114 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
115 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
116 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
120 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.UsesNode;
123 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
124 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
126 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
127 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
128 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
129 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
130 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
131 import org.slf4j.Logger;
132 import org.slf4j.LoggerFactory;
134 abstract class AbstractTypeGenerator {
135 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
136 private static final Splitter COLON_SPLITTER = Splitter.on(':');
137 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
138 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
139 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
142 * Comparator based on augment target path.
144 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
145 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
146 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
148 while (thisIt.hasNext()) {
149 if (!otherIt.hasNext()) {
153 final int comp = thisIt.next().compareTo(otherIt.next());
159 return otherIt.hasNext() ? -1 : 0;
163 * Constant with the concrete name of identifier.
165 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
168 * Constant with the concrete name of namespace.
170 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
172 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
175 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
176 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
177 * for schema node specified in key part.
179 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
182 * Provide methods for converting YANG types to JAVA types.
184 private final AbstractTypeProvider typeProvider;
187 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
189 private final @NonNull SchemaContext schemaContext;
192 * Holds renamed elements.
194 private final Map<SchemaNode, JavaTypeName> renames;
196 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
197 final Map<SchemaNode, JavaTypeName> renames) {
198 this.schemaContext = requireNonNull(context);
199 this.typeProvider = requireNonNull(typeProvider);
200 this.renames = requireNonNull(renames);
202 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
203 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
204 for (final Module contextModule : contextModules) {
205 contexts.add(moduleToGenTypes(contextModule));
208 contexts.forEach(this::allAugmentsToGenTypes);
211 final @NonNull SchemaContext schemaContext() {
212 return schemaContext;
215 final Collection<ModuleContext> moduleContexts() {
216 return genCtx.values();
219 final ModuleContext moduleContext(final QNameModule module) {
220 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
223 final AbstractTypeProvider typeProvider() {
227 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
229 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
231 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
232 Collection<? extends SchemaNode> nodes);
234 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
236 private ModuleContext moduleToGenTypes(final Module module) {
237 final ModuleContext context = new ModuleContext(module);
238 genCtx.put(module.getQNameModule(), context);
239 allTypeDefinitionsToGenTypes(context);
240 groupingsToGenTypes(context, module.getGroupings());
241 rpcMethodsToGenType(context);
242 allIdentitiesToGenTypes(context);
243 notificationsToGenType(context);
245 if (!module.getChildNodes().isEmpty()) {
246 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
247 context.addModuleNode(moduleType);
248 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
254 * Converts all extended type definitions of module to the list of
255 * <code>Type</code> objects.
258 * module from which is obtained set of type definitions
259 * @throws IllegalArgumentException
261 * <li>if module is null</li>
262 * <li>if name of module is null</li>
264 * @throws IllegalStateException
265 * if set of type definitions from module is null
267 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
268 final Module module = context.module();
269 checkArgument(module.getName() != null, "Module name cannot be NULL.");
271 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
272 if (typedef != null) {
273 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
275 context.addTypedefType(typedef, type);
276 context.addTypeToSchema(type,typedef);
282 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
283 final DataSchemaNode node, final boolean inGrouping) {
284 if (node.isAugmenting() || node.isAddedByUses()) {
287 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
288 defaultImplementedInterace(genType);
289 annotateDeprecatedIfNecessary(node, genType);
291 final Module module = context.module();
292 genType.setModuleName(module.getName());
293 addCodegenInformation(genType, module, node);
294 genType.setSchemaPath(node.getPath());
295 if (node instanceof DataNodeContainer) {
296 context.addChildNodeType(node, genType);
297 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
298 processUsesAugments((DataNodeContainer) node, context, inGrouping);
303 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
304 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
305 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
306 if (genType != null) {
307 constructGetter(parent, genType, node);
308 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
309 actionsToGenType(context, genType, node, null, inGrouping);
310 notificationsToGenType(context, genType, node, null, inGrouping);
314 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
315 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
316 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
317 if (genType != null) {
318 final List<String> listKeys = listKeys(node);
319 final GeneratedTOBuilder keyTypeBuilder;
320 if (!listKeys.isEmpty()) {
321 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
322 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
323 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
324 .addImplementsType(identifier(genType));
325 genType.addImplementsType(identifiable(keyTypeBuilder));
327 keyTypeBuilder = null;
330 // Decide whether to generate a List or a Map
331 final ParameterizedType listType;
332 if (keyTypeBuilder != null && !node.isUserOrdered()) {
333 listType = mapTypeFor(keyTypeBuilder, genType);
335 listType = listTypeFor(genType);
338 constructGetter(parent, listType, node);
339 constructNonnull(parent, listType, node);
341 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
342 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
344 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
345 if (!schemaNode.isAugmenting()) {
346 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
351 if (keyTypeBuilder != null) {
352 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
353 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
354 keyTypeBuilder.setSUID(prop);
357 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
361 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
362 final boolean inGrouping) {
363 for (final UsesNode usesNode : node.getUses()) {
364 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
365 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
366 processUsesAugments(augment, context, inGrouping);
372 * Converts all <b>augmentation</b> of the module to the list
373 * <code>Type</code> objects.
376 * module from which is obtained list of all augmentation objects
377 * to iterate over them
378 * @throws IllegalArgumentException
380 * <li>if the module is null</li>
381 * <li>if the name of module is null</li>
383 * @throws IllegalStateException
384 * if set of augmentations from module is null
386 private void allAugmentsToGenTypes(final ModuleContext context) {
387 final Module module = context.module();
388 checkArgument(module != null, "Module reference cannot be NULL.");
389 checkArgument(module.getName() != null, "Module name cannot be NULL.");
390 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
392 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
393 augmentationToGenTypes(context, augment);
398 * Returns list of <code>AugmentationSchema</code> objects. The objects are
399 * sorted according to the length of their target path from the shortest to
403 * module from which is obtained list of all augmentation objects
404 * @return list of sorted <code>AugmentationSchema</code> objects obtained
405 * from <code>module</code>
406 * @throws IllegalArgumentException
408 * @throws IllegalStateException
409 * if set of module augmentations is null
411 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
412 checkArgument(module != null, "Module reference cannot be NULL.");
413 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
415 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
416 sortedAugmentations.sort(AUGMENT_COMP);
418 return sortedAugmentations;
422 * Create GeneratedTypeBuilder object from module argument.
425 * Module object from which builder will be created
426 * @return <code>GeneratedTypeBuilder</code> which is internal
427 * representation of the module
428 * @throws IllegalArgumentException
431 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
432 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
433 final Module module = context.module();
434 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
435 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
437 addCodegenInformation(moduleDataTypeBuilder, module);
438 return moduleDataTypeBuilder;
441 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
442 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
443 for (final ActionDefinition action : parentSchema.getActions()) {
444 if (action.isAugmenting()) {
448 final GeneratedType input;
449 final GeneratedType output;
450 if (action.isAddedByUses()) {
451 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
452 // Original definition may live in a different module, make sure we account for that
453 final ModuleContext origContext = moduleContext(
454 orig.getPath().getPathFromRoot().iterator().next().getModule());
455 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
456 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
458 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
459 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
462 if (!(parentSchema instanceof GroupingDefinition)) {
463 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
464 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
465 // and do not capture an actual instantiation.
466 final QName qname = action.getQName();
467 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
468 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
469 BindingMapping.getClassName(qname)));
470 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
472 annotateDeprecatedIfNecessary(action, builder);
473 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
474 : action(parent, input, output));
476 addCodegenInformation(builder, context.module(), action);
477 context.addChildNodeType(action, builder);
482 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
483 final QName qname = action.getQName();
484 for (UsesNode uses : parent.getUses()) {
485 final GroupingDefinition grp = uses.getSourceGrouping();
486 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
488 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
489 if (found.isPresent()) {
490 final ActionDefinition result = found.get();
491 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
495 return Optional.empty();
498 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
499 final ContainerSchemaNode schema, final boolean inGrouping) {
500 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
501 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
502 return genType.build();
506 * Converts all <b>RPCs</b> input and output substatements of the module
507 * to the list of <code>Type</code> objects. In addition are to containers
508 * and lists which belong to input or output also part of returning list.
511 * module from which is obtained set of all rpc objects to
513 * @throws IllegalArgumentException
515 * <li>if the module is null</li>
516 * <li>if the name of module is null</li>
518 * @throws IllegalStateException
519 * if set of rpcs from module is null
521 private void rpcMethodsToGenType(final ModuleContext context) {
522 final Module module = context.module();
523 checkArgument(module.getName() != null, "Module name cannot be NULL.");
524 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
525 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
526 if (rpcDefinitions.isEmpty()) {
530 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
531 interfaceBuilder.addImplementsType(RPC_SERVICE);
533 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
535 for (final RpcDefinition rpc : rpcDefinitions) {
537 final String rpcName = BindingMapping.getClassName(rpc.getQName());
538 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
539 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
541 // Do not refer to annotation class, as it may not be available at runtime
542 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
543 addComment(method, rpc);
545 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
546 method.setReturnType(listenableFutureTypeFor(
547 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
551 context.addTopLevelNodeType(interfaceBuilder);
554 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
555 final ContainerSchemaNode schema, final Type type) {
556 processUsesAugments(schema, context, false);
557 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
558 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
560 addImplementedInterfaceFromUses(schema, outType);
561 outType.addImplementsType(type);
562 outType.addImplementsType(augmentable(outType));
563 defaultImplementedInterace(outType);
564 annotateDeprecatedIfNecessary(rpc, outType);
565 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
566 context.addChildNodeType(schema, outType);
567 return outType.build();
571 * Converts all <b>notifications</b> of the module to the list of
572 * <code>Type</code> objects. In addition are to this list added containers
573 * and lists which are part of this notification.
576 * module from which is obtained set of all notification objects
577 * to iterate over them
578 * @throws IllegalArgumentException
580 * <li>if the module equals null</li>
581 * <li>if the name of module equals null</li>
583 * @throws IllegalStateException
584 * if set of notifications from module is null
586 private void notificationsToGenType(final ModuleContext context) {
587 final Module module = context.module();
588 checkArgument(module.getName() != null, "Module name cannot be NULL.");
589 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
590 if (notifications.isEmpty()) {
594 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
595 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
597 for (final NotificationDefinition notification : notifications) {
598 if (notification != null) {
599 processUsesAugments(notification, context, false);
601 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
602 context.modulePackageName(), notification, DATA_OBJECT, context);
603 defaultImplementedInterace(notificationInterface);
604 annotateDeprecatedIfNecessary(notification, notificationInterface);
605 notificationInterface.addImplementsType(NOTIFICATION);
606 context.addChildNodeType(notification, notificationInterface);
608 // Notification object
609 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
610 notification.getChildNodes(), false);
612 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
613 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
614 .setReturnType(primitiveVoidType()), notification);
618 addCodegenInformation(listenerInterface, module, "notifications", notifications);
619 context.addTopLevelNodeType(listenerInterface);
622 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
623 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
624 final boolean inGrouping) {
625 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
626 if (notifications.isEmpty()) {
630 for (NotificationDefinition notif : notifications) {
631 if (notif.isAugmenting()) {
634 if (parentSchema instanceof GroupingDefinition) {
635 // Notifications cannot be really established, as they lack instantiation context, which would be
636 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
640 processUsesAugments(notif, context, false);
642 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
643 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
644 defaultImplementedInterace(notifInterface);
645 annotateDeprecatedIfNecessary(notif, notifInterface);
647 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
648 : instanceNotification(notifInterface, parent));
649 context.addChildNodeType(notif, notifInterface);
651 // Notification object
652 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
657 * Converts all <b>identities</b> of the module to the list of
658 * <code>Type</code> objects.
661 * module from which is obtained set of all identity objects to
663 * @param schemaContext
664 * schema context only used as input parameter for method
665 * {@link BindingGeneratorImpl#identityToGenType}
668 private void allIdentitiesToGenTypes(final ModuleContext context) {
669 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
671 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
672 for (final IdentitySchemaNode identity : schemaIdentities) {
673 identityToGenType(context, identity);
679 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
680 * created transport object builder. If identity contains base identity then
681 * reference to base identity is added to superior identity as its extend.
682 * If identity doesn't contain base identity then only reference to abstract
683 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
684 * BaseIdentity} is added
688 * @param basePackageName
689 * string contains the module package name
691 * IdentitySchemaNode which contains data about identity
693 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
694 if (identity == null) {
698 JavaTypeName name = renames.get(identity);
700 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
701 BindingMapping.getClassName(identity.getQName()));
704 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
705 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
706 if (!baseIdentities.isEmpty()) {
707 for (IdentitySchemaNode baseIdentity : baseIdentities) {
708 JavaTypeName base = renames.get(baseIdentity);
710 final QName qname = baseIdentity.getQName();
711 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
712 BindingMapping.getClassName(qname));
715 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
716 newType.addImplementsType(gto);
719 newType.addImplementsType(BASE_IDENTITY);
722 final Module module = context.module();
723 addCodegenInformation(newType, module, identity);
724 newType.setModuleName(module.getName());
725 newType.setSchemaPath(identity.getPath());
727 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
729 context.addIdentityType(identity, newType);
732 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
733 final JavaTypeName yangModuleInfo, final String localName) {
734 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
735 new SimpleImmutableEntry<>(yangModuleInfo, localName));
739 * Converts all <b>groupings</b> of the module to the list of
740 * <code>Type</code> objects. Firstly are groupings sorted according mutual
741 * dependencies. At least dependent (independent) groupings are in the list
742 * saved at first positions. For every grouping the record is added to map
743 * {@link ModuleContext#groupings allGroupings}
748 * collection of groupings from which types will be generated
751 private void groupingsToGenTypes(final ModuleContext context,
752 final Collection<? extends GroupingDefinition> groupings) {
753 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
754 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
755 // node of grouping is resolved to the method.
756 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
757 narrowImplementedInterface(genType);
758 annotateDeprecatedIfNecessary(grouping, genType);
759 context.addGroupingType(grouping, genType);
760 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
761 groupingsToGenTypes(context, grouping.getGroupings());
762 processUsesAugments(grouping, context, true);
763 actionsToGenType(context, genType, grouping, null, true);
764 notificationsToGenType(context, genType, grouping, null, true);
769 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
770 * <code>enumTypeDef</code> item is added to builder with its name and value.
772 * @param enumTypeDef EnumTypeDefinition contains enum data
773 * @param enumName string contains name which will be assigned to enumeration builder
774 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
775 * @param module Module in which type should be generated
776 * @return enumeration builder which contains data from <code>enumTypeDef</code>
778 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
779 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
780 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
781 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
782 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
783 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
784 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
791 * Generates type builder for <code>module</code>.
793 * @param module Module which is source of package name for generated type builder
794 * @param postfix string which is added to the module class name representation as suffix
795 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
796 * @throws IllegalArgumentException if <code>module</code> is null
798 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
799 final Module module = context.module();
800 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
801 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
802 JavaTypeName.create(context.modulePackageName(), moduleName));
804 moduleBuilder.setModuleName(moduleName);
805 addCodegenInformation(moduleBuilder, module);
806 return moduleBuilder;
810 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
811 * In addition there are also generated types for all containers, list and choices which are child of
812 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
814 * @param augmentPackageName string with the name of the package to which the augmentation belongs
815 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
816 * @param module current module
817 * @throws IllegalArgumentException
819 * <li>if <code>augmentPackageName</code> equals null</li>
820 * <li>if <code>augSchema</code> equals null</li>
822 * @throws IllegalStateException
823 * if augment target path is null
825 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
826 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
827 checkState(augSchema.getTargetPath() != null,
828 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
830 processUsesAugments(augSchema, context, false);
831 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
832 SchemaNode targetSchemaNode = null;
834 // FIXME: can we use findDataSchemaNode() instead?
835 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
836 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
837 if (targetSchemaNode instanceof DerivableSchemaNode) {
838 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
840 if (targetSchemaNode == null) {
841 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
842 + " in module " + context.module().getName());
845 if (targetSchemaNode == null) {
846 throw new IllegalArgumentException("augment target not found: " + targetPath);
849 if (targetSchemaNode instanceof ChoiceSchemaNode) {
850 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
851 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
852 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
853 augSchema.getChildNodes(), null, false);
857 final JavaTypeName targetName;
858 if (targetSchemaNode instanceof CaseSchemaNode) {
859 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
860 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
861 targetName = builder.getIdentifier();
863 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
864 if (builder == null) {
865 targetName = findAliasByPath(targetSchemaNode.getPath());
866 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
868 targetName = builder.getIdentifier();
872 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
875 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
876 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
877 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
878 checkState(augSchema.getTargetPath() != null,
879 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
881 processUsesAugments(augSchema, context, inGrouping);
882 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
883 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
884 if (targetSchemaNode == null) {
885 throw new IllegalArgumentException("augment target not found: " + targetPath);
888 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
889 if (targetTypeBuilder == null) {
890 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
892 if (targetTypeBuilder == null) {
893 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
896 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
897 if (usesNodeParent instanceof SchemaNode) {
898 addRawAugmentGenTypeDefinition(context,
899 packageNameForAugmentedGeneratedType(context.modulePackageName(),
900 ((SchemaNode) usesNodeParent).getPath()),
901 targetTypeBuilder.build(), augSchema, inGrouping);
903 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
906 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
907 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
912 * Convenient method to find node added by uses statement.
914 * @param targetPath node path
915 * @param parentUsesNode parent of uses node
916 * @return node from its original location in grouping
918 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
919 final UsesNode parentUsesNode) {
920 SchemaNode result = parentUsesNode.getSourceGrouping();
921 for (final QName node : targetPath.getNodeIdentifiers()) {
922 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
923 if (result instanceof DataNodeContainer) {
924 final QName resultNode = node.bindTo(result.getQName().getModule());
926 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
928 if (result instanceof ActionNodeContainer) {
929 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
931 if (found == null && result instanceof NotificationNodeContainer) {
932 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
936 } else if (result instanceof ChoiceSchemaNode) {
937 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
938 } else if (result instanceof ActionDefinition) {
939 final ActionDefinition action = (ActionDefinition) result;
940 final QName resultNode = node.bindTo(result.getQName().getModule());
942 final ContainerSchemaNode input = action.getInput();
943 final ContainerSchemaNode output = action.getOutput();
944 if (resultNode.equals(input.getQName())) {
946 } else if (resultNode.equals(output.getQName())) {
951 } else if (result != null) {
952 throw new IllegalStateException("Cannot handle " + result);
955 if (result == null) {
959 if (result instanceof DerivableSchemaNode) {
960 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
961 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
962 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
963 result = originalNode.get();
967 if (result instanceof DataSchemaNode) {
968 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
969 if (resultDataSchemaNode.isAddedByUses()) {
970 // The original node is required, but we have only the copy of
971 // the original node.
972 // Maybe this indicates a bug in Yang parser.
973 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
976 return resultDataSchemaNode;
979 throw new IllegalStateException(
980 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
985 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
986 * of augmented node with serial number as suffix.
988 * @param context current module
989 * @param augmentPackageName string with contains the package name to which the augment belongs
990 * @param basePackageName string with the package name to which the augmented node belongs
991 * @param targetTypeRef target type
992 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
993 * @return generated type builder for augment
995 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
996 final String augmentPackageName, final Type targetTypeRef,
997 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
998 Map<String, GeneratedTypeBuilder> augmentBuilders =
999 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1000 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1003 if (augIdentifier != null) {
1004 augTypeName = BindingMapping.getClassName(augIdentifier);
1006 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1009 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1010 JavaTypeName.create(augmentPackageName, augTypeName));
1012 augTypeBuilder.addImplementsType(DATA_OBJECT);
1013 defaultImplementedInterace(augTypeBuilder);
1015 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1016 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1017 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1019 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1020 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1021 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1023 augmentBuilders.put(augTypeName, augTypeBuilder);
1025 if (!augSchema.getChildNodes().isEmpty()) {
1026 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1029 context.addAugmentType(augTypeBuilder);
1030 return augTypeBuilder;
1033 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1034 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1035 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1039 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1040 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1041 final QName nodeType = unknownSchemaNode.getNodeType();
1042 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1043 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1044 return unknownSchemaNode.getNodeParameter();
1051 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1052 * consists from name of augmented node and serial number of its augmentation.
1054 * @param builders map of builders which were created in the package to which the augmentation belongs
1055 * @param genTypeName string with name of augmented node
1056 * @return string with unique name for augmentation builder
1058 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1060 if (builders != null) {
1061 while (builders.containsKey(genTypeName + index)) {
1065 return genTypeName + index;
1069 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1070 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1071 * already part of them).
1073 * @param module current module
1074 * @param parent generated type builder which represents any node. The subnodes of this node are added
1075 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1076 * container, choice.
1077 * @param childOf parent type
1078 * @param schemaNodes set of data schema nodes which are the children of the node for which
1079 * <code>typeBuilder</code> was created
1080 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1081 * child nodes) could be added to it.
1083 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1084 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1085 final boolean inGrouping) {
1086 if (schemaNodes != null && parent != null) {
1087 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1088 for (final DataSchemaNode schemaNode : schemaNodes) {
1089 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1090 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1098 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1101 * @param module current module
1102 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1103 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1104 * container, choice.
1105 * @param childOf parent type
1106 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1108 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1109 * The getter method could be added to it.
1111 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1112 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1113 final boolean inGrouping) {
1114 if (schemaNodes != null && typeBuilder != null) {
1115 final Type baseInterface = childOf(typeBuilder);
1116 for (final DataSchemaNode schemaNode : schemaNodes) {
1117 if (!schemaNode.isAugmenting()) {
1118 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1126 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1128 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1129 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1130 * @param childOf parent type
1131 * @param module current module
1133 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1134 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1135 if (node != null && typeBuilder != null) {
1136 if (node instanceof LeafSchemaNode) {
1137 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1138 } else if (node instanceof LeafListSchemaNode) {
1139 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1140 } else if (node instanceof ContainerSchemaNode) {
1141 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1142 } else if (node instanceof ListSchemaNode) {
1143 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1144 } else if (node instanceof ChoiceSchemaNode) {
1145 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1146 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1147 opaqueToGeneratedType(context, typeBuilder, node);
1149 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1150 typeBuilder.getFullyQualifiedName());
1156 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1157 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1158 * and names of all parents node.
1160 * @param context current module
1161 * @param basePackageName string with the module package name
1162 * @param parent parent type
1163 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1165 * @throws IllegalArgumentException
1167 * <li>if <code>basePackageName</code> is null</li>
1168 * <li>if <code>choiceNode</code> is null</li>
1171 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1172 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1173 if (!choiceNode.isAddedByUses()) {
1174 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1175 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1176 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1177 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1178 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1179 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1181 final GeneratedType choiceType = choiceTypeBuilder.build();
1182 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1184 constructGetter(parent, choiceType, choiceNode);
1188 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1189 final DataSchemaNode anyNode) {
1190 if (!anyNode.isAddedByUses()) {
1191 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1192 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1193 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1194 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1195 defaultImplementedInterace(anyxmlTypeBuilder);
1196 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1197 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1199 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1204 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1205 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1206 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1207 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1209 * @param context current module context
1210 * @param refChoiceType type which represents superior <i>case</i>
1211 * @param choiceNode choice case node which is mapped to generated type
1212 * @throws IllegalArgumentException
1214 * <li>if <code>refChoiceType</code> equals null</li>
1215 * <li>if <code>caseNodes</code> equals null</li>
1218 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1219 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1220 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1221 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1223 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1224 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1225 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1226 caseTypeBuilder.addImplementsType(refChoiceType);
1227 defaultImplementedInterace(caseTypeBuilder);
1228 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1229 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1230 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1231 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1232 if (caseChildNodes != null) {
1233 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1235 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1236 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1238 if (parent instanceof AugmentationSchemaNode) {
1239 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1240 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1241 // FIXME: can we use findDataSchemaNode?
1242 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1243 targetPath.getNodeIdentifiers());
1244 if (targetSchemaNode instanceof DataSchemaNode
1245 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1246 if (targetSchemaNode instanceof DerivableSchemaNode) {
1247 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1250 if (targetSchemaNode == null) {
1251 throw new IllegalStateException(
1252 "Failed to find target node from grouping for augmentation " + augSchema
1253 + " in module " + context.module().getName());
1256 parent = targetSchemaNode;
1259 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1260 Type childOfType = findChildNodeByPath(parent.getPath());
1261 if (childOfType == null) {
1262 childOfType = findGroupingByPath(parent.getPath());
1264 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1266 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1271 processUsesAugments(caseNode, context, inGrouping);
1276 * Generates list of generated types for all the cases of a choice which are added to the choice through
1279 * @param module current module
1280 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1281 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1282 * of the augmenting choice will belong to pcg2.
1283 * @param targetType Type which represents target choice
1284 * @param targetNode node which represents target choice
1285 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1287 * @throws IllegalArgumentException
1289 * <li>if <code>basePackageName</code> is null</li>
1290 * <li>if <code>targetType</code> is null</li>
1291 * <li>if <code>augmentedNodes</code> is null</li>
1294 // FIXME: nullness rules need to untangled in this method
1295 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1296 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1297 final Type targetType, final ChoiceSchemaNode targetNode,
1298 final Iterable<? extends DataSchemaNode> augmentedNodes,
1299 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1300 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1301 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1303 for (final DataSchemaNode caseNode : augmentedNodes) {
1304 if (caseNode != null) {
1305 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1306 caseTypeBuilder.addImplementsType(targetType);
1307 defaultImplementedInterace(caseTypeBuilder);
1309 CaseSchemaNode node = null;
1310 final String caseLocalName = caseNode.getQName().getLocalName();
1311 if (caseNode instanceof CaseSchemaNode) {
1312 node = (CaseSchemaNode) caseNode;
1313 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1314 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1315 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1316 if (dataSchemaNode instanceof ChoiceSchemaNode
1317 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1318 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1323 node = findNamedCase(targetNode, caseLocalName);
1325 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1326 if (childNodes != null) {
1327 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1330 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1331 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1336 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1337 final SchemaPath nodePath = targetNode.getPath();
1338 final SchemaPath parentSp = nodePath.getParent();
1339 if (parentSp.getParent() == null) {
1340 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1343 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1344 GeneratedTypeBuilder childOfType = null;
1345 if (parent instanceof CaseSchemaNode) {
1346 childOfType = findCaseByPath(parent.getPath());
1347 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1348 childOfType = findChildNodeByPath(parent.getPath());
1349 } else if (parent instanceof GroupingDefinition) {
1350 childOfType = findGroupingByPath(parent.getPath());
1353 if (childOfType == null) {
1354 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1360 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1361 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1362 return cases.isEmpty() ? null : cases.get(0);
1365 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1366 // New parser with encapsulated type
1367 if (leaf.getPath().equals(type.getPath())) {
1371 // Embedded type definition with new parser. Also takes care of the old parser with bits
1372 if (leaf.getPath().equals(type.getPath().getParent())) {
1379 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1380 final List<PatternConstraint> patternConstraints) {
1381 if (!patternConstraints.isEmpty()) {
1382 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1383 .append(BindingMapping.getPropertyName(leafName));
1384 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1385 typeProvider.resolveRegExpressions(patternConstraints));
1390 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1392 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1393 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1394 * @param module Module in which type was defined
1395 * @return boolean value
1397 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1399 * <li>true - in other cases</li>
1402 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1403 final ModuleContext context, final boolean inGrouping) {
1404 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1408 final Module parentModule = findParentModule(schemaContext, leaf);
1409 Type returnType = null;
1411 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1412 if (isInnerType(leaf, typeDef)) {
1413 if (typeDef instanceof EnumTypeDefinition) {
1414 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1415 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1416 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1417 typeBuilder, context);
1418 if (enumBuilder != null) {
1419 returnType = enumBuilder.toInstance(typeBuilder);
1421 typeProvider.putReferencedType(leaf.getPath(), returnType);
1422 } else if (typeDef instanceof UnionTypeDefinition) {
1423 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1424 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1425 // Store the inner type within the union so that we can find the reference for it
1426 context.addInnerTypedefType(typeDef.getPath(), returnType);
1427 } else if (typeDef instanceof BitsTypeDefinition) {
1428 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1430 if (genTOBuilder != null) {
1431 returnType = genTOBuilder.build();
1434 // It is constrained version of already declared type (inner declared type exists,
1435 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1436 // In order to get proper class we need to look up closest derived type
1437 // and apply restrictions from leaf type
1438 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1439 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1440 restrictions, inGrouping);
1441 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1444 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1445 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1446 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1449 if (returnType == null) {
1453 if (typeDef instanceof EnumTypeDefinition) {
1454 typeProvider.putReferencedType(leaf.getPath(), returnType);
1457 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1458 processContextRefExtension(leaf, getter, parentModule);
1462 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1463 // Returns DerivedType in case of new parser.
1464 final TypeDefinition<?> baseType = typeDef.getBaseType();
1465 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1468 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1469 final Module module) {
1470 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1471 final QName nodeType = node.getNodeType();
1472 if ("context-reference".equals(nodeType.getLocalName())) {
1473 final String nodeParam = node.getNodeParameter();
1474 IdentitySchemaNode identity = null;
1475 String basePackageName = null;
1476 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1477 final Iterator<String> iterator = splittedElement.iterator();
1478 final int length = Iterables.size(splittedElement);
1480 identity = findIdentityByName(module.getIdentities(), iterator.next());
1481 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1482 } else if (length == 2) {
1483 final String prefix = iterator.next();
1484 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1485 if (dependentModule == null) {
1486 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1489 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1490 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1492 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1495 if (identity == null) {
1496 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1500 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1501 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1502 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1503 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1508 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1509 final String name) {
1510 for (final IdentitySchemaNode id : identities) {
1511 if (id.getQName().getLocalName().equals(name)) {
1518 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1519 for (final ModuleImport imp : imports) {
1520 if (imp.getPrefix().equals(prefix)) {
1521 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1527 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1528 final boolean isReadOnly) {
1529 if (leaf != null && toBuilder != null) {
1531 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1532 if (typeDef instanceof UnionTypeDefinition) {
1533 // GeneratedType for this type definition should have be already created
1534 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1535 returnType = mc.getTypedefs().get(typeDef.getPath());
1536 if (returnType == null) {
1537 // This may still be an inner type, try to find it
1538 returnType = mc.getInnerType(typeDef.getPath());
1540 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1541 // Annonymous enumeration (already generated, since it is inherited via uses).
1542 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1543 QName qname = originalLeaf.getQName();
1544 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1546 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1548 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1554 * Converts <code>leaf</code> schema node to property of generated TO builder.
1556 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1557 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1558 * @param returnType property type
1559 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1560 * @return boolean value
1562 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1563 * name equals null or if leaf is added by <i>uses</i>.</li>
1564 * <li>true - other cases</li>
1567 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1568 final Type returnType, final boolean isReadOnly) {
1569 if (returnType == null) {
1572 final String leafName = leaf.getQName().getLocalName();
1573 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1574 propBuilder.setReadOnly(isReadOnly);
1575 propBuilder.setReturnType(returnType);
1576 addComment(propBuilder, leaf);
1578 toBuilder.addEqualsIdentity(propBuilder);
1579 toBuilder.addHashIdentity(propBuilder);
1580 toBuilder.addToStringProperty(propBuilder);
1585 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1587 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1588 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1589 * @param module module
1590 * @return boolean value
1592 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1593 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1594 * <li>false - other cases</li>
1597 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1598 final ModuleContext context, final boolean inGrouping) {
1599 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1603 final QName nodeName = node.getQName();
1605 final TypeDefinition<?> typeDef = node.getType();
1606 final Module parentModule = findParentModule(schemaContext, node);
1608 Type returnType = null;
1609 if (typeDef.getBaseType() == null) {
1610 if (typeDef instanceof EnumTypeDefinition) {
1611 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1612 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1613 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1614 typeBuilder, context);
1615 returnType = DefaultType.of(enumBuilder);
1616 typeProvider.putReferencedType(node.getPath(), returnType);
1617 } else if (typeDef instanceof UnionTypeDefinition) {
1618 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1619 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1620 } else if (typeDef instanceof BitsTypeDefinition) {
1621 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1622 node, parentModule);
1623 returnType = genTOBuilder.build();
1625 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1626 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1627 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1630 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1631 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1632 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1635 constructGetter(typeBuilder, listTypeFor(returnType), node);
1639 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1640 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1641 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1642 returnTypeBuilder.setIsUnion(true);
1643 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1644 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1645 returnTypeBuilder.setModuleName(parentModule.getName());
1646 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1648 genTOBuilder.setTypedef(true);
1649 genTOBuilder.setIsUnion(true);
1650 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1652 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1656 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1657 final GeneratedTransferObject returnType, final Module parentModule) {
1658 // Append enclosing path hierarchy without dots
1659 final StringBuilder sb = new StringBuilder();
1660 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1661 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1662 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1663 unionBuilder.setIsUnionBuilder(true);
1665 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1666 method.setReturnType(returnType);
1667 method.addParameter(STRING, "defaultValue");
1668 method.setAccessModifier(AccessModifier.PUBLIC);
1669 method.setStatic(true);
1671 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1672 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1675 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1676 final SchemaNode schemaNode) {
1677 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1680 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1681 final SchemaNode schemaNode, final Type baseInterface) {
1682 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1683 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1687 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1688 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1689 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1690 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1691 * If <code>schemaNode</code> is instance of
1692 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1693 * which are specified in <i>uses</i>.
1695 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1696 * @param schemaNode schema node for which is created generated type builder
1697 * @param parent parent type (can be null)
1698 * @return generated type builder <code>schemaNode</code>
1700 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1701 final Type baseInterface, final ModuleContext context) {
1702 JavaTypeName name = renames.get(schemaNode);
1704 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1707 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1708 it.addImplementsType(baseInterface);
1709 if (!(schemaNode instanceof GroupingDefinition)) {
1710 it.addImplementsType(augmentable(it));
1712 if (schemaNode instanceof DataNodeContainer) {
1713 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1714 groupingsToGenTypes(context, containerSchema.getGroupings());
1715 addImplementedInterfaceFromUses(containerSchema, it);
1722 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1723 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1724 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1726 * @param packageName string with the package name to which returning generated type builder belongs
1727 * @param schemaNode schema node which provide data about the schema node name
1728 * @param prefix return type name prefix
1729 * @return generated type builder for <code>schemaNode</code>
1730 * @throws IllegalArgumentException
1732 * <li>if <code>schemaNode</code> is null</li>
1733 * <li>if <code>packageName</code> is null</li>
1734 * <li>if QName of schema node is null</li>
1735 * <li>if schemaNode name is null</li>
1738 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1739 final SchemaNode schemaNode) {
1740 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1741 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1742 final String schemaNodeName = schemaNode.getQName().getLocalName();
1743 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1745 // FIXME: Validation of name conflict
1746 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1747 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1749 final Module module = context.module();
1750 addCodegenInformation(newType, module, schemaNode);
1751 newType.setSchemaPath(schemaNode.getPath());
1752 newType.setModuleName(module.getName());
1754 final String packageName = identifier.packageName();
1755 final String simpleName = identifier.simpleName();
1756 if (!genTypeBuilders.containsKey(packageName)) {
1757 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1758 builders.put(simpleName, newType);
1759 genTypeBuilders.put(packageName, builders);
1761 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1762 if (!builders.containsKey(simpleName)) {
1763 builders.put(simpleName, newType);
1770 * Creates the name of the getter method name from <code>localName</code>.
1772 * @param localName string with the name of the getter method
1773 * @param returnType return type
1774 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1776 public static String getterMethodName(final String localName, final Type returnType) {
1777 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1781 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1782 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1783 * and <code>returnType</code> information are added to the builder.
1785 * @param interfaceBuilder generated type builder for which the getter method should be created
1786 * @param returnType type which represents the return type of the getter method
1787 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1788 * @param comment string with comment for the getter method
1789 * @param status status from yang file, for deprecated annotation
1790 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1792 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1793 final SchemaNode node) {
1794 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1795 getterMethodName(node.getQName().getLocalName(), returnType));
1796 getMethod.setReturnType(returnType);
1798 annotateDeprecatedIfNecessary(node, getMethod);
1799 addComment(getMethod, node);
1804 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1805 final ListSchemaNode node) {
1806 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1807 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1808 getMethod.setReturnType(returnType).setDefault(true);
1809 annotateDeprecatedIfNecessary(node, getMethod);
1813 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1816 * @param basePackageName string contains the module package name
1817 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1818 * or as a property to <code>genTOBuilder</code> if is part of the list key
1819 * @param typeBuilder generated type builder for the list schema node
1820 * @param genTOBuilder generated TO builder for the list keys
1821 * @param listKeys list of string which contains names of the list keys
1822 * @param module current module
1823 * @throws IllegalArgumentException
1825 * <li>if <code>schemaNode</code> equals null</li>
1826 * <li>if <code>typeBuilder</code> equals null</li>
1829 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1830 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1831 final List<String> listKeys, final boolean inGrouping) {
1832 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1833 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1835 if (schemaNode instanceof LeafSchemaNode) {
1836 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1837 final String leafName = leaf.getQName().getLocalName();
1838 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1839 if (listKeys.contains(leafName)) {
1841 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1843 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1846 } else if (!schemaNode.isAddedByUses()) {
1847 if (schemaNode instanceof LeafListSchemaNode) {
1848 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1849 } else if (schemaNode instanceof ContainerSchemaNode) {
1850 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1851 (ContainerSchemaNode) schemaNode, inGrouping);
1852 } else if (schemaNode instanceof ChoiceSchemaNode) {
1853 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1854 } else if (schemaNode instanceof ListSchemaNode) {
1855 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1856 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1857 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1862 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1863 final GeneratedTOBuilder genTOBuilder) {
1864 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1866 if (genTOBuilder != null) {
1867 final GeneratedTransferObject genTO = genTOBuilder.build();
1868 // Add Identifiable.getKey() for items
1869 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1870 .addAnnotation(OVERRIDE_ANNOTATION);
1871 context.addGeneratedTOBuilder(genTOBuilder);
1876 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1878 * @param list of string with names of the list keys
1879 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1880 * an empty list is returned.
1882 private static List<String> listKeys(final ListSchemaNode list) {
1883 final List<QName> keyDefinition = list.getKeyDefinition();
1884 switch (keyDefinition.size()) {
1886 return Collections.emptyList();
1888 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1890 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1891 for (final QName keyDef : keyDefinition) {
1892 listKeys.add(keyDef.getLocalName());
1899 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1900 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1901 * enclosing transfer objects.
1903 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1904 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1905 * @param leaf string with name for generated TO builder
1906 * @param parentModule parent module
1907 * @return generated TO builder for <code>typeDef</code>
1909 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1910 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1911 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1912 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1914 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1915 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1916 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1917 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1918 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1920 for (GeneratedTOBuilder builder : types) {
1921 if (builder.isUnion()) {
1922 final GeneratedTransferObject type = builder.build();
1923 createUnionBuilder(builder, typeBuilder, type, parentModule);
1927 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1931 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1932 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1933 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1936 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1937 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1938 * @param leaf string with name for generated TO builder
1939 * @param parentModule parent module
1940 * @return generated TO builder for <code>typeDef</code>
1942 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1943 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1944 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1945 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1946 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1947 return genTOBuilder;
1951 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1952 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1953 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1954 * to <code>builder</code>
1956 * @param dataNodeContainer element which contains the list of used YANG groupings
1957 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1958 * @return generated type builder with all implemented types
1960 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1961 final GeneratedTypeBuilder builder) {
1962 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1963 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1964 if (genType == null) {
1965 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1966 + " is not resolved for " + builder.getName());
1969 builder.addImplementsType(genType.build());
1974 private JavaTypeName findAliasByPath(final SchemaPath path) {
1975 for (final ModuleContext ctx : genCtx.values()) {
1976 final JavaTypeName result = ctx.getAlias(path);
1977 if (result != null) {
1984 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1985 for (final ModuleContext ctx : genCtx.values()) {
1986 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1987 if (result != null) {
1994 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
1995 for (final ModuleContext ctx : genCtx.values()) {
1996 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
1997 if (result != null) {
2004 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2005 for (final ModuleContext ctx : genCtx.values()) {
2006 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2007 if (result != null) {
2014 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2015 for (final ModuleContext ctx : genCtx.values()) {
2016 final GeneratedTypeBuilder result = ctx.getCase(path);
2017 if (result != null) {
2024 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2025 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2026 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2029 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2030 switch (node.getStatus()) {
2032 // FIXME: we really want to use a pre-made annotation
2033 builder.addAnnotation(DEPRECATED_ANNOTATION);
2036 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2042 throw new IllegalStateException("Unhandled status in " + node);
2046 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2047 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2050 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2051 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2054 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2055 final Type classType) {
2056 final MethodSignatureBuilder ret = typeBuilder
2057 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2058 .setAccessModifier(AccessModifier.PUBLIC)
2059 .setReturnType(classType(classType));
2060 ret.addAnnotation(OVERRIDE_ANNOTATION);