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.STRING;
40 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
41 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeWildcard;
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.objectType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveBooleanType;
47 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
48 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
49 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
50 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
51 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
52 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
54 import com.google.common.base.Splitter;
55 import com.google.common.collect.Iterables;
56 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
57 import java.util.AbstractMap.SimpleImmutableEntry;
58 import java.util.ArrayList;
59 import java.util.Collection;
60 import java.util.Collections;
61 import java.util.Comparator;
62 import java.util.HashMap;
63 import java.util.HashSet;
64 import java.util.Iterator;
65 import java.util.List;
67 import java.util.Optional;
68 import org.eclipse.jdt.annotation.NonNull;
69 import org.eclipse.jdt.annotation.Nullable;
70 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
71 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
72 import org.opendaylight.mdsal.binding.model.api.Constant;
73 import org.opendaylight.mdsal.binding.model.api.DefaultType;
74 import org.opendaylight.mdsal.binding.model.api.Enumeration;
75 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
76 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
77 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
78 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
79 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
80 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
81 import org.opendaylight.mdsal.binding.model.api.Restrictions;
82 import org.opendaylight.mdsal.binding.model.api.Type;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
87 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
88 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
89 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
90 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
91 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
92 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
93 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
94 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
95 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
96 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
97 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
98 import org.opendaylight.mdsal.binding.yang.types.CompatUtils;
99 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
100 import org.opendaylight.yangtools.yang.common.QName;
101 import org.opendaylight.yangtools.yang.common.QNameModule;
102 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
103 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
104 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
110 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
112 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
115 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
116 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
117 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
118 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
120 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
123 import org.opendaylight.yangtools.yang.model.api.Module;
124 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
125 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
126 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
127 import org.opendaylight.yangtools.yang.model.api.OutputSchemaNode;
128 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
129 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
131 import org.opendaylight.yangtools.yang.model.api.Status;
132 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
133 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.UsesNode;
136 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
137 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
138 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
139 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
140 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
141 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
142 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
143 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
144 import org.slf4j.Logger;
145 import org.slf4j.LoggerFactory;
147 abstract class AbstractTypeGenerator {
148 private enum InheritedGetter {
150 * There is no matching method present.
154 * There is a matching method and its return type is resolved.
158 * There is a matching method and its return type is unresolved -- i.e. in case of a leafref pointing to outside
159 * of its parent grouping.
164 * We are using {@code @Override} annotation to indicate specialization, hence we can differentiate between
165 * resolved and unresolved methods based on them.
167 * @param annotations Method annotations
168 * @return Either {@link #RESOLVED} or {@link #UNRESOLVED}.
170 static InheritedGetter fromAnnotations(final List<AnnotationType> annotations) {
171 for (AnnotationType annotation : annotations) {
172 if (OVERRIDE_ANNOTATION.equals(annotation.getIdentifier())) {
173 return InheritedGetter.RESOLVED;
176 return InheritedGetter.UNRESOLVED;
180 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
181 private static final Splitter COLON_SPLITTER = Splitter.on(':');
182 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
183 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
184 private static final JavaTypeName CHECK_RETURN_VALUE_ANNOTATION =
185 // Do not refer to annotation class, as it may not be available at runtime
186 JavaTypeName.create("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
187 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
190 * Comparator based on augment target path.
192 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
193 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
194 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
196 while (thisIt.hasNext()) {
197 if (!otherIt.hasNext()) {
201 final int comp = thisIt.next().compareTo(otherIt.next());
207 return otherIt.hasNext() ? -1 : 0;
211 * Constant with the concrete name of identifier.
213 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
216 * Constant with the concrete name of namespace.
218 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
220 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
223 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
224 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
225 * for schema node specified in key part.
227 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
230 * Provide methods for converting YANG types to JAVA types.
232 private final AbstractTypeProvider typeProvider;
235 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
237 private final @NonNull EffectiveModelContext schemaContext;
240 * Holds renamed elements.
242 private final Map<SchemaNode, JavaTypeName> renames;
244 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
245 final Map<SchemaNode, JavaTypeName> renames) {
246 this.schemaContext = requireNonNull(context);
247 this.typeProvider = requireNonNull(typeProvider);
248 this.renames = requireNonNull(renames);
250 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
251 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
252 for (final Module contextModule : contextModules) {
253 contexts.add(moduleToGenTypes(contextModule));
256 contexts.forEach(this::allAugmentsToGenTypes);
259 final @NonNull EffectiveModelContext schemaContext() {
260 return schemaContext;
263 final Collection<ModuleContext> moduleContexts() {
264 return genCtx.values();
267 final ModuleContext moduleContext(final QNameModule module) {
268 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
271 final AbstractTypeProvider typeProvider() {
275 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
277 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
279 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
280 Collection<? extends SchemaNode> nodes);
282 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
284 abstract void addRpcMethodComment(TypeMemberBuilder<?> genType, RpcDefinition node);
286 private ModuleContext moduleToGenTypes(final Module module) {
287 final ModuleContext context = new ModuleContext(module);
288 genCtx.put(module.getQNameModule(), context);
289 allTypeDefinitionsToGenTypes(context);
290 groupingsToGenTypes(context, module.getGroupings());
291 allIdentitiesToGenTypes(context);
293 if (!module.getChildNodes().isEmpty()) {
294 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
295 context.addModuleNode(moduleType);
296 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
299 // Resolve RPCs and notifications only after we have created instantiated tree
300 rpcMethodsToGenType(context);
301 notificationsToGenType(context);
306 * Converts all extended type definitions of module to the list of
307 * <code>Type</code> objects.
310 * module from which is obtained set of type definitions
311 * @throws IllegalArgumentException
313 * <li>if module is null</li>
314 * <li>if name of module is null</li>
316 * @throws IllegalStateException
317 * if set of type definitions from module is null
319 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
320 final Module module = context.module();
321 checkArgument(module.getName() != null, "Module name cannot be NULL.");
323 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
324 if (typedef != null) {
325 final GeneratedType type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
327 context.addTypedefType(typedef, type);
328 context.addTypeToSchema(type,typedef);
334 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
335 final DataSchemaNode node, final boolean inGrouping) {
336 if (node.isAugmenting() || node.isAddedByUses()) {
339 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
340 addConcreteInterfaceMethods(genType);
341 annotateDeprecatedIfNecessary(node, genType);
343 final Module module = context.module();
344 genType.setModuleName(module.getName());
345 addCodegenInformation(genType, module, node);
346 genType.setSchemaPath(node.getPath());
347 if (node instanceof DataNodeContainer) {
348 context.addChildNodeType(node, genType);
349 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
350 processUsesAugments((DataNodeContainer) node, context, inGrouping);
355 private Type containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
356 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
357 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
358 if (genType != null) {
359 constructGetter(parent, genType, node);
360 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
361 actionsToGenType(context, genType, node, null, inGrouping);
362 notificationsToGenType(context, genType, node, null, inGrouping);
367 private GeneratedTypeBuilder listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
368 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
369 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
370 if (genType != null) {
371 final List<String> listKeys = listKeys(node);
372 final GeneratedTOBuilder keyTypeBuilder;
373 if (!listKeys.isEmpty()) {
374 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
375 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
376 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
377 .addImplementsType(identifier(genType));
378 genType.addImplementsType(identifiable(keyTypeBuilder));
380 keyTypeBuilder = null;
383 // Decide whether to generate a List or a Map
384 final ParameterizedType listType;
385 if (keyTypeBuilder != null && !node.isUserOrdered()) {
386 listType = mapTypeFor(keyTypeBuilder, genType);
388 listType = listTypeFor(genType);
391 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
392 constructNonnull(parent, listType, node);
394 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
395 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
397 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
398 if (!schemaNode.isAugmenting()) {
399 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
404 if (keyTypeBuilder != null) {
405 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
406 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
407 keyTypeBuilder.setSUID(prop);
410 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
415 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
416 final boolean inGrouping) {
417 for (final UsesNode usesNode : node.getUses()) {
418 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
419 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
420 processUsesAugments(augment, context, inGrouping);
426 * Converts all <b>augmentation</b> of the module to the list
427 * <code>Type</code> objects.
430 * module from which is obtained list of all augmentation objects
431 * to iterate over them
432 * @throws IllegalArgumentException
434 * <li>if the module is null</li>
435 * <li>if the name of module is null</li>
437 * @throws IllegalStateException
438 * if set of augmentations from module is null
440 private void allAugmentsToGenTypes(final ModuleContext context) {
441 final Module module = context.module();
442 checkArgument(module != null, "Module reference cannot be NULL.");
443 checkArgument(module.getName() != null, "Module name cannot be NULL.");
444 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
446 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
447 augmentationToGenTypes(context, augment);
452 * Returns list of <code>AugmentationSchema</code> objects. The objects are
453 * sorted according to the length of their target path from the shortest to
457 * module from which is obtained list of all augmentation objects
458 * @return list of sorted <code>AugmentationSchema</code> objects obtained
459 * from <code>module</code>
460 * @throws IllegalArgumentException
462 * @throws IllegalStateException
463 * if set of module augmentations is null
465 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
466 checkArgument(module != null, "Module reference cannot be NULL.");
467 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
469 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
470 sortedAugmentations.sort(AUGMENT_COMP);
472 return sortedAugmentations;
476 * Create GeneratedTypeBuilder object from module argument.
479 * Module object from which builder will be created
480 * @return <code>GeneratedTypeBuilder</code> which is internal
481 * representation of the module
482 * @throws IllegalArgumentException
485 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
486 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, BindingMapping.DATA_ROOT_SUFFIX);
487 final Module module = context.module();
488 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
489 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
490 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
491 // top level DataRoot object
492 if (module.getUses().size() > 1) {
493 narrowImplementedInterface(moduleDataTypeBuilder);
496 addCodegenInformation(moduleDataTypeBuilder, module);
497 return moduleDataTypeBuilder;
500 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
501 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
502 for (final ActionDefinition action : parentSchema.getActions()) {
503 if (action.isAugmenting()) {
507 final GeneratedType input;
508 final GeneratedType output;
509 if (action.isAddedByUses()) {
510 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
511 // Original definition may live in a different module, make sure we account for that
512 final ModuleContext origContext = moduleContext(
513 orig.getPath().getPathFromRoot().iterator().next().getModule());
514 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
515 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
517 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
518 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
521 if (!(parentSchema instanceof GroupingDefinition)) {
522 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
523 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
524 // and do not capture an actual instantiation.
525 final QName qname = action.getQName();
526 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
527 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
528 BindingMapping.getClassName(qname)));
529 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
531 annotateDeprecatedIfNecessary(action, builder);
532 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
533 : action(parent, input, output));
535 addCodegenInformation(builder, context.module(), action);
536 context.addChildNodeType(action, builder);
541 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
542 final QName qname = action.getQName();
543 for (UsesNode uses : parent.getUses()) {
544 final GroupingDefinition grp = uses.getSourceGrouping();
545 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
547 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
548 if (found.isPresent()) {
549 final ActionDefinition result = found.get();
550 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
554 return Optional.empty();
557 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
558 final ContainerLike schema, final boolean inGrouping) {
559 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
560 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
561 return genType.build();
565 * Converts all <b>RPCs</b> input and output substatements of the module
566 * to the list of <code>Type</code> objects. In addition are to containers
567 * and lists which belong to input or output also part of returning list.
570 * module from which is obtained set of all rpc objects to
572 * @throws IllegalArgumentException
574 * <li>if the module is null</li>
575 * <li>if the name of module is null</li>
577 * @throws IllegalStateException
578 * if set of rpcs from module is null
580 private void rpcMethodsToGenType(final ModuleContext context) {
581 final Module module = context.module();
582 checkArgument(module.getName() != null, "Module name cannot be NULL.");
583 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
584 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
585 if (rpcDefinitions.isEmpty()) {
589 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, BindingMapping.RPC_SERVICE_SUFFIX);
590 interfaceBuilder.addImplementsType(RPC_SERVICE);
592 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
594 for (final RpcDefinition rpc : rpcDefinitions) {
596 final String rpcName = BindingMapping.getClassName(rpc.getQName());
597 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
598 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
600 // Do not refer to annotation class, as it may not be available at runtime
601 method.addAnnotation(CHECK_RETURN_VALUE_ANNOTATION);
602 addRpcMethodComment(method, rpc);
604 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
605 method.setReturnType(listenableFutureTypeFor(
606 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
610 context.addTopLevelNodeType(interfaceBuilder);
613 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
614 final ContainerLike schema, final Type type) {
615 processUsesAugments(schema, context, false);
616 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
617 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
619 addImplementedInterfaceFromUses(schema, outType);
620 outType.addImplementsType(type);
621 outType.addImplementsType(augmentable(outType));
622 addConcreteInterfaceMethods(outType);
623 annotateDeprecatedIfNecessary(rpc, outType);
624 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
625 context.addChildNodeType(schema, outType);
626 return outType.build();
630 * Converts all <b>notifications</b> of the module to the list of
631 * <code>Type</code> objects. In addition are to this list added containers
632 * and lists which are part of this notification.
635 * module from which is obtained set of all notification objects
636 * to iterate over them
637 * @throws IllegalArgumentException
639 * <li>if the module equals null</li>
640 * <li>if the name of module equals null</li>
642 * @throws IllegalStateException
643 * if set of notifications from module is null
645 private void notificationsToGenType(final ModuleContext context) {
646 final Module module = context.module();
647 checkArgument(module.getName() != null, "Module name cannot be NULL.");
648 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
649 if (notifications.isEmpty()) {
653 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context,
654 BindingMapping.NOTIFICATION_LISTENER_SUFFIX);
655 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
657 for (final NotificationDefinition notification : notifications) {
658 if (notification != null) {
659 processUsesAugments(notification, context, false);
661 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
662 context.modulePackageName(), notification, DATA_OBJECT, context);
663 addConcreteInterfaceMethods(notificationInterface);
664 annotateDeprecatedIfNecessary(notification, notificationInterface);
665 notificationInterface.addImplementsType(NOTIFICATION);
666 context.addChildNodeType(notification, notificationInterface);
668 // Notification object
669 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
670 notification.getChildNodes(), false);
672 final MethodSignatureBuilder notificationMethod =
673 listenerInterface.addMethod("on" + notificationInterface.getName())
674 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
675 .setReturnType(primitiveVoidType());
677 annotateDeprecatedIfNecessary(notification, notificationMethod);
678 if (notification.getStatus().equals(Status.OBSOLETE)) {
679 notificationMethod.setDefault(true);
681 addComment(notificationMethod, notification);
685 addCodegenInformation(listenerInterface, module, "notifications", notifications);
686 context.addTopLevelNodeType(listenerInterface);
689 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
690 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
691 final boolean inGrouping) {
692 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
693 if (notifications.isEmpty()) {
697 for (NotificationDefinition notif : notifications) {
698 if (notif.isAugmenting()) {
701 if (parentSchema instanceof GroupingDefinition) {
702 // Notifications cannot be really established, as they lack instantiation context, which would be
703 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
707 processUsesAugments(notif, context, false);
709 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
710 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
711 addConcreteInterfaceMethods(notifInterface);
712 annotateDeprecatedIfNecessary(notif, notifInterface);
714 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
715 : instanceNotification(notifInterface, parent));
716 context.addChildNodeType(notif, notifInterface);
718 // Notification object
719 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
724 * Converts all <b>identities</b> of the module to the list of
725 * <code>Type</code> objects.
728 * module from which is obtained set of all identity objects to
730 * @param schemaContext
731 * schema context only used as input parameter for method
732 * {@link BindingGeneratorImpl#identityToGenType}
735 private void allIdentitiesToGenTypes(final ModuleContext context) {
736 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
738 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
739 for (final IdentitySchemaNode identity : schemaIdentities) {
740 identityToGenType(context, identity);
746 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
747 * created transport object builder. If identity contains base identity then
748 * reference to base identity is added to superior identity as its extend.
749 * If identity doesn't contain base identity then only reference to abstract
750 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
751 * BaseIdentity} is added
755 * @param basePackageName
756 * string contains the module package name
758 * IdentitySchemaNode which contains data about identity
760 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
761 if (identity == null) {
765 JavaTypeName name = renames.get(identity);
767 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
768 BindingMapping.getClassName(identity.getQName()));
771 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
772 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
773 if (!baseIdentities.isEmpty()) {
774 for (IdentitySchemaNode baseIdentity : baseIdentities) {
775 JavaTypeName base = renames.get(baseIdentity);
777 final QName qname = baseIdentity.getQName();
778 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
779 BindingMapping.getClassName(qname));
782 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
783 newType.addImplementsType(gto);
786 newType.addImplementsType(BASE_IDENTITY);
789 final Module module = context.module();
790 addCodegenInformation(newType, module, identity);
791 newType.setModuleName(module.getName());
792 newType.setSchemaPath(identity.getPath());
794 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
796 context.addIdentityType(identity, newType);
799 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
800 final JavaTypeName yangModuleInfo, final String localName) {
801 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
802 new SimpleImmutableEntry<>(yangModuleInfo, localName));
806 * Converts all <b>groupings</b> of the module to the list of
807 * <code>Type</code> objects. Firstly are groupings sorted according mutual
808 * dependencies. At least dependent (independent) groupings are in the list
809 * saved at first positions. For every grouping the record is added to map
810 * {@link ModuleContext#groupings allGroupings}
815 * collection of groupings from which types will be generated
818 private void groupingsToGenTypes(final ModuleContext context,
819 final Collection<? extends GroupingDefinition> groupings) {
820 for (final GroupingDefinition grouping : GroupingDefinitionDependencySort.sort(groupings)) {
821 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
822 // node of grouping is resolved to the method.
823 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
824 narrowImplementedInterface(genType);
825 annotateDeprecatedIfNecessary(grouping, genType);
826 context.addGroupingType(grouping, genType);
827 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
828 groupingsToGenTypes(context, grouping.getGroupings());
829 processUsesAugments(grouping, context, true);
830 actionsToGenType(context, genType, grouping, null, true);
831 notificationsToGenType(context, genType, grouping, null, true);
836 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
837 * <code>enumTypeDef</code> item is added to builder with its name and value.
839 * @param enumTypeDef EnumTypeDefinition contains enum data
840 * @param enumName string contains name which will be assigned to enumeration builder
841 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
842 * @param module Module in which type should be generated
843 * @return enumeration builder which contains data from <code>enumTypeDef</code>
845 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
846 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
847 final EnumBuilder enumBuilder = typeProvider.newEnumerationBuilder(typeBuilder.getIdentifier()
848 .createEnclosed(BindingMapping.getClassName(enumName), "$"));
849 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
850 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
851 final Enumeration ret = enumBuilder.toInstance();
852 typeBuilder.addEnumeration(ret);
854 context.addTypeToSchema(ret, enumTypeDef);
855 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
860 * Generates type builder for <code>module</code>.
862 * @param module Module which is source of package name for generated type builder
863 * @param postfix string which is added to the module class name representation as suffix
864 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
865 * @throws IllegalArgumentException if <code>module</code> is null
867 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
868 final Module module = context.module();
869 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
870 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
871 JavaTypeName.create(context.modulePackageName(), moduleName));
873 moduleBuilder.setModuleName(moduleName);
874 addCodegenInformation(moduleBuilder, module);
875 return moduleBuilder;
879 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
880 * In addition there are also generated types for all containers, list and choices which are child of
881 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
883 * @param augmentPackageName string with the name of the package to which the augmentation belongs
884 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
885 * @param module current module
886 * @throws IllegalArgumentException
888 * <li>if <code>augmentPackageName</code> equals null</li>
889 * <li>if <code>augSchema</code> equals null</li>
891 * @throws IllegalStateException
892 * if augment target path is null
894 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
895 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
896 checkState(augSchema.getTargetPath() != null,
897 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
899 processUsesAugments(augSchema, context, false);
900 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
901 SchemaNode targetSchemaNode = null;
903 // FIXME: can we use findDataSchemaNode() instead?
904 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
905 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
906 if (targetSchemaNode instanceof DerivableSchemaNode) {
907 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
909 if (targetSchemaNode == null) {
910 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
911 + " in module " + context.module().getName());
914 if (targetSchemaNode == null) {
915 throw new IllegalArgumentException("augment target not found: " + targetPath);
918 if (targetSchemaNode instanceof ChoiceSchemaNode) {
919 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
920 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
921 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
922 augSchema.getChildNodes(), null, false);
926 final JavaTypeName targetName;
927 if (targetSchemaNode instanceof CaseSchemaNode) {
928 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
929 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
930 targetName = builder.getIdentifier();
932 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
933 if (builder == null) {
934 targetName = findAliasByPath(targetSchemaNode.getPath());
935 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
937 targetName = builder.getIdentifier();
941 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
944 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
945 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
946 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
947 checkState(augSchema.getTargetPath() != null,
948 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
950 processUsesAugments(augSchema, context, inGrouping);
951 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
952 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
953 if (targetSchemaNode == null) {
954 throw new IllegalArgumentException("augment target not found: " + targetPath);
957 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
958 if (targetTypeBuilder == null) {
959 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
961 if (targetTypeBuilder == null) {
962 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
965 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
966 if (usesNodeParent instanceof SchemaNode) {
967 addRawAugmentGenTypeDefinition(context,
968 packageNameForAugmentedGeneratedType(context.modulePackageName(),
969 ((SchemaNode) usesNodeParent).getPath()),
970 targetTypeBuilder.build(), augSchema, inGrouping);
972 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
975 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
976 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
981 * Convenient method to find node added by uses statement.
983 * @param targetPath node path
984 * @param parentUsesNode parent of uses node
985 * @return node from its original location in grouping
987 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
988 final UsesNode parentUsesNode) {
989 SchemaNode result = parentUsesNode.getSourceGrouping();
990 for (final QName node : targetPath.getNodeIdentifiers()) {
991 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
992 if (result instanceof DataNodeContainer) {
993 final QName resultNode = node.bindTo(result.getQName().getModule());
995 SchemaNode found = ((DataNodeContainer) result).dataChildByName(resultNode);
997 if (result instanceof ActionNodeContainer) {
998 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
1000 if (found == null && result instanceof NotificationNodeContainer) {
1001 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
1005 } else if (result instanceof ChoiceSchemaNode) {
1006 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
1007 } else if (result instanceof ActionDefinition) {
1008 final ActionDefinition action = (ActionDefinition) result;
1009 final QName resultNode = node.bindTo(result.getQName().getModule());
1011 final InputSchemaNode input = action.getInput();
1012 final OutputSchemaNode output = action.getOutput();
1013 if (resultNode.equals(input.getQName())) {
1015 } else if (resultNode.equals(output.getQName())) {
1020 } else if (result != null) {
1021 throw new IllegalStateException("Cannot handle " + result);
1024 if (result == null) {
1028 if (result instanceof DerivableSchemaNode) {
1029 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
1030 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
1031 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
1032 result = originalNode.get();
1036 if (result instanceof DataSchemaNode) {
1037 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
1038 if (resultDataSchemaNode.isAddedByUses()) {
1039 // The original node is required, but we have only the copy of
1040 // the original node.
1041 // Maybe this indicates a bug in Yang parser.
1042 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
1045 return resultDataSchemaNode;
1048 throw new IllegalStateException(
1049 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
1054 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
1055 * of augmented node with serial number as suffix.
1057 * @param context current module
1058 * @param augmentPackageName string with contains the package name to which the augment belongs
1059 * @param basePackageName string with the package name to which the augmented node belongs
1060 * @param targetTypeRef target type
1061 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1062 * @return generated type builder for augment
1064 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1065 final String augmentPackageName, final Type targetTypeRef,
1066 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1067 Map<String, GeneratedTypeBuilder> augmentBuilders =
1068 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1069 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1072 if (augIdentifier != null) {
1073 augTypeName = BindingMapping.getClassName(augIdentifier);
1075 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1078 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1079 JavaTypeName.create(augmentPackageName, augTypeName));
1081 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1082 addConcreteInterfaceMethods(augTypeBuilder);
1084 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1085 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1087 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1088 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1089 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1091 augmentBuilders.put(augTypeName, augTypeBuilder);
1093 if (!augSchema.getChildNodes().isEmpty()) {
1094 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1097 context.addAugmentType(augTypeBuilder);
1098 return augTypeBuilder;
1101 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1102 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1103 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1107 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1108 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1109 final QName nodeType = unknownSchemaNode.getNodeType();
1110 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1111 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1112 return unknownSchemaNode.getNodeParameter();
1119 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1120 * consists from name of augmented node and serial number of its augmentation.
1122 * @param builders map of builders which were created in the package to which the augmentation belongs
1123 * @param genTypeName string with name of augmented node
1124 * @return string with unique name for augmentation builder
1126 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1128 if (builders != null) {
1129 while (builders.containsKey(genTypeName + index)) {
1133 return genTypeName + index;
1137 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1138 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1139 * already part of them).
1141 * @param module current module
1142 * @param parent generated type builder which represents any node. The subnodes of this node are added
1143 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1144 * container, choice.
1145 * @param childOf parent type
1146 * @param schemaNodes set of data schema nodes which are the children of the node for which
1147 * <code>typeBuilder</code> was created
1148 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1149 * child nodes) could be added to it.
1151 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1152 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1153 final boolean inGrouping) {
1154 if (schemaNodes != null && parent != null) {
1155 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1156 for (final DataSchemaNode schemaNode : schemaNodes) {
1157 if (!schemaNode.isAugmenting()) {
1158 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1165 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode schemaNode,
1166 final GeneratedTypeBuilder parent, final Type baseInterface, final boolean inGrouping) {
1167 if (!schemaNode.isAddedByUses()) {
1168 addUnambiguousNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1169 } else if (needGroupingMethodOverride(schemaNode, parent)) {
1170 addLeafrefNodeToBuilderAsMethod(context, (TypedDataSchemaNode) schemaNode, parent, inGrouping);
1175 * Determine whether a particular node, added from a grouping, needs to be reflected as a method. This method
1176 * performs a check for {@link TypedDataSchemaNode} and defers to
1177 * {@link #needGroupingMethodOverride(TypedDataSchemaNode, GeneratedTypeBuilder)}.
1179 * @param parent {@code GeneratedType} where method should be defined
1180 * @param child node from which method should be defined
1181 * @return True if an override method is needed
1183 private static boolean needGroupingMethodOverride(final DataSchemaNode child, final GeneratedTypeBuilder parent) {
1184 return child instanceof TypedDataSchemaNode && needGroupingMethodOverride((TypedDataSchemaNode) child, parent);
1188 * Determine whether a particular {@link TypedDataSchemaNode}, added from a grouping, needs to be reflected as a
1192 * This check would be super easy were it not for relative leafrefs in groupings. These can legally point outside of
1193 * the grouping -- which means we cannot inherently cannot determine their type, as they are polymorphic.
1195 * @param parent {@code GeneratedType} where method should be defined
1196 * @param child node from which method should be defined
1197 * @return True if an override method is needed
1199 private static boolean needGroupingMethodOverride(final TypedDataSchemaNode child,
1200 final GeneratedTypeBuilder parent) {
1201 // This is a child added through uses and it is is data-bearing, i.e. leaf or leaf-list. Under normal
1202 // circumstances we would not bother, but if the target type is a leafref we have more checks to do.
1203 return isRelativeLeafref(child.getType()) && needMethodDefinition(child.getQName().getLocalName(), parent);
1206 private static boolean needMethodDefinition(final String localName, final GeneratedTypeBuilder parent) {
1207 for (Type implementsType : parent.getImplementsTypes()) {
1208 if (implementsType instanceof GeneratedType) {
1209 final InheritedGetter precision = findInheritedGetter(localName, (GeneratedType) implementsType);
1210 switch (precision) {
1220 throw new IllegalStateException(localName + " should be present in " + parent
1221 + " or in one of its ancestors as a getter");
1224 private static InheritedGetter findInheritedGetter(final String localName, final GeneratedType impl) {
1225 return findInheritedGetter(impl, BindingMapping.getGetterMethodName(localName));
1228 private static InheritedGetter findInheritedGetter(final GeneratedType type, final String getter) {
1229 for (MethodSignature method : type.getMethodDefinitions()) {
1230 if (getter.equals(method.getName())) {
1231 return InheritedGetter.fromAnnotations(method.getAnnotations());
1235 // Try to find the method in other interfaces we implement
1236 for (Type implementsType : type.getImplements()) {
1237 if (implementsType instanceof GeneratedType) {
1238 final InheritedGetter found = findInheritedGetter((GeneratedType) implementsType, getter);
1239 if (found != InheritedGetter.NOT_PRESENT) {
1244 return InheritedGetter.NOT_PRESENT;
1247 private static boolean isRelativeLeafref(final TypeDefinition<? extends TypeDefinition<?>> type) {
1248 return type instanceof LeafrefTypeDefinition && !((LeafrefTypeDefinition) type).getPathStatement().isAbsolute();
1252 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1255 * @param module current module
1256 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1257 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1258 * container, choice.
1259 * @param childOf parent type
1260 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1262 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1263 * The getter method could be added to it.
1265 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1266 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1267 final boolean inGrouping) {
1268 if (schemaNodes != null && typeBuilder != null) {
1269 final Type baseInterface = childOf(typeBuilder);
1270 for (final DataSchemaNode schemaNode : schemaNodes) {
1271 if (!schemaNode.isAugmenting()) {
1272 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1280 * Adds to {@code typeBuilder} a method which is derived from {@code schemaNode}.
1282 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1283 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1284 * @param childOf parent type
1285 * @param module current module
1287 private void addLeafrefNodeToBuilderAsMethod(final ModuleContext context, final TypedDataSchemaNode node,
1288 final GeneratedTypeBuilder typeBuilder, final boolean inGrouping) {
1289 if (node != null && typeBuilder != null) {
1290 if (node instanceof LeafSchemaNode) {
1291 resolveLeafLeafrefNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1292 } else if (node instanceof LeafListSchemaNode) {
1293 resolveLeafListLeafrefNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1295 logUnableToAddNodeAsMethod(node, typeBuilder);
1300 private void addUnambiguousNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1301 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1302 if (node instanceof LeafSchemaNode) {
1303 resolveUnambiguousLeafNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1304 } else if (node instanceof LeafListSchemaNode) {
1305 resolveUnambiguousLeafListNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1306 } else if (node instanceof ContainerSchemaNode) {
1307 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1308 } else if (node instanceof ListSchemaNode) {
1309 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1310 } else if (node instanceof ChoiceSchemaNode) {
1311 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1312 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1313 opaqueToGeneratedType(context, typeBuilder, node);
1315 logUnableToAddNodeAsMethod(node, typeBuilder);
1319 private static void logUnableToAddNodeAsMethod(final DataSchemaNode node, final GeneratedTypeBuilder typeBuilder) {
1320 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1321 typeBuilder.getFullyQualifiedName());
1325 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1326 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1327 * and names of all parents node.
1329 * @param context current module
1330 * @param basePackageName string with the module package name
1331 * @param parent parent type
1332 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1334 * @throws IllegalArgumentException
1336 * <li>if <code>basePackageName</code> is null</li>
1337 * <li>if <code>choiceNode</code> is null</li>
1340 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1341 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1342 if (!choiceNode.isAddedByUses()) {
1343 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1344 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1345 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1346 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1347 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1348 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1350 final GeneratedType choiceType = choiceTypeBuilder.build();
1351 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1353 constructGetter(parent, choiceType, choiceNode);
1357 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1358 final DataSchemaNode anyNode) {
1359 if (!anyNode.isAddedByUses()) {
1360 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1361 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1362 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1363 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1364 defaultImplementedInterace(anyxmlTypeBuilder);
1365 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1366 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1368 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1373 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1374 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1375 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1376 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1378 * @param context current module context
1379 * @param refChoiceType type which represents superior <i>case</i>
1380 * @param choiceNode choice case node which is mapped to generated type
1381 * @throws IllegalArgumentException
1383 * <li>if <code>refChoiceType</code> equals null</li>
1384 * <li>if <code>caseNodes</code> equals null</li>
1387 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1388 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1389 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1390 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1392 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1393 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1394 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1395 caseTypeBuilder.addImplementsType(refChoiceType);
1396 addConcreteInterfaceMethods(caseTypeBuilder);
1397 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1398 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1399 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1400 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1401 if (caseChildNodes != null) {
1402 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1404 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1405 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1407 if (parent instanceof AugmentationSchemaNode) {
1408 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1409 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1410 // FIXME: can we use findDataSchemaNode?
1411 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1412 targetPath.getNodeIdentifiers());
1413 if (targetSchemaNode instanceof DataSchemaNode
1414 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1415 if (targetSchemaNode instanceof DerivableSchemaNode) {
1416 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1419 if (targetSchemaNode == null) {
1420 throw new IllegalStateException(
1421 "Failed to find target node from grouping for augmentation " + augSchema
1422 + " in module " + context.module().getName());
1425 parent = targetSchemaNode;
1428 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1429 Type childOfType = findChildNodeByPath(parent.getPath());
1430 if (childOfType == null) {
1431 childOfType = findGroupingByPath(parent.getPath());
1433 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1435 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1440 processUsesAugments(caseNode, context, inGrouping);
1445 * Generates list of generated types for all the cases of a choice which are added to the choice through
1448 * @param module current module
1449 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1450 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1451 * of the augmenting choice will belong to pcg2.
1452 * @param targetType Type which represents target choice
1453 * @param targetNode node which represents target choice
1454 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1456 * @throws IllegalArgumentException
1458 * <li>if <code>basePackageName</code> is null</li>
1459 * <li>if <code>targetType</code> is null</li>
1460 * <li>if <code>augmentedNodes</code> is null</li>
1463 // FIXME: nullness rules need to untangled in this method
1464 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1465 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1466 final Type targetType, final ChoiceSchemaNode targetNode,
1467 final Iterable<? extends DataSchemaNode> augmentedNodes,
1468 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1469 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1470 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1472 for (final DataSchemaNode caseNode : augmentedNodes) {
1473 if (caseNode != null) {
1474 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1475 caseTypeBuilder.addImplementsType(targetType);
1476 addConcreteInterfaceMethods(caseTypeBuilder);
1478 CaseSchemaNode node = null;
1479 final String caseLocalName = caseNode.getQName().getLocalName();
1480 if (caseNode instanceof CaseSchemaNode) {
1481 node = (CaseSchemaNode) caseNode;
1482 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1483 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1484 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1485 if (dataSchemaNode instanceof ChoiceSchemaNode
1486 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1487 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1492 node = findNamedCase(targetNode, caseLocalName);
1494 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1495 if (childNodes != null) {
1496 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1499 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1500 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1505 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1506 final SchemaPath nodePath = targetNode.getPath();
1507 final SchemaPath parentSp = nodePath.getParent();
1508 if (parentSp.getParent() == null) {
1509 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1512 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1513 GeneratedTypeBuilder childOfType = null;
1514 if (parent instanceof CaseSchemaNode) {
1515 childOfType = findCaseByPath(parent.getPath());
1516 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1517 childOfType = findChildNodeByPath(parent.getPath());
1518 } else if (parent instanceof GroupingDefinition) {
1519 childOfType = findGroupingByPath(parent.getPath());
1522 if (childOfType == null) {
1523 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1529 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1530 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1531 return cases.isEmpty() ? null : cases.get(0);
1534 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1535 // New parser with encapsulated type
1536 if (leaf.getPath().equals(type.getPath())) {
1540 // Embedded type definition with new parser. Also takes care of the old parser with bits
1541 if (leaf.getPath().equals(type.getPath().getParent())) {
1548 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1549 final List<PatternConstraint> patternConstraints) {
1550 if (!patternConstraints.isEmpty()) {
1551 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1552 .append(BindingMapping.getPropertyName(leafName));
1553 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1554 typeProvider.resolveRegExpressions(patternConstraints));
1558 private Type resolveLeafLeafrefNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1559 final ModuleContext context, final boolean inGrouping) {
1560 final Module parentModule = findParentModule(schemaContext, leaf);
1561 final Type returnType = resolveReturnType(typeBuilder, leaf, context, parentModule, inGrouping);
1562 if (returnType != null && isTypeSpecified(returnType)) {
1563 processContextRefExtension(leaf, constructOverrideGetter(typeBuilder, returnType, leaf), parentModule);
1569 * Converts {@code leafList} to the getter method which is added to {@code typeBuilder}.
1571 * @param context module in which type was defined
1572 * @param typeBuilder generated type builder to which is added getter method as {@code leafList} mapping
1573 * @param leafList leaf-list schema node which is mapped as getter method which is added to {@code typeBuilder}
1575 private void resolveLeafListNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode leafList,
1576 final ModuleContext context, final boolean inGrouping) {
1577 if (!leafList.isAddedByUses()) {
1578 resolveUnambiguousLeafListNode(typeBuilder, leafList, context, inGrouping);
1579 } else if (needGroupingMethodOverride(leafList, typeBuilder)) {
1580 resolveLeafListLeafrefNode(typeBuilder, leafList, context, inGrouping);
1584 private Type resolveUnambiguousLeafNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1585 final ModuleContext context, final boolean inGrouping) {
1586 final Module parentModule = findParentModule(schemaContext, leaf);
1587 final Type returnType = resolveReturnType(typeBuilder, leaf, context, parentModule, inGrouping);
1588 if (returnType != null) {
1589 processContextRefExtension(leaf, constructGetter(typeBuilder, returnType, leaf), parentModule);
1594 private Type resolveReturnType(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1595 final ModuleContext context, final Module parentModule, final boolean inGrouping) {
1596 Type returnType = null;
1598 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1599 if (isInnerType(leaf, typeDef)) {
1600 if (typeDef instanceof EnumTypeDefinition) {
1601 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1602 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1603 typeProvider.putReferencedType(leaf.getPath(), returnType);
1604 } else if (typeDef instanceof UnionTypeDefinition) {
1605 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1606 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1607 // Store the inner type within the union so that we can find the reference for it
1608 context.addInnerTypedefType(typeDef.getPath(), returnType);
1609 } else if (typeDef instanceof BitsTypeDefinition) {
1610 returnType = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf, parentModule);
1612 // It is constrained version of already declared type (inner declared type exists, only for special
1613 // cases (Enum, Union, Bits), which were already checked.
1614 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1616 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1617 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1618 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1619 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1620 final SchemaNode leafrefTarget =
1621 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1622 if (leafrefTarget instanceof TypedDataSchemaNode) {
1623 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1626 if (returnType == null) {
1627 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1628 restrictions, inGrouping);
1631 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1634 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1635 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1636 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1639 if (returnType == null) {
1643 if (typeDef instanceof EnumTypeDefinition) {
1644 typeProvider.putReferencedType(leaf.getPath(), returnType);
1650 private static boolean isTypeSpecified(final Type type) {
1651 return !type.equals(objectType());
1654 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1655 // Returns DerivedType in case of new parser.
1656 final TypeDefinition<?> baseType = typeDef.getBaseType();
1657 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1660 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1661 final Module module) {
1662 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1663 final QName nodeType = node.getNodeType();
1664 if ("context-reference".equals(nodeType.getLocalName())) {
1665 final String nodeParam = node.getNodeParameter();
1666 IdentitySchemaNode identity = null;
1667 String basePackageName = null;
1668 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1669 final Iterator<String> iterator = splittedElement.iterator();
1670 final int length = Iterables.size(splittedElement);
1672 identity = findIdentityByName(module.getIdentities(), iterator.next());
1673 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1674 } else if (length == 2) {
1675 final String prefix = iterator.next();
1676 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1677 if (dependentModule == null) {
1678 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1681 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1682 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1684 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1687 if (identity == null) {
1688 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1692 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1693 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1694 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1695 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1700 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1701 final String name) {
1702 for (final IdentitySchemaNode id : identities) {
1703 if (id.getQName().getLocalName().equals(name)) {
1710 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1711 for (final ModuleImport imp : imports) {
1712 if (imp.getPrefix().equals(prefix)) {
1713 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1719 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1720 final boolean isReadOnly) {
1721 if (leaf != null && toBuilder != null) {
1723 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1724 if (typeDef instanceof UnionTypeDefinition) {
1725 // GeneratedType for this type definition should have be already created
1726 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1727 returnType = mc.getTypedefs().get(typeDef.getPath());
1728 if (returnType == null) {
1729 // This may still be an inner type, try to find it
1730 returnType = mc.getInnerType(typeDef.getPath());
1732 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1733 // Annonymous enumeration (already generated, since it is inherited via uses).
1734 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1735 QName qname = originalLeaf.getQName();
1736 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1738 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1740 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1746 * Converts <code>leaf</code> schema node to property of generated TO builder.
1748 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1749 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1750 * @param returnType property type
1751 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1752 * @return boolean value
1754 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1755 * name equals null or if leaf is added by <i>uses</i>.</li>
1756 * <li>true - other cases</li>
1759 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1760 final Type returnType, final boolean isReadOnly) {
1761 if (returnType == null) {
1764 final String leafName = leaf.getQName().getLocalName();
1765 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1766 propBuilder.setReadOnly(isReadOnly);
1767 propBuilder.setReturnType(returnType);
1768 addComment(propBuilder, leaf);
1770 toBuilder.addEqualsIdentity(propBuilder);
1771 toBuilder.addHashIdentity(propBuilder);
1772 toBuilder.addToStringProperty(propBuilder);
1776 private void resolveLeafListLeafrefNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1777 final ModuleContext context, final boolean inGrouping) {
1778 final Type returnType = resolveLeafListItemsType(typeBuilder, node, context, inGrouping,
1779 findParentModule(schemaContext, node));
1780 if (isTypeSpecified(returnType)) {
1781 constructOverrideGetter(typeBuilder, listTypeFor(returnType), node);
1786 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1788 * @param context module
1789 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1790 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1792 private Type resolveUnambiguousLeafListNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1793 final ModuleContext context, final boolean inGrouping) {
1794 final Module parentModule = findParentModule(schemaContext, node);
1795 final Type listItemsType = resolveLeafListItemsType(typeBuilder, node, context, inGrouping, parentModule);
1796 final Type returnType;
1797 if (listItemsType.equals(objectType())) {
1798 returnType = listTypeWildcard();
1800 returnType = listTypeFor(listItemsType);
1803 constructGetter(typeBuilder, returnType, node);
1808 private Type resolveLeafListItemsType(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1809 final ModuleContext context, final boolean inGrouping, final Module parentModule) {
1810 final Type returnType;
1811 final TypeDefinition<? extends TypeDefinition<?>> typeDef = node.getType();
1812 if (typeDef.getBaseType() == null) {
1813 if (typeDef instanceof EnumTypeDefinition) {
1814 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1815 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, node.getQName(), typeBuilder, context);
1816 typeProvider.putReferencedType(node.getPath(), returnType);
1817 } else if (typeDef instanceof UnionTypeDefinition) {
1818 final UnionTypeDefinition unionDef = (UnionTypeDefinition) typeDef;
1819 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1820 } else if (typeDef instanceof BitsTypeDefinition) {
1821 returnType = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, node, parentModule);
1823 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1824 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1825 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1828 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1829 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1830 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1835 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1836 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1837 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1838 returnTypeBuilder.setIsUnion(true);
1839 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1840 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1841 returnTypeBuilder.setModuleName(parentModule.getName());
1842 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1844 genTOBuilder.setTypedef(true);
1845 genTOBuilder.setIsUnion(true);
1846 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1848 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1852 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1853 final GeneratedTransferObject returnType, final Module parentModule) {
1854 // Append enclosing path hierarchy without dots
1855 final StringBuilder sb = new StringBuilder();
1856 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1857 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1858 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1859 unionBuilder.setIsUnionBuilder(true);
1861 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1862 method.setReturnType(returnType);
1863 method.addParameter(STRING, "defaultValue");
1864 method.setAccessModifier(AccessModifier.PUBLIC);
1865 method.setStatic(true);
1867 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1868 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1871 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1872 final SchemaNode schemaNode) {
1873 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1876 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1877 final SchemaNode schemaNode, final Type baseInterface) {
1878 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1879 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1883 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1884 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1885 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1886 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1887 * If <code>schemaNode</code> is instance of
1888 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1889 * which are specified in <i>uses</i>.
1891 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1892 * @param schemaNode schema node for which is created generated type builder
1893 * @param parent parent type (can be null)
1894 * @return generated type builder <code>schemaNode</code>
1896 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1897 final Type baseInterface, final ModuleContext context) {
1898 JavaTypeName name = renames.get(schemaNode);
1900 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1903 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1904 it.addImplementsType(baseInterface);
1905 if (!(schemaNode instanceof GroupingDefinition)) {
1906 it.addImplementsType(augmentable(it));
1908 if (schemaNode instanceof DataNodeContainer) {
1909 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1910 groupingsToGenTypes(context, containerSchema.getGroupings());
1911 addImplementedInterfaceFromUses(containerSchema, it);
1918 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1919 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1920 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1922 * @param packageName string with the package name to which returning generated type builder belongs
1923 * @param schemaNode schema node which provide data about the schema node name
1924 * @param prefix return type name prefix
1925 * @return generated type builder for <code>schemaNode</code>
1926 * @throws IllegalArgumentException
1928 * <li>if <code>schemaNode</code> is null</li>
1929 * <li>if <code>packageName</code> is null</li>
1930 * <li>if QName of schema node is null</li>
1931 * <li>if schemaNode name is null</li>
1934 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1935 final SchemaNode schemaNode) {
1936 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1937 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1938 final String schemaNodeName = schemaNode.getQName().getLocalName();
1939 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1941 // FIXME: Validation of name conflict
1942 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1943 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1945 final Module module = context.module();
1946 addCodegenInformation(newType, module, schemaNode);
1947 newType.setSchemaPath(schemaNode.getPath());
1948 newType.setModuleName(module.getName());
1950 final String packageName = identifier.packageName();
1951 final String simpleName = identifier.simpleName();
1952 if (!genTypeBuilders.containsKey(packageName)) {
1953 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1954 builders.put(simpleName, newType);
1955 genTypeBuilders.put(packageName, builders);
1957 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1958 if (!builders.containsKey(simpleName)) {
1959 builders.put(simpleName, newType);
1966 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1967 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1968 * and <code>returnType</code> information are added to the builder.
1970 * @param interfaceBuilder generated type builder for which the getter method should be created
1971 * @param returnType type which represents the return type of the getter method
1972 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1973 * @param comment string with comment for the getter method
1974 * @param status status from yang file, for deprecated annotation
1975 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1977 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1978 final SchemaNode node) {
1979 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1980 BindingMapping.getGetterMethodName(node.getQName().getLocalName()));
1981 getMethod.setReturnType(returnType);
1983 annotateDeprecatedIfNecessary(node, getMethod);
1984 addComment(getMethod, node);
1989 private MethodSignatureBuilder constructOverrideGetter(final GeneratedTypeBuilder interfaceBuilder,
1990 final Type returnType, final SchemaNode node) {
1991 final MethodSignatureBuilder getter = constructGetter(interfaceBuilder, returnType, node);
1992 getter.addAnnotation(OVERRIDE_ANNOTATION);
1996 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1997 final ListSchemaNode node) {
1998 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1999 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
2000 getMethod.setReturnType(returnType).setDefault(true);
2001 annotateDeprecatedIfNecessary(node, getMethod);
2005 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
2008 * @param basePackageName string contains the module package name
2009 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
2010 * or as a property to <code>genTOBuilder</code> if is part of the list key
2011 * @param typeBuilder generated type builder for the list schema node
2012 * @param genTOBuilder generated TO builder for the list keys
2013 * @param listKeys list of string which contains names of the list keys
2014 * @param module current module
2015 * @throws IllegalArgumentException
2017 * <li>if <code>schemaNode</code> equals null</li>
2018 * <li>if <code>typeBuilder</code> equals null</li>
2021 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
2022 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
2023 final List<String> listKeys, final boolean inGrouping) {
2024 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
2025 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
2027 if (schemaNode instanceof LeafSchemaNode) {
2028 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
2029 final String leafName = leaf.getQName().getLocalName();
2031 if (!schemaNode.isAddedByUses()) {
2032 type = resolveUnambiguousLeafNodeAsMethod(typeBuilder, leaf, context, inGrouping);
2033 } else if (needGroupingMethodOverride(leaf, typeBuilder)) {
2034 type = resolveLeafLeafrefNodeAsMethod(typeBuilder, leaf, context, inGrouping);
2039 if (listKeys.contains(leafName)) {
2041 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
2043 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
2046 } else if (schemaNode instanceof LeafListSchemaNode) {
2047 resolveLeafListNodeAsMethod(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
2048 } else if (!schemaNode.isAddedByUses()) {
2049 if (schemaNode instanceof ContainerSchemaNode) {
2050 containerToGenType(context, typeBuilder, childOf(typeBuilder), (ContainerSchemaNode) schemaNode,
2052 } else if (schemaNode instanceof ChoiceSchemaNode) {
2053 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
2054 } else if (schemaNode instanceof ListSchemaNode) {
2055 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
2056 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
2057 opaqueToGeneratedType(context, typeBuilder, schemaNode);
2062 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
2063 final GeneratedTOBuilder genTOBuilder) {
2064 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
2066 if (genTOBuilder != null) {
2067 final GeneratedTransferObject genTO = genTOBuilder.build();
2068 // Add Identifiable.getKey() for items
2069 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
2070 .addAnnotation(OVERRIDE_ANNOTATION);
2071 context.addGeneratedTOBuilder(genTOBuilder);
2076 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
2078 * @param list of string with names of the list keys
2079 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
2080 * an empty list is returned.
2082 private static List<String> listKeys(final ListSchemaNode list) {
2083 final List<QName> keyDefinition = list.getKeyDefinition();
2084 switch (keyDefinition.size()) {
2086 return Collections.emptyList();
2088 return Collections.singletonList(keyDefinition.get(0).getLocalName());
2090 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
2091 for (final QName keyDef : keyDefinition) {
2092 listKeys.add(keyDef.getLocalName());
2099 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
2100 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
2101 * enclosing transfer objects.
2103 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
2104 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
2105 * @param leaf string with name for generated TO builder
2106 * @param parentModule parent module
2107 * @return generated TO builder for <code>typeDef</code>
2109 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
2110 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2111 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
2112 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
2114 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
2115 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
2116 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
2117 genTOBuilders.forEach(builder -> typeBuilder.addEnclosingTransferObject(builder.build()));
2119 for (GeneratedTOBuilder builder : types) {
2120 final GeneratedTransferObject type = builder.build();
2121 resultTOBuilder.addEnclosingTransferObject(type);
2122 if (builder.isUnion()) {
2123 createUnionBuilder(builder, typeBuilder, type, parentModule);
2127 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
2131 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
2132 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
2133 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
2136 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
2137 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
2138 * @param leaf string with name for generated TO builder
2139 * @param parentModule parent module
2140 * @return generated TO builder for <code>typeDef</code>
2142 private GeneratedTransferObject addTOToTypeBuilder(final BitsTypeDefinition typeDef,
2143 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2144 final GeneratedTransferObject genTO = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
2145 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName())
2147 typeBuilder.addEnclosingTransferObject(genTO);
2152 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
2153 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
2154 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
2155 * to <code>builder</code>
2157 * @param dataNodeContainer element which contains the list of used YANG groupings
2158 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
2159 * @return generated type builder with all implemented types
2161 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2162 final GeneratedTypeBuilder builder) {
2163 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2164 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
2165 if (genType == null) {
2166 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
2167 + " is not resolved for " + builder.getFullyQualifiedName());
2170 builder.addImplementsType(genType.build());
2175 private JavaTypeName findAliasByPath(final SchemaPath path) {
2176 for (final ModuleContext ctx : genCtx.values()) {
2177 final JavaTypeName result = ctx.getAlias(path);
2178 if (result != null) {
2185 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2186 for (final ModuleContext ctx : genCtx.values()) {
2187 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2188 if (result != null) {
2195 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2196 for (final ModuleContext ctx : genCtx.values()) {
2197 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2198 if (result != null) {
2205 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2206 for (final ModuleContext ctx : genCtx.values()) {
2207 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2208 if (result != null) {
2215 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2216 for (final ModuleContext ctx : genCtx.values()) {
2217 final GeneratedTypeBuilder result = ctx.getCase(path);
2218 if (result != null) {
2225 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2226 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2227 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2230 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2231 switch (node.getStatus()) {
2233 // FIXME: we really want to use a pre-made annotation
2234 builder.addAnnotation(DEPRECATED_ANNOTATION);
2237 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2243 throw new IllegalStateException("Unhandled status in " + node);
2247 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2248 defaultImplementedInterace(typeBuilder);
2250 typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2251 .setAccessModifier(AccessModifier.PUBLIC)
2253 .setReturnType(primitiveIntType());
2254 typeBuilder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
2255 .setAccessModifier(AccessModifier.PUBLIC)
2257 .setReturnType(primitiveBooleanType());
2258 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2259 .setAccessModifier(AccessModifier.PUBLIC)
2261 .setReturnType(STRING);
2264 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2265 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2268 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2269 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2272 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2273 final Type classType) {
2274 final MethodSignatureBuilder ret = typeBuilder
2275 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2276 .setAccessModifier(AccessModifier.PUBLIC)
2277 .setReturnType(classType(classType));
2278 ret.addAnnotation(OVERRIDE_ANNOTATION);