2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
34 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
35 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
36 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
38 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
39 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
40 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
42 import com.google.common.base.Splitter;
43 import com.google.common.collect.Iterables;
44 import com.google.common.collect.Sets;
45 import java.util.AbstractMap.SimpleImmutableEntry;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Optional;
55 import org.eclipse.jdt.annotation.Nullable;
56 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
57 import org.opendaylight.mdsal.binding.model.api.Constant;
58 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
60 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
61 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
62 import org.opendaylight.mdsal.binding.model.api.Restrictions;
63 import org.opendaylight.mdsal.binding.model.api.Type;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
73 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
74 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
75 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
76 import org.opendaylight.mdsal.binding.model.util.Types;
77 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
78 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
79 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
80 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
81 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.common.QNameModule;
84 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
85 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
94 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
95 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
101 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
102 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
103 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
104 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
106 import org.opendaylight.yangtools.yang.model.api.Status;
107 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
108 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.UsesNode;
110 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
111 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
113 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
114 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
115 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
116 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
117 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
121 abstract class AbstractTypeGenerator {
122 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
123 private static final Splitter COLON_SPLITTER = Splitter.on(':');
124 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
125 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
126 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
129 * Comparator based on augment target path.
131 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
132 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
133 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
135 while (thisIt.hasNext()) {
136 if (!otherIt.hasNext()) {
140 final int comp = thisIt.next().compareTo(otherIt.next());
146 return otherIt.hasNext() ? -1 : 0;
150 * Constant with the concrete name of identifier.
152 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
155 * Constant with the concrete name of namespace.
157 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
159 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
162 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
163 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
164 * for schema node specified in key part.
166 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
169 * Provide methods for converting YANG types to JAVA types.
171 private final AbstractTypeProvider typeProvider;
174 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
176 private final SchemaContext schemaContext;
179 * Holds renamed elements.
181 private final Map<SchemaNode, JavaTypeName> renames;
183 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
184 final Map<SchemaNode, JavaTypeName> renames) {
185 this.schemaContext = requireNonNull(context);
186 this.typeProvider = requireNonNull(typeProvider);
187 this.renames = requireNonNull(renames);
189 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
190 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
191 for (final Module contextModule : contextModules) {
192 contexts.add(moduleToGenTypes(contextModule));
195 contexts.forEach(this::allAugmentsToGenTypes);
198 final Collection<ModuleContext> moduleContexts() {
199 return genCtx.values();
202 final ModuleContext moduleContext(final QNameModule module) {
203 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
206 final AbstractTypeProvider typeProvider() {
210 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
212 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
214 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
215 Set<? extends SchemaNode> nodes);
217 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
219 private ModuleContext moduleToGenTypes(final Module module) {
220 final ModuleContext context = new ModuleContext(module);
221 genCtx.put(module.getQNameModule(), context);
222 allTypeDefinitionsToGenTypes(context);
223 groupingsToGenTypes(context, module.getGroupings());
224 rpcMethodsToGenType(context);
225 allIdentitiesToGenTypes(context);
226 notificationsToGenType(context);
228 if (!module.getChildNodes().isEmpty()) {
229 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
230 context.addModuleNode(moduleType);
231 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
237 * Converts all extended type definitions of module to the list of
238 * <code>Type</code> objects.
241 * module from which is obtained set of type definitions
242 * @throws IllegalArgumentException
244 * <li>if module is null</li>
245 * <li>if name of module is null</li>
247 * @throws IllegalStateException
248 * if set of type definitions from module is null
250 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
251 final Module module = context.module();
252 checkArgument(module.getName() != null, "Module name cannot be NULL.");
253 final DataNodeIterator it = new DataNodeIterator(module);
254 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
255 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
257 for (final TypeDefinition<?> typedef : typeDefinitions) {
258 if (typedef != null) {
259 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
261 context.addTypedefType(typedef, type);
262 context.addTypeToSchema(type,typedef);
268 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
269 final DataSchemaNode node) {
270 if (node.isAugmenting() || node.isAddedByUses()) {
273 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
274 annotateDeprecatedIfNecessary(node.getStatus(), genType);
276 final Module module = context.module();
277 genType.setModuleName(module.getName());
278 addCodegenInformation(genType, module, node);
279 genType.setSchemaPath(node.getPath());
280 if (node instanceof DataNodeContainer) {
281 context.addChildNodeType(node, genType);
282 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
283 processUsesAugments((DataNodeContainer) node, context);
288 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
289 final Type baseInterface, final ContainerSchemaNode node) {
290 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
291 if (genType != null) {
292 constructGetter(parent, genType, node);
293 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
294 actionsToGenType(context, genType, node, null);
298 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
299 final Type baseInterface, final ListSchemaNode node) {
300 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
301 if (genType != null) {
302 constructGetter(parent, listTypeFor(genType), node);
304 final List<String> listKeys = listKeys(node);
305 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
306 if (genTOBuilder != null) {
307 final Type identifierMarker = identifier(genType);
308 final Type identifiableMarker = identifiable(genTOBuilder);
309 genTOBuilder.addImplementsType(identifierMarker);
310 genType.addImplementsType(identifiableMarker);
313 actionsToGenType(context, genType, node, genTOBuilder);
315 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
316 if (!schemaNode.isAugmenting()) {
317 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
322 if (genTOBuilder != null) {
323 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
324 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
325 genTOBuilder.setSUID(prop);
328 typeBuildersToGenTypes(context, genType, genTOBuilder);
332 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
333 for (final UsesNode usesNode : node.getUses()) {
334 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
335 usesAugmentationToGenTypes(context, augment, usesNode, node);
336 processUsesAugments(augment, context);
342 * Converts all <b>augmentation</b> of the module to the list
343 * <code>Type</code> objects.
346 * module from which is obtained list of all augmentation objects
347 * to iterate over them
348 * @throws IllegalArgumentException
350 * <li>if the module is null</li>
351 * <li>if the name of module is null</li>
353 * @throws IllegalStateException
354 * if set of augmentations from module is null
356 private void allAugmentsToGenTypes(final ModuleContext context) {
357 final Module module = context.module();
358 checkArgument(module != null, "Module reference cannot be NULL.");
359 checkArgument(module.getName() != null, "Module name cannot be NULL.");
360 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
362 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
363 augmentationToGenTypes(context, augment);
368 * Returns list of <code>AugmentationSchema</code> objects. The objects are
369 * sorted according to the length of their target path from the shortest to
373 * module from which is obtained list of all augmentation objects
374 * @return list of sorted <code>AugmentationSchema</code> objects obtained
375 * from <code>module</code>
376 * @throws IllegalArgumentException
378 * @throws IllegalStateException
379 * if set of module augmentations is null
381 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
382 checkArgument(module != null, "Module reference cannot be NULL.");
383 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
385 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
386 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
387 sortedAugmentations.sort(AUGMENT_COMP);
389 return sortedAugmentations;
393 * Create GeneratedTypeBuilder object from module argument.
396 * Module object from which builder will be created
397 * @return <code>GeneratedTypeBuilder</code> which is internal
398 * representation of the module
399 * @throws IllegalArgumentException
402 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
403 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
404 final Module module = context.module();
405 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
406 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
408 addCodegenInformation(moduleDataTypeBuilder, module);
409 return moduleDataTypeBuilder;
412 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
413 final Type parent, final T parentSchema, final Type keyType) {
414 for (final ActionDefinition action : parentSchema.getActions()) {
415 final GeneratedType input;
416 final GeneratedType output;
417 if (action.isAddedByUses()) {
418 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
419 input = context.getChildNode(orig.getInput().getPath()).build();
420 output = context.getChildNode(orig.getOutput().getPath()).build();
422 input = actionContainer(context, RPC_INPUT, action.getInput());
423 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
426 if (!(parentSchema instanceof GroupingDefinition)) {
427 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
428 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
429 // and do not capture an actual instantiation.
430 final QName qname = action.getQName();
431 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
432 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
433 BindingMapping.getClassName(qname)));
434 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
435 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
437 annotateDeprecatedIfNecessary(action.getStatus(), builder);
438 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
439 : action(parent, input, output));
441 addCodegenInformation(builder, context.module(), action);
442 context.addChildNodeType(action, builder);
447 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
448 for (UsesNode uses : parent.getUses()) {
449 final GroupingDefinition grp = findUsedGrouping(uses);
450 final Optional<ActionDefinition> found = grp.getActions().stream()
451 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
452 if (found.isPresent()) {
453 final ActionDefinition result = found.get();
454 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
458 return Optional.empty();
461 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
462 final ContainerSchemaNode schema) {
463 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
464 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
465 return genType.build();
469 * Converts all <b>RPCs</b> input and output substatements of the module
470 * to the list of <code>Type</code> objects. In addition are to containers
471 * and lists which belong to input or output also part of returning list.
474 * module from which is obtained set of all rpc objects to
476 * @throws IllegalArgumentException
478 * <li>if the module is null</li>
479 * <li>if the name of module is null</li>
481 * @throws IllegalStateException
482 * if set of rpcs from module is null
484 private void rpcMethodsToGenType(final ModuleContext context) {
485 final Module module = context.module();
486 checkArgument(module.getName() != null, "Module name cannot be NULL.");
487 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
488 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
489 if (rpcDefinitions.isEmpty()) {
493 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
494 interfaceBuilder.addImplementsType(RPC_SERVICE);
496 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
498 for (final RpcDefinition rpc : rpcDefinitions) {
500 final String rpcName = BindingMapping.getClassName(rpc.getQName());
501 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
502 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
504 // Do not refer to annotation class, as it may not be available at runtime
505 method.addAnnotation("javax.annotation", "CheckReturnValue");
506 addComment(method, rpc);
508 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
509 method.setReturnType(listenableFutureTypeFor(
510 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
514 context.addTopLevelNodeType(interfaceBuilder);
517 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
518 final ContainerSchemaNode schema, final Type type) {
519 processUsesAugments(schema, context);
520 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
521 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
523 addImplementedInterfaceFromUses(schema, outType);
524 outType.addImplementsType(type);
525 outType.addImplementsType(augmentable(outType));
526 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
527 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
528 context.addChildNodeType(schema, outType);
529 return outType.build();
533 * Converts all <b>notifications</b> of the module to the list of
534 * <code>Type</code> objects. In addition are to this list added containers
535 * and lists which are part of this notification.
538 * module from which is obtained set of all notification objects
539 * to iterate over them
540 * @throws IllegalArgumentException
542 * <li>if the module equals null</li>
543 * <li>if the name of module equals null</li>
545 * @throws IllegalStateException
546 * if set of notifications from module is null
548 private void notificationsToGenType(final ModuleContext context) {
549 final Module module = context.module();
550 checkArgument(module.getName() != null, "Module name cannot be NULL.");
551 final Set<NotificationDefinition> notifications = module.getNotifications();
552 if (notifications.isEmpty()) {
556 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
557 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
559 for (final NotificationDefinition notification : notifications) {
560 if (notification != null) {
561 processUsesAugments(notification, context);
563 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
564 context.modulePackageName(), notification, DATA_OBJECT, context);
565 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
566 notificationInterface.addImplementsType(NOTIFICATION);
567 context.addChildNodeType(notification, notificationInterface);
569 // Notification object
570 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
571 notification.getChildNodes());
573 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
574 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
575 .setReturnType(Types.primitiveVoidType()), notification);
579 addCodegenInformation(listenerInterface, module, "notifications", notifications);
580 context.addTopLevelNodeType(listenerInterface);
584 * Converts all <b>identities</b> of the module to the list of
585 * <code>Type</code> objects.
588 * module from which is obtained set of all identity objects to
590 * @param schemaContext
591 * schema context only used as input parameter for method
592 * {@link BindingGeneratorImpl#identityToGenType}
595 private void allIdentitiesToGenTypes(final ModuleContext context) {
596 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
598 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
599 for (final IdentitySchemaNode identity : schemaIdentities) {
600 identityToGenType(context, identity);
606 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
607 * created transport object builder. If identity contains base identity then
608 * reference to base identity is added to superior identity as its extend.
609 * If identity doesn't contain base identity then only reference to abstract
610 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
611 * BaseIdentity} is added
615 * @param basePackageName
616 * string contains the module package name
618 * IdentitySchemaNode which contains data about identity
620 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
621 if (identity == null) {
625 JavaTypeName name = renames.get(identity);
627 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
628 BindingMapping.getClassName(identity.getQName()));
631 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
632 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
633 if (!baseIdentities.isEmpty()) {
634 for (IdentitySchemaNode baseIdentity : baseIdentities) {
635 JavaTypeName base = renames.get(baseIdentity);
637 final QName qname = baseIdentity.getQName();
638 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
639 BindingMapping.getClassName(qname));
642 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
643 newType.addImplementsType(gto);
646 newType.addImplementsType(BASE_IDENTITY);
649 final Module module = context.module();
650 addCodegenInformation(newType, module, identity);
651 newType.setModuleName(module.getName());
652 newType.setSchemaPath(identity.getPath());
654 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
655 identity.getQName().getLocalName());
657 context.addIdentityType(identity, newType);
660 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
661 final JavaTypeName yangModuleInfo, final String localName) {
662 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
663 new SimpleImmutableEntry<>(yangModuleInfo, localName));
667 * Converts all <b>groupings</b> of the module to the list of
668 * <code>Type</code> objects. Firstly are groupings sorted according mutual
669 * dependencies. At least dependent (independent) groupings are in the list
670 * saved at first positions. For every grouping the record is added to map
671 * {@link ModuleContext#groupings allGroupings}
676 * collection of groupings from which types will be generated
679 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
680 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
681 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
682 // node of grouping is resolved to the method.
683 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
684 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
685 context.addGroupingType(grouping, genType);
686 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
687 groupingsToGenTypes(context, grouping.getGroupings());
688 processUsesAugments(grouping, context);
689 actionsToGenType(context, genType, grouping, null);
694 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
695 * <code>enumTypeDef</code> item is added to builder with its name and value.
697 * @param enumTypeDef EnumTypeDefinition contains enum data
698 * @param enumName string contains name which will be assigned to enumeration builder
699 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
700 * @param module Module in which type should be generated
701 * @return enumeration builder which contains data from <code>enumTypeDef</code>
703 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
704 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
705 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
706 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
707 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
708 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
709 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
716 * Generates type builder for <code>module</code>.
718 * @param module Module which is source of package name for generated type builder
719 * @param postfix string which is added to the module class name representation as suffix
720 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
721 * @throws IllegalArgumentException if <code>module</code> is null
723 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
724 final Module module = context.module();
725 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
726 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
727 JavaTypeName.create(context.modulePackageName(), moduleName));
729 moduleBuilder.setModuleName(moduleName);
730 addCodegenInformation(moduleBuilder, module);
731 return moduleBuilder;
735 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
736 * In addition there are also generated types for all containers, list and choices which are child of
737 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
739 * @param augmentPackageName string with the name of the package to which the augmentation belongs
740 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
741 * @param module current module
742 * @throws IllegalArgumentException
744 * <li>if <code>augmentPackageName</code> equals null</li>
745 * <li>if <code>augSchema</code> equals null</li>
747 * @throws IllegalStateException
748 * if augment target path is null
750 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
751 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
752 checkState(augSchema.getTargetPath() != null,
753 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
755 processUsesAugments(augSchema, context);
756 final SchemaPath targetPath = augSchema.getTargetPath();
757 SchemaNode targetSchemaNode = null;
759 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
760 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
761 if (targetSchemaNode instanceof DerivableSchemaNode) {
762 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
764 if (targetSchemaNode == null) {
765 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
766 + " in module " + context.module().getName());
769 if (targetSchemaNode == null) {
770 throw new IllegalArgumentException("augment target not found: " + targetPath);
773 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
774 if (targetTypeBuilder == null) {
775 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
777 if (targetTypeBuilder == null) {
778 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
781 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
782 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
783 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
786 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
787 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
791 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
792 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
793 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
794 checkState(augSchema.getTargetPath() != null,
795 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
797 processUsesAugments(augSchema, context);
798 final SchemaPath targetPath = augSchema.getTargetPath();
799 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
800 if (targetSchemaNode == null) {
801 throw new IllegalArgumentException("augment target not found: " + targetPath);
804 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
805 if (targetTypeBuilder == null) {
806 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
808 if (targetTypeBuilder == null) {
809 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
812 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
813 if (usesNodeParent instanceof SchemaNode) {
814 addRawAugmentGenTypeDefinition(context,
815 packageNameForAugmentedGeneratedType(context.modulePackageName(),
816 ((SchemaNode) usesNodeParent).getPath()),
817 targetTypeBuilder.build(), augSchema);
819 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
822 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
823 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
827 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
828 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
830 if (targetGrouping instanceof GroupingDefinition) {
831 return (GroupingDefinition) targetGrouping;
834 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
838 * Convenient method to find node added by uses statement.
840 * @param targetPath node path
841 * @param parentUsesNode parent of uses node
842 * @return node from its original location in grouping
844 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
845 SchemaNode result = findUsedGrouping(parentUsesNode);
846 for (final QName node : targetPath.getPathFromRoot()) {
847 if (result instanceof DataNodeContainer) {
848 final QName resultNode = node.withModule(result.getQName().getModule());
849 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
850 } else if (result instanceof ChoiceSchemaNode) {
851 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
854 if (result == null) {
858 if (result instanceof DerivableSchemaNode) {
859 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
860 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
861 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
862 result = originalNode.get();
866 if (result instanceof DataSchemaNode) {
867 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
868 if (resultDataSchemaNode.isAddedByUses()) {
869 // The original node is required, but we have only the copy of
870 // the original node.
871 // Maybe this indicates a bug in Yang parser.
872 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
875 return resultDataSchemaNode;
878 throw new IllegalStateException(
879 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
884 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
885 * of augmented node with serial number as suffix.
887 * @param context current module
888 * @param augmentPackageName string with contains the package name to which the augment belongs
889 * @param basePackageName string with the package name to which the augmented node belongs
890 * @param targetTypeRef target type
891 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
892 * @return generated type builder for augment
894 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
895 final String augmentPackageName, final Type targetTypeRef,
896 final AugmentationSchemaNode augSchema) {
897 Map<String, GeneratedTypeBuilder> augmentBuilders =
898 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
899 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
902 if (augIdentifier != null) {
903 augTypeName = BindingMapping.getClassName(augIdentifier);
905 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
908 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
909 JavaTypeName.create(augmentPackageName, augTypeName));
911 augTypeBuilder.addImplementsType(DATA_OBJECT);
912 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
913 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
914 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
916 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
917 augmentBuilders.put(augTypeName, augTypeBuilder);
919 if (!augSchema.getChildNodes().isEmpty()) {
920 context.addTypeToAugmentation(augTypeBuilder, augSchema);
923 context.addAugmentType(augTypeBuilder);
924 return augTypeBuilder;
927 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
928 final AugmentationSchemaNode augSchema) {
929 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
932 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
933 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
934 final QName nodeType = unknownSchemaNode.getNodeType();
935 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
936 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
937 return unknownSchemaNode.getNodeParameter();
944 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
945 * consists from name of augmented node and serial number of its augmentation.
947 * @param builders map of builders which were created in the package to which the augmentation belongs
948 * @param genTypeName string with name of augmented node
949 * @return string with unique name for augmentation builder
951 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
953 if (builders != null) {
954 while (builders.containsKey(genTypeName + index)) {
958 return genTypeName + index;
962 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
963 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
964 * already part of them).
966 * @param module current module
967 * @param parent generated type builder which represents any node. The subnodes of this node are added
968 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
970 * @param childOf parent type
971 * @param schemaNodes set of data schema nodes which are the children of the node for which
972 * <code>typeBuilder</code> was created
973 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
974 * child nodes) could be added to it.
976 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
977 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
978 if (schemaNodes != null && parent != null) {
979 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
980 for (final DataSchemaNode schemaNode : schemaNodes) {
981 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
982 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
990 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
993 * @param module current module
994 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
995 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
997 * @param childOf parent type
998 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1000 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1001 * The getter method could be added to it.
1003 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1004 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1005 if (schemaNodes != null && typeBuilder != null) {
1006 final Type baseInterface = childOf(typeBuilder);
1007 for (final DataSchemaNode schemaNode : schemaNodes) {
1008 if (!schemaNode.isAugmenting()) {
1009 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1017 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1019 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1020 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1021 * @param childOf parent type
1022 * @param module current module
1024 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1025 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1026 if (node != null && typeBuilder != null) {
1027 if (node instanceof LeafSchemaNode) {
1028 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1029 } else if (node instanceof LeafListSchemaNode) {
1030 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1031 } else if (node instanceof ContainerSchemaNode) {
1032 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1033 } else if (node instanceof ListSchemaNode) {
1034 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1035 } else if (node instanceof ChoiceSchemaNode) {
1036 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1038 // TODO: anyxml not yet supported
1039 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1040 typeBuilder.getFullyQualifiedName());
1046 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1047 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1048 * and names of all parents node.
1050 * @param context current module
1051 * @param basePackageName string with the module package name
1052 * @param parent parent type
1053 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1055 * @throws IllegalArgumentException
1057 * <li>if <code>basePackageName</code> is null</li>
1058 * <li>if <code>choiceNode</code> is null</li>
1061 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1062 final ChoiceSchemaNode choiceNode) {
1063 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1065 if (!choiceNode.isAddedByUses()) {
1066 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1067 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1068 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1069 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1070 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1071 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1073 final GeneratedType choiceType = choiceTypeBuilder.build();
1074 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1076 constructGetter(parent, choiceType, choiceNode);
1081 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1082 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1083 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1084 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1086 * @param context current module context
1087 * @param refChoiceType type which represents superior <i>case</i>
1088 * @param choiceNode choice case node which is mapped to generated type
1089 * @throws IllegalArgumentException
1091 * <li>if <code>refChoiceType</code> equals null</li>
1092 * <li>if <code>caseNodes</code> equals null</li>
1095 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1096 final ChoiceSchemaNode choiceNode) {
1097 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1098 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1100 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1101 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1102 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1103 caseTypeBuilder.addImplementsType(refChoiceType);
1104 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1105 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1106 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1107 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1108 if (caseChildNodes != null) {
1109 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1111 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1112 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1114 if (parent instanceof AugmentationSchemaNode) {
1115 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1116 final SchemaPath targetPath = augSchema.getTargetPath();
1117 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1118 if (targetSchemaNode instanceof DataSchemaNode
1119 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1120 if (targetSchemaNode instanceof DerivableSchemaNode) {
1121 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1124 if (targetSchemaNode == null) {
1125 throw new IllegalStateException(
1126 "Failed to find target node from grouping for augmentation " + augSchema
1127 + " in module " + context.module().getName());
1130 parent = targetSchemaNode;
1133 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1134 Type childOfType = findChildNodeByPath(parent.getPath());
1135 if (childOfType == null) {
1136 childOfType = findGroupingByPath(parent.getPath());
1138 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1140 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1144 processUsesAugments(caseNode, context);
1149 * Generates list of generated types for all the cases of a choice which are added to the choice through
1152 * @param module current module
1153 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1154 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1155 * of the augmenting choice will belong to pcg2.
1156 * @param targetType Type which represents target choice
1157 * @param targetNode node which represents target choice
1158 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1160 * @throws IllegalArgumentException
1162 * <li>if <code>basePackageName</code> is null</li>
1163 * <li>if <code>targetType</code> is null</li>
1164 * <li>if <code>augmentedNodes</code> is null</li>
1167 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1168 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1169 final DataNodeContainer usesNodeParent) {
1170 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1171 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1173 for (final DataSchemaNode caseNode : augmentedNodes) {
1174 if (caseNode != null) {
1175 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1176 caseTypeBuilder.addImplementsType(targetType);
1178 CaseSchemaNode node = null;
1179 final String caseLocalName = caseNode.getQName().getLocalName();
1180 if (caseNode instanceof CaseSchemaNode) {
1181 node = (CaseSchemaNode) caseNode;
1182 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1183 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1184 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1185 if (dataSchemaNode instanceof ChoiceSchemaNode
1186 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1187 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1192 node = findNamedCase(targetNode, caseLocalName);
1194 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1195 if (childNodes != null) {
1196 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1198 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1199 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1204 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1205 final SchemaPath nodePath = targetNode.getPath();
1206 final SchemaPath parentSp = nodePath.getParent();
1207 if (parentSp.getParent() == null) {
1208 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1211 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1212 GeneratedTypeBuilder childOfType = null;
1213 if (parent instanceof CaseSchemaNode) {
1214 childOfType = findCaseByPath(parent.getPath());
1215 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1216 childOfType = findChildNodeByPath(parent.getPath());
1217 } else if (parent instanceof GroupingDefinition) {
1218 childOfType = findGroupingByPath(parent.getPath());
1221 if (childOfType == null) {
1222 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1228 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1229 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1230 return cases.isEmpty() ? null : cases.get(0);
1233 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1234 // New parser with encapsulated type
1235 if (leaf.getPath().equals(type.getPath())) {
1239 // Embedded type definition with new parser. Also takes care of the old parser with bits
1240 if (leaf.getPath().equals(type.getPath().getParent())) {
1247 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1248 final List<PatternConstraint> patternConstraints) {
1249 if (!patternConstraints.isEmpty()) {
1250 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1251 .append(BindingMapping.getPropertyName(leafName));
1252 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1253 typeProvider.resolveRegExpressions(patternConstraints));
1258 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1260 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1261 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1262 * @param module Module in which type was defined
1263 * @return boolean value
1265 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1267 * <li>true - in other cases</li>
1270 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1271 final ModuleContext context) {
1272 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1276 final Module parentModule = findParentModule(schemaContext, leaf);
1277 Type returnType = null;
1279 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1280 if (isInnerType(leaf, typeDef)) {
1281 if (typeDef instanceof EnumTypeDefinition) {
1282 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1283 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1284 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1285 typeBuilder, context);
1286 if (enumBuilder != null) {
1287 returnType = enumBuilder.toInstance(typeBuilder);
1289 typeProvider.putReferencedType(leaf.getPath(), returnType);
1290 } else if (typeDef instanceof UnionTypeDefinition) {
1291 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1292 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1293 // Store the inner type within the union so that we can find the reference for it
1294 context.addInnerTypedefType(typeDef.getPath(), returnType);
1295 } else if (typeDef instanceof BitsTypeDefinition) {
1296 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1298 if (genTOBuilder != null) {
1299 returnType = genTOBuilder.build();
1302 // It is constrained version of already declared type (inner declared type exists,
1303 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1304 // In order to get proper class we need to look up closest derived type
1305 // and apply restrictions from leaf type
1306 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1307 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1309 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1312 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1313 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1314 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1317 if (returnType == null) {
1321 if (typeDef instanceof EnumTypeDefinition) {
1322 typeProvider.putReferencedType(leaf.getPath(), returnType);
1325 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1326 processContextRefExtension(leaf, getter, parentModule);
1330 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1331 // Returns DerivedType in case of new parser.
1332 final TypeDefinition<?> baseType = typeDef.getBaseType();
1333 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1336 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1337 final Module module) {
1338 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1339 final QName nodeType = node.getNodeType();
1340 if ("context-reference".equals(nodeType.getLocalName())) {
1341 final String nodeParam = node.getNodeParameter();
1342 IdentitySchemaNode identity = null;
1343 String basePackageName = null;
1344 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1345 final Iterator<String> iterator = splittedElement.iterator();
1346 final int length = Iterables.size(splittedElement);
1348 identity = findIdentityByName(module.getIdentities(), iterator.next());
1349 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1350 } else if (length == 2) {
1351 final String prefix = iterator.next();
1352 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1353 if (dependentModule == null) {
1354 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1357 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1358 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1360 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1363 if (identity == null) {
1364 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1368 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1369 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1370 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1371 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1376 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1377 for (final IdentitySchemaNode id : identities) {
1378 if (id.getQName().getLocalName().equals(name)) {
1385 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1386 for (final ModuleImport imp : imports) {
1387 if (imp.getPrefix().equals(prefix)) {
1388 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1394 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1395 final boolean isReadOnly) {
1396 if (leaf != null && toBuilder != null) {
1398 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1399 if (typeDef instanceof UnionTypeDefinition) {
1400 // GeneratedType for this type definition should have be already created
1401 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1402 returnType = mc.getTypedefs().get(typeDef.getPath());
1403 if (returnType == null) {
1404 // This may still be an inner type, try to find it
1405 returnType = mc.getInnerType(typeDef.getPath());
1407 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1408 // Annonymous enumeration (already generated, since it is inherited via uses).
1409 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1410 QName qname = originalLeaf.getQName();
1411 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1413 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1415 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1421 * Converts <code>leaf</code> schema node to property of generated TO builder.
1423 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1424 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1425 * @param returnType property type
1426 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1427 * @return boolean value
1429 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1430 * name equals null or if leaf is added by <i>uses</i>.</li>
1431 * <li>true - other cases</li>
1434 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1435 final Type returnType, final boolean isReadOnly) {
1436 if (returnType == null) {
1439 final String leafName = leaf.getQName().getLocalName();
1440 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1441 propBuilder.setReadOnly(isReadOnly);
1442 propBuilder.setReturnType(returnType);
1443 addComment(propBuilder, leaf);
1445 toBuilder.addEqualsIdentity(propBuilder);
1446 toBuilder.addHashIdentity(propBuilder);
1447 toBuilder.addToStringProperty(propBuilder);
1452 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1454 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1455 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1456 * @param module module
1457 * @return boolean value
1459 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1460 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1461 * <li>false - other cases</li>
1464 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1465 final ModuleContext context) {
1466 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1470 final QName nodeName = node.getQName();
1472 final TypeDefinition<?> typeDef = node.getType();
1473 final Module parentModule = findParentModule(schemaContext, node);
1475 Type returnType = null;
1476 if (typeDef.getBaseType() == null) {
1477 if (typeDef instanceof EnumTypeDefinition) {
1478 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1479 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1480 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1481 typeBuilder, context);
1482 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1483 typeProvider.putReferencedType(node.getPath(), returnType);
1484 } else if (typeDef instanceof UnionTypeDefinition) {
1485 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1486 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1487 } else if (typeDef instanceof BitsTypeDefinition) {
1488 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1489 node, parentModule);
1490 returnType = genTOBuilder.build();
1492 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1493 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1494 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1497 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1498 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1499 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1502 final ParameterizedType listType = listTypeFor(returnType);
1503 constructGetter(typeBuilder, listType, node);
1507 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1508 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1509 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1510 returnTypeBuilder.setIsUnion(true);
1511 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1512 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1513 returnTypeBuilder.setModuleName(parentModule.getName());
1514 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1516 genTOBuilder.setTypedef(true);
1517 genTOBuilder.setIsUnion(true);
1518 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1520 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1524 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1525 final GeneratedTransferObject returnType, final Module parentModule) {
1526 // Append enclosing path hierarchy without dots
1527 final StringBuilder sb = new StringBuilder();
1528 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1529 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1530 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1531 unionBuilder.setIsUnionBuilder(true);
1533 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1534 method.setReturnType(returnType);
1535 method.addParameter(Types.STRING, "defaultValue");
1536 method.setAccessModifier(AccessModifier.PUBLIC);
1537 method.setStatic(true);
1539 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1540 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1541 if (types == null) {
1542 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1544 types.add(unionBuilderType);
1548 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1549 final SchemaNode schemaNode) {
1550 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1553 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1554 final SchemaNode schemaNode, final Type baseInterface) {
1555 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1556 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1560 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1561 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1562 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1563 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1564 * If <code>schemaNode</code> is instance of
1565 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1566 * which are specified in <i>uses</i>.
1568 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1569 * @param schemaNode schema node for which is created generated type builder
1570 * @param parent parent type (can be null)
1571 * @return generated type builder <code>schemaNode</code>
1573 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1574 final Type baseInterface, final ModuleContext context) {
1575 JavaTypeName name = renames.get(schemaNode);
1577 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1580 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1582 it.addImplementsType(baseInterface);
1583 if (!(schemaNode instanceof GroupingDefinition)) {
1584 it.addImplementsType(augmentable(it));
1586 if (schemaNode instanceof DataNodeContainer) {
1587 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1588 groupingsToGenTypes(context, containerSchema.getGroupings());
1589 addImplementedInterfaceFromUses(containerSchema, it);
1596 * Wraps the calling of the same overloaded method.
1598 * @param packageName string with the package name to which returning generated type builder belongs
1599 * @param schemaNode schema node which provide data about the schema node name
1600 * @return generated type builder for <code>schemaNode</code>
1602 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1603 final String prefix) {
1604 return addRawInterfaceDefinition(
1605 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1606 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1610 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1611 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1612 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1614 * @param packageName string with the package name to which returning generated type builder belongs
1615 * @param schemaNode schema node which provide data about the schema node name
1616 * @param prefix return type name prefix
1617 * @return generated type builder for <code>schemaNode</code>
1618 * @throws IllegalArgumentException
1620 * <li>if <code>schemaNode</code> is null</li>
1621 * <li>if <code>packageName</code> is null</li>
1622 * <li>if QName of schema node is null</li>
1623 * <li>if schemaNode name is null</li>
1626 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1627 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1628 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1629 final String schemaNodeName = schemaNode.getQName().getLocalName();
1630 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1632 // FIXME: Validation of name conflict
1633 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1634 final Module module = findParentModule(schemaContext, schemaNode);
1635 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1636 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1638 addCodegenInformation(newType, module, schemaNode);
1639 newType.setSchemaPath(schemaNode.getPath());
1640 newType.setModuleName(module.getName());
1642 final String packageName = identifier.packageName();
1643 final String simpleName = identifier.simpleName();
1644 if (!genTypeBuilders.containsKey(packageName)) {
1645 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1646 builders.put(simpleName, newType);
1647 genTypeBuilders.put(packageName, builders);
1649 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1650 if (!builders.containsKey(simpleName)) {
1651 builders.put(simpleName, newType);
1658 * Creates the name of the getter method name from <code>localName</code>.
1660 * @param localName string with the name of the getter method
1661 * @param returnType return type
1662 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1664 public static String getterMethodName(final String localName, final Type returnType) {
1665 final StringBuilder method = new StringBuilder();
1666 if (BOOLEAN.equals(returnType)) {
1667 method.append("is");
1669 method.append("get");
1671 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1672 method.append(name);
1673 return method.toString();
1677 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1678 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1679 * and <code>returnType</code> information are added to the builder.
1681 * @param interfaceBuilder generated type builder for which the getter method should be created
1682 * @param returnType type which represents the return type of the getter method
1683 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1684 * @param comment string with comment for the getter method
1685 * @param status status from yang file, for deprecated annotation
1686 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1688 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1689 final SchemaNode node) {
1690 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1691 getterMethodName(node.getQName().getLocalName(), returnType));
1692 getMethod.setReturnType(returnType);
1694 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1695 if (!returnType.getPackageName().isEmpty()) {
1696 // The return type has a package, so it's not a primitive type
1697 getMethod.addAnnotation("javax.annotation", "Nullable");
1699 addComment(getMethod, node);
1705 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1708 * @param basePackageName string contains the module package name
1709 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1710 * or as a property to <code>genTOBuilder</code> if is part of the list key
1711 * @param typeBuilder generated type builder for the list schema node
1712 * @param genTOBuilder generated TO builder for the list keys
1713 * @param listKeys list of string which contains names of the list keys
1714 * @param module current module
1715 * @throws IllegalArgumentException
1717 * <li>if <code>schemaNode</code> equals null</li>
1718 * <li>if <code>typeBuilder</code> equals null</li>
1721 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1722 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1723 final List<String> listKeys) {
1724 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1725 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1727 if (schemaNode instanceof LeafSchemaNode) {
1728 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1729 final String leafName = leaf.getQName().getLocalName();
1730 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1731 if (listKeys.contains(leafName)) {
1733 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1735 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1738 } else if (!schemaNode.isAddedByUses()) {
1739 if (schemaNode instanceof LeafListSchemaNode) {
1740 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1741 } else if (schemaNode instanceof ContainerSchemaNode) {
1742 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1743 (ContainerSchemaNode) schemaNode);
1744 } else if (schemaNode instanceof ChoiceSchemaNode) {
1745 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1746 } else if (schemaNode instanceof ListSchemaNode) {
1747 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1752 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1753 final GeneratedTOBuilder genTOBuilder) {
1754 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1756 if (genTOBuilder != null) {
1757 final GeneratedTransferObject genTO = genTOBuilder.build();
1758 // Add Identifiable.getKey() for items
1759 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1760 .addAnnotation(OVERRIDE_ANNOTATION);
1761 context.addGeneratedTOBuilder(genTOBuilder);
1766 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1768 * @param list of string with names of the list keys
1769 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1770 * an empty list is returned.
1772 private static List<String> listKeys(final ListSchemaNode list) {
1773 final List<String> listKeys = new ArrayList<>();
1775 final List<QName> keyDefinition = list.getKeyDefinition();
1776 if (keyDefinition != null) {
1777 for (final QName keyDef : keyDefinition) {
1778 listKeys.add(keyDef.getLocalName());
1785 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1787 * @param packageName string with package name to which the list belongs
1788 * @param list list schema node which is source of data about the list name
1789 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1790 * null or list of key definitions is null or empty.
1792 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1793 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1794 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1795 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1796 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1802 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1803 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1804 * enclosing transfer objects.
1806 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1807 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1808 * @param leaf string with name for generated TO builder
1809 * @param parentModule parent module
1810 * @return generated TO builder for <code>typeDef</code>
1812 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1813 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1814 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1815 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1818 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1819 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1820 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1821 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1822 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1824 for (GeneratedTOBuilder builder : types) {
1825 if (builder.isUnion()) {
1826 final GeneratedTransferObject type = builder.build();
1827 createUnionBuilder(builder, typeBuilder, type, parentModule);
1831 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1835 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1836 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1837 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1840 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1841 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1842 * @param leaf string with name for generated TO builder
1843 * @param parentModule parent module
1844 * @return generated TO builder for <code>typeDef</code>
1846 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1847 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1848 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1849 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1850 typeDef, parentModule.getName());
1851 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1852 return genTOBuilder;
1857 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1858 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1859 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1860 * to <code>builder</code>
1862 * @param dataNodeContainer element which contains the list of used YANG groupings
1863 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1864 * @return generated type builder with all implemented types
1866 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1867 final GeneratedTypeBuilder builder) {
1868 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1869 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1870 if (genType == null) {
1871 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1872 + builder.getName());
1875 builder.addImplementsType(genType);
1880 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1881 for (final ModuleContext ctx : genCtx.values()) {
1882 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1883 if (result != null) {
1890 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1891 for (final ModuleContext ctx : genCtx.values()) {
1892 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1893 if (result != null) {
1900 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1901 for (final ModuleContext ctx : genCtx.values()) {
1902 final GeneratedTypeBuilder result = ctx.getCase(path);
1903 if (result != null) {
1910 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1911 if (status == Status.DEPRECATED) {
1912 builder.addAnnotation(DEPRECATED_ANNOTATION);