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
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder for schema node specified in key part.
167 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
170 * Provide methods for converting YANG types to JAVA types.
172 private final AbstractTypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element
176 * when creating augmentation builder
178 private final SchemaContext schemaContext;
181 * Holds renamed elements.
183 private final Map<SchemaNode, JavaTypeName> renames;
185 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
186 final Map<SchemaNode, JavaTypeName> renames) {
187 this.schemaContext = requireNonNull(context);
188 this.typeProvider = requireNonNull(typeProvider);
189 this.renames = requireNonNull(renames);
191 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
192 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
193 for (final Module contextModule : contextModules) {
194 contexts.add(moduleToGenTypes(contextModule));
197 contexts.forEach(this::allAugmentsToGenTypes);
200 final Collection<ModuleContext> moduleContexts() {
201 return genCtx.values();
204 final ModuleContext moduleContext(final QNameModule module) {
205 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
208 final AbstractTypeProvider typeProvider() {
212 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
214 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
216 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
217 Set<? extends SchemaNode> nodes);
219 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
221 private ModuleContext moduleToGenTypes(final Module module) {
222 final ModuleContext context = new ModuleContext(module);
223 genCtx.put(module.getQNameModule(), context);
224 allTypeDefinitionsToGenTypes(context);
225 groupingsToGenTypes(context, module.getGroupings());
226 rpcMethodsToGenType(context);
227 allIdentitiesToGenTypes(context);
228 notificationsToGenType(context);
230 if (!module.getChildNodes().isEmpty()) {
231 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
232 context.addModuleNode(moduleType);
233 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
239 * Converts all extended type definitions of module to the list of
240 * <code>Type</code> objects.
243 * module from which is obtained set of type definitions
244 * @throws IllegalArgumentException
246 * <li>if module is null</li>
247 * <li>if name of module is null</li>
249 * @throws IllegalStateException
250 * if set of type definitions from module is null
252 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
253 final Module module = context.module();
254 checkArgument(module.getName() != null, "Module name cannot be NULL.");
255 final DataNodeIterator it = new DataNodeIterator(module);
256 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
257 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
259 for (final TypeDefinition<?> typedef : typeDefinitions) {
260 if (typedef != null) {
261 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
263 context.addTypedefType(typedef, type);
264 context.addTypeToSchema(type,typedef);
270 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
271 final DataSchemaNode node) {
272 if (node.isAugmenting() || node.isAddedByUses()) {
275 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
276 annotateDeprecatedIfNecessary(node.getStatus(), genType);
278 final Module module = context.module();
279 genType.setModuleName(module.getName());
280 addCodegenInformation(genType, module, node);
281 genType.setSchemaPath(node.getPath());
282 if (node instanceof DataNodeContainer) {
283 context.addChildNodeType(node, genType);
284 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
285 processUsesAugments((DataNodeContainer) node, context);
290 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
291 final Type baseInterface, final ContainerSchemaNode node) {
292 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
293 if (genType != null) {
294 constructGetter(parent, genType, node);
295 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
296 actionsToGenType(context, genType, node, null);
300 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
301 final Type baseInterface, final ListSchemaNode node) {
302 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
303 if (genType != null) {
304 constructGetter(parent, listTypeFor(genType), node);
306 final List<String> listKeys = listKeys(node);
307 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
308 if (genTOBuilder != null) {
309 final Type identifierMarker = identifier(genType);
310 final Type identifiableMarker = identifiable(genTOBuilder);
311 genTOBuilder.addImplementsType(identifierMarker);
312 genType.addImplementsType(identifiableMarker);
315 actionsToGenType(context, genType, node, genTOBuilder);
317 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
318 if (!schemaNode.isAugmenting()) {
319 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
324 if (genTOBuilder != null) {
325 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
326 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
327 genTOBuilder.setSUID(prop);
330 typeBuildersToGenTypes(context, genType, genTOBuilder);
334 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
335 for (final UsesNode usesNode : node.getUses()) {
336 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
337 usesAugmentationToGenTypes(context, augment, usesNode, node);
338 processUsesAugments(augment, context);
344 * Converts all <b>augmentation</b> of the module to the list
345 * <code>Type</code> objects.
348 * module from which is obtained list of all augmentation objects
349 * to iterate over them
350 * @throws IllegalArgumentException
352 * <li>if the module is null</li>
353 * <li>if the name of module is null</li>
355 * @throws IllegalStateException
356 * if set of augmentations from module is null
358 private void allAugmentsToGenTypes(final ModuleContext context) {
359 final Module module = context.module();
360 checkArgument(module != null, "Module reference cannot be NULL.");
361 checkArgument(module.getName() != null, "Module name cannot be NULL.");
362 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
364 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
365 augmentationToGenTypes(context, augment);
370 * Returns list of <code>AugmentationSchema</code> objects. The objects are
371 * sorted according to the length of their target path from the shortest to
375 * module from which is obtained list of all augmentation objects
376 * @return list of sorted <code>AugmentationSchema</code> objects obtained
377 * from <code>module</code>
378 * @throws IllegalArgumentException
380 * @throws IllegalStateException
381 * if set of module augmentations is null
383 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
384 checkArgument(module != null, "Module reference cannot be NULL.");
385 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
387 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
388 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
389 sortedAugmentations.sort(AUGMENT_COMP);
391 return sortedAugmentations;
395 * Create GeneratedTypeBuilder object from module argument.
398 * Module object from which builder will be created
399 * @return <code>GeneratedTypeBuilder</code> which is internal
400 * representation of the module
401 * @throws IllegalArgumentException
404 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
405 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
406 final Module module = context.module();
407 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
408 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
410 addCodegenInformation(moduleDataTypeBuilder, module);
411 return moduleDataTypeBuilder;
414 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
415 final Type parent, final T parentSchema, final Type keyType) {
416 for (final ActionDefinition action : parentSchema.getActions()) {
417 final GeneratedType input;
418 final GeneratedType output;
419 if (action.isAddedByUses()) {
420 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
421 input = context.getChildNode(orig.getInput().getPath()).build();
422 output = context.getChildNode(orig.getOutput().getPath()).build();
424 input = actionContainer(context, RPC_INPUT, action.getInput());
425 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
428 if (!(parentSchema instanceof GroupingDefinition)) {
429 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
430 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
431 // and do not capture an actual instantiation.
432 final QName qname = action.getQName();
433 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
434 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
435 BindingMapping.getClassName(qname)));
436 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
437 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
439 annotateDeprecatedIfNecessary(action.getStatus(), builder);
440 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
441 : action(parent, input, output));
443 addCodegenInformation(builder, context.module(), action);
444 context.addChildNodeType(action, builder);
449 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
450 for (UsesNode uses : parent.getUses()) {
451 final GroupingDefinition grp = findUsedGrouping(uses);
452 final Optional<ActionDefinition> found = grp.getActions().stream()
453 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
454 if (found.isPresent()) {
455 final ActionDefinition result = found.get();
456 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
460 return Optional.empty();
463 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
464 final ContainerSchemaNode schema) {
465 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
466 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
467 return genType.build();
471 * Converts all <b>RPCs</b> input and output substatements of the module
472 * to the list of <code>Type</code> objects. In addition are to containers
473 * and lists which belong to input or output also part of returning list.
476 * module from which is obtained set of all rpc objects to
478 * @throws IllegalArgumentException
480 * <li>if the module is null</li>
481 * <li>if the name of module is null</li>
483 * @throws IllegalStateException
484 * if set of rpcs from module is null
486 private void rpcMethodsToGenType(final ModuleContext context) {
487 final Module module = context.module();
488 checkArgument(module.getName() != null, "Module name cannot be NULL.");
489 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
490 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
491 if (rpcDefinitions.isEmpty()) {
495 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
496 interfaceBuilder.addImplementsType(RPC_SERVICE);
498 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
500 for (final RpcDefinition rpc : rpcDefinitions) {
502 final String rpcName = BindingMapping.getClassName(rpc.getQName());
503 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
504 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
506 // Do not refer to annotation class, as it may not be available at runtime
507 method.addAnnotation("javax.annotation", "CheckReturnValue");
508 addComment(method, rpc);
510 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
511 method.setReturnType(listenableFutureTypeFor(
512 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
516 context.addTopLevelNodeType(interfaceBuilder);
519 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
520 final ContainerSchemaNode schema, final Type type) {
521 processUsesAugments(schema, context);
522 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
523 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
525 addImplementedInterfaceFromUses(schema, outType);
526 outType.addImplementsType(type);
527 outType.addImplementsType(augmentable(outType));
528 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
529 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
530 context.addChildNodeType(schema, outType);
531 return outType.build();
535 * Converts all <b>notifications</b> of the module to the list of
536 * <code>Type</code> objects. In addition are to this list added containers
537 * and lists which are part of this notification.
540 * module from which is obtained set of all notification objects
541 * to iterate over them
542 * @throws IllegalArgumentException
544 * <li>if the module equals null</li>
545 * <li>if the name of module equals null</li>
547 * @throws IllegalStateException
548 * if set of notifications from module is null
550 private void notificationsToGenType(final ModuleContext context) {
551 final Module module = context.module();
552 checkArgument(module.getName() != null, "Module name cannot be NULL.");
553 final Set<NotificationDefinition> notifications = module.getNotifications();
554 if (notifications.isEmpty()) {
558 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
559 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
561 for (final NotificationDefinition notification : notifications) {
562 if (notification != null) {
563 processUsesAugments(notification, context);
565 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
566 context.modulePackageName(), notification, DATA_OBJECT, context);
567 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
568 notificationInterface.addImplementsType(NOTIFICATION);
569 context.addChildNodeType(notification, notificationInterface);
571 // Notification object
572 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
573 notification.getChildNodes());
575 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
576 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
577 .setReturnType(Types.primitiveVoidType()), notification);
581 addCodegenInformation(listenerInterface, module, "notifications", notifications);
582 context.addTopLevelNodeType(listenerInterface);
586 * Converts all <b>identities</b> of the module to the list of
587 * <code>Type</code> objects.
590 * module from which is obtained set of all identity objects to
592 * @param schemaContext
593 * schema context only used as input parameter for method
594 * {@link BindingGeneratorImpl#identityToGenType}
597 private void allIdentitiesToGenTypes(final ModuleContext context) {
598 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
600 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
601 for (final IdentitySchemaNode identity : schemaIdentities) {
602 identityToGenType(context, identity);
608 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
609 * created transport object builder. If identity contains base identity then
610 * reference to base identity is added to superior identity as its extend.
611 * If identity doesn't contain base identity then only reference to abstract
612 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
613 * BaseIdentity} is added
617 * @param basePackageName
618 * string contains the module package name
620 * IdentitySchemaNode which contains data about identity
622 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
623 if (identity == null) {
627 JavaTypeName name = renames.get(identity);
629 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
630 BindingMapping.getClassName(identity.getQName()));
633 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
634 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
635 if (!baseIdentities.isEmpty()) {
636 for (IdentitySchemaNode baseIdentity : baseIdentities) {
637 JavaTypeName base = renames.get(baseIdentity);
639 final QName qname = baseIdentity.getQName();
640 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
641 BindingMapping.getClassName(qname));
644 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
645 newType.addImplementsType(gto);
648 newType.addImplementsType(BASE_IDENTITY);
651 final Module module = context.module();
652 addCodegenInformation(newType, module, identity);
653 newType.setModuleName(module.getName());
654 newType.setSchemaPath(identity.getPath());
656 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
657 identity.getQName().getLocalName());
659 context.addIdentityType(identity, newType);
662 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
663 final JavaTypeName yangModuleInfo, final String localName) {
664 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
665 new SimpleImmutableEntry<>(yangModuleInfo, localName));
669 * Converts all <b>groupings</b> of the module to the list of
670 * <code>Type</code> objects. Firstly are groupings sorted according mutual
671 * dependencies. At least dependent (independent) groupings are in the list
672 * saved at first positions. For every grouping the record is added to map
673 * {@link ModuleContext#groupings allGroupings}
678 * collection of groupings from which types will be generated
681 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
682 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
683 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
684 // node of grouping is resolved to the method.
685 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
686 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
687 context.addGroupingType(grouping, genType);
688 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
689 groupingsToGenTypes(context, grouping.getGroupings());
690 processUsesAugments(grouping, context);
691 actionsToGenType(context, genType, grouping, null);
696 * Adds enumeration builder created from <code>enumTypeDef</code> to
697 * <code>typeBuilder</code>.
699 * Each <code>enumTypeDef</code> item is added to builder with its name and
703 * EnumTypeDefinition contains enum data
705 * string contains name which will be assigned to enumeration
708 * GeneratedTypeBuilder to which will be enum builder assigned
710 * Module in which type should be generated
711 * @return enumeration builder which contains data from
712 * <code>enumTypeDef</code>
714 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
715 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
716 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
717 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
718 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
719 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
720 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
727 * Generates type builder for <code>module</code>.
730 * Module which is source of package name for generated type
733 * string which is added to the module class name representation
735 * @return instance of GeneratedTypeBuilder which represents
736 * <code>module</code>.
737 * @throws IllegalArgumentException
738 * if <code>module</code> is null
740 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
741 final Module module = context.module();
742 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
743 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
744 JavaTypeName.create(context.modulePackageName(), moduleName));
746 moduleBuilder.setModuleName(moduleName);
747 addCodegenInformation(moduleBuilder, module);
748 return moduleBuilder;
752 * Converts <code>augSchema</code> to list of <code>Type</code> which
753 * contains generated type for augmentation. In addition there are also
754 * generated types for all containers, list and choices which are child of
755 * <code>augSchema</code> node or a generated types for cases are added if
756 * augmented node is choice.
758 * @param augmentPackageName
759 * string with the name of the package to which the augmentation
762 * AugmentationSchema which is contains data about augmentation
763 * (target path, childs...)
766 * @throws IllegalArgumentException
768 * <li>if <code>augmentPackageName</code> equals null</li>
769 * <li>if <code>augSchema</code> equals null</li>
771 * @throws IllegalStateException
772 * if augment target path is null
774 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
775 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
776 checkState(augSchema.getTargetPath() != null,
777 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
779 processUsesAugments(augSchema, context);
780 final SchemaPath targetPath = augSchema.getTargetPath();
781 SchemaNode targetSchemaNode = null;
783 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
784 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
785 if (targetSchemaNode instanceof DerivableSchemaNode) {
786 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
788 if (targetSchemaNode == null) {
789 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
790 + " in module " + context.module().getName());
793 if (targetSchemaNode == null) {
794 throw new IllegalArgumentException("augment target not found: " + targetPath);
797 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
798 if (targetTypeBuilder == null) {
799 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
801 if (targetTypeBuilder == null) {
802 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
805 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
806 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
807 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
810 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
811 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
815 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
816 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
817 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
818 checkState(augSchema.getTargetPath() != null,
819 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
821 processUsesAugments(augSchema, context);
822 final SchemaPath targetPath = augSchema.getTargetPath();
823 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
824 if (targetSchemaNode == null) {
825 throw new IllegalArgumentException("augment target not found: " + targetPath);
828 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
829 if (targetTypeBuilder == null) {
830 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
832 if (targetTypeBuilder == null) {
833 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
836 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
837 if (usesNodeParent instanceof SchemaNode) {
838 addRawAugmentGenTypeDefinition(context,
839 packageNameForAugmentedGeneratedType(context.modulePackageName(),
840 ((SchemaNode) usesNodeParent).getPath()),
841 targetTypeBuilder.build(), augSchema);
843 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
846 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
847 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
851 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
852 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
854 if (targetGrouping instanceof GroupingDefinition) {
855 return (GroupingDefinition) targetGrouping;
858 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
862 * Convenient method to find node added by uses statement.
866 * @param parentUsesNode
867 * parent of uses node
868 * @return node from its original location in grouping
870 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
871 SchemaNode result = findUsedGrouping(parentUsesNode);
872 for (final QName node : targetPath.getPathFromRoot()) {
873 if (result instanceof DataNodeContainer) {
874 final QName resultNode = node.withModule(result.getQName().getModule());
875 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
876 } else if (result instanceof ChoiceSchemaNode) {
877 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
880 if (result == null) {
884 if (result instanceof DerivableSchemaNode) {
885 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
886 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
887 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
888 result = originalNode.get();
892 if (result instanceof DataSchemaNode) {
893 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
894 if (resultDataSchemaNode.isAddedByUses()) {
895 // The original node is required, but we have only the copy of
896 // the original node.
897 // Maybe this indicates a bug in Yang parser.
898 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
901 return resultDataSchemaNode;
904 throw new IllegalStateException(
905 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
910 * Returns a generated type builder for an augmentation.
912 * The name of the type builder is equal to the name of augmented node with
913 * serial number as suffix.
917 * @param augmentPackageName
918 * string with contains the package name to which the augment
920 * @param basePackageName
921 * string with the package name to which the augmented node
923 * @param targetTypeRef
926 * augmentation schema which contains data about the child nodes
927 * and uses of augment
928 * @return generated type builder for augment
930 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
931 final String augmentPackageName, final Type targetTypeRef,
932 final AugmentationSchemaNode augSchema) {
933 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
934 if (augmentBuilders == null) {
935 augmentBuilders = new HashMap<>();
936 genTypeBuilders.put(augmentPackageName, augmentBuilders);
938 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
941 if (augIdentifier != null) {
942 augTypeName = BindingMapping.getClassName(augIdentifier);
944 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
947 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
948 JavaTypeName.create(augmentPackageName, augTypeName));
950 augTypeBuilder.addImplementsType(DATA_OBJECT);
951 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
952 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
953 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
955 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
956 augmentBuilders.put(augTypeName, augTypeBuilder);
958 if (!augSchema.getChildNodes().isEmpty()) {
959 context.addTypeToAugmentation(augTypeBuilder, augSchema);
962 context.addAugmentType(augTypeBuilder);
963 return augTypeBuilder;
966 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
967 final AugmentationSchemaNode augSchema) {
968 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
973 * @param unknownSchemaNodes
974 * @return nodeParameter of UnknownSchemaNode
976 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
977 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
978 final QName nodeType = unknownSchemaNode.getNodeType();
979 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
980 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
981 return unknownSchemaNode.getNodeParameter();
988 * Returns first unique name for the augment generated type builder. The
989 * generated type builder name for augment consists from name of augmented
990 * node and serial number of its augmentation.
993 * map of builders which were created in the package to which the
994 * augmentation belongs
996 * string with name of augmented node
997 * @return string with unique name for augmentation builder
999 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1001 if (builders != null) {
1002 while (builders.containsKey(genTypeName + index)) {
1006 return genTypeName + index;
1010 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1011 * node for which <code>typeBuilder</code> was created.
1013 * The subnodes aren't mapped to the methods if they are part of grouping or
1014 * augment (in this case are already part of them).
1019 * generated type builder which represents any node. The subnodes
1020 * of this node are added to the <code>typeBuilder</code> as
1021 * methods. The subnode can be of type leaf, leaf-list, list,
1022 * container, choice.
1025 * @param schemaNodes
1026 * set of data schema nodes which are the children of the node
1027 * for which <code>typeBuilder</code> was created
1028 * @return generated type builder which is the same builder as input
1029 * parameter. The getter methods (representing child nodes) could be
1032 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1033 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1034 if (schemaNodes != null && parent != null) {
1035 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1036 for (final DataSchemaNode schemaNode : schemaNodes) {
1037 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1038 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1046 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1047 * node for which <code>typeBuilder</code> was created.
1051 * @param typeBuilder
1052 * generated type builder which represents any node. The subnodes
1053 * of this node are added to the <code>typeBuilder</code> as
1054 * methods. The subnode can be of type leaf, leaf-list, list,
1055 * container, choice.
1058 * @param schemaNodes
1059 * set of data schema nodes which are the children of the node
1060 * for which <code>typeBuilder</code> was created
1061 * @return generated type builder which is the same object as the input
1062 * parameter <code>typeBuilder</code>. The getter method could be
1065 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1066 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1067 if (schemaNodes != null && typeBuilder != null) {
1068 final Type baseInterface = childOf(typeBuilder);
1069 for (final DataSchemaNode schemaNode : schemaNodes) {
1070 if (!schemaNode.isAugmenting()) {
1071 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1079 * Adds to <code>typeBuilder</code> a method which is derived from
1080 * <code>schemaNode</code>.
1083 * data schema node which is added to <code>typeBuilder</code> as
1085 * @param typeBuilder
1086 * generated type builder to which is <code>schemaNode</code>
1087 * added as a method.
1093 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1094 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1095 if (node != null && typeBuilder != null) {
1096 if (node instanceof LeafSchemaNode) {
1097 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1098 } else if (node instanceof LeafListSchemaNode) {
1099 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1100 } else if (node instanceof ContainerSchemaNode) {
1101 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1102 } else if (node instanceof ListSchemaNode) {
1103 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1104 } else if (node instanceof ChoiceSchemaNode) {
1105 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1107 // TODO: anyxml not yet supported
1108 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1109 typeBuilder.getFullyQualifiedName());
1115 * Converts <code>choiceNode</code> to the list of generated types for
1116 * choice and its cases.
1118 * The package names for choice and for its cases are created as
1119 * concatenation of the module package (<code>basePackageName</code>) and
1120 * names of all parents node.
1124 * @param basePackageName
1125 * string with the module package name
1129 * choice node which is mapped to generated type. Also child
1130 * nodes - cases are mapped to generated types.
1131 * @throws IllegalArgumentException
1133 * <li>if <code>basePackageName</code> is null</li>
1134 * <li>if <code>choiceNode</code> is null</li>
1137 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1138 final ChoiceSchemaNode choiceNode) {
1139 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1141 if (!choiceNode.isAddedByUses()) {
1142 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1143 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1144 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1145 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1146 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1147 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1149 final GeneratedType choiceType = choiceTypeBuilder.build();
1150 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1152 constructGetter(parent, choiceType, choiceNode);
1157 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1159 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1160 * The package names for the builder is created as concatenation of the module package and names of all parents
1161 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1162 * and <i>choice</i> type
1165 * current module context
1166 * @param refChoiceType
1167 * type which represents superior <i>case</i>
1169 * choice case node which is mapped to generated type
1170 * @throws IllegalArgumentException
1172 * <li>if <code>refChoiceType</code> equals null</li>
1173 * <li>if <code>caseNodes</code> equals null</li>
1176 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1177 final ChoiceSchemaNode choiceNode) {
1178 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1179 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1181 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1182 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1183 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1184 caseTypeBuilder.addImplementsType(refChoiceType);
1185 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1186 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1187 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1188 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1189 if (caseChildNodes != null) {
1190 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1192 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1193 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1195 if (parent instanceof AugmentationSchemaNode) {
1196 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1197 final SchemaPath targetPath = augSchema.getTargetPath();
1198 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1199 if (targetSchemaNode instanceof DataSchemaNode
1200 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1201 if (targetSchemaNode instanceof DerivableSchemaNode) {
1202 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1205 if (targetSchemaNode == null) {
1206 throw new IllegalStateException(
1207 "Failed to find target node from grouping for augmentation " + augSchema
1208 + " in module " + context.module().getName());
1211 parent = targetSchemaNode;
1214 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1215 Type childOfType = findChildNodeByPath(parent.getPath());
1216 if (childOfType == null) {
1217 childOfType = findGroupingByPath(parent.getPath());
1219 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1221 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1225 processUsesAugments(caseNode, context);
1230 * Generates list of generated types for all the cases of a choice which are
1231 * added to the choice through the augment.
1235 * @param basePackageName
1236 * string contains name of package to which augment belongs. If
1237 * an augmented choice is from an other package (pcg1) than an
1238 * augmenting choice (pcg2) then case's of the augmenting choice
1239 * will belong to pcg2.
1241 * Type which represents target choice
1243 * node which represents target choice
1244 * @param augmentedNodes
1245 * set of choice case nodes for which is checked if are/aren't
1246 * added to choice through augmentation
1247 * @throws IllegalArgumentException
1249 * <li>if <code>basePackageName</code> is null</li>
1250 * <li>if <code>targetType</code> is null</li>
1251 * <li>if <code>augmentedNodes</code> is null</li>
1254 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1255 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1256 final DataNodeContainer usesNodeParent) {
1257 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1258 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1260 for (final DataSchemaNode caseNode : augmentedNodes) {
1261 if (caseNode != null) {
1262 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1263 caseTypeBuilder.addImplementsType(targetType);
1265 CaseSchemaNode node = null;
1266 final String caseLocalName = caseNode.getQName().getLocalName();
1267 if (caseNode instanceof CaseSchemaNode) {
1268 node = (CaseSchemaNode) caseNode;
1269 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1270 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1271 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1272 if (dataSchemaNode instanceof ChoiceSchemaNode
1273 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1274 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1279 node = findNamedCase(targetNode, caseLocalName);
1281 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1282 if (childNodes != null) {
1283 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1285 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1286 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1291 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1292 final SchemaPath nodePath = targetNode.getPath();
1293 final SchemaPath parentSp = nodePath.getParent();
1294 if (parentSp.getParent() == null) {
1295 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1298 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1299 GeneratedTypeBuilder childOfType = null;
1300 if (parent instanceof CaseSchemaNode) {
1301 childOfType = findCaseByPath(parent.getPath());
1302 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1303 childOfType = findChildNodeByPath(parent.getPath());
1304 } else if (parent instanceof GroupingDefinition) {
1305 childOfType = findGroupingByPath(parent.getPath());
1308 if (childOfType == null) {
1309 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1315 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1316 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1317 return cases.isEmpty() ? null : cases.get(0);
1320 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1321 // New parser with encapsulated type
1322 if (leaf.getPath().equals(type.getPath())) {
1326 // Embedded type definition with new parser. Also takes care of the old parser with bits
1327 if (leaf.getPath().equals(type.getPath().getParent())) {
1334 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1335 final List<PatternConstraint> patternConstraints) {
1336 if (!patternConstraints.isEmpty()) {
1337 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1338 .append(BindingMapping.getPropertyName(leafName));
1339 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1340 typeProvider.resolveRegExpressions(patternConstraints));
1345 * Converts <code>leaf</code> to the getter method which is added to
1346 * <code>typeBuilder</code>.
1348 * @param typeBuilder
1349 * generated type builder to which is added getter method as
1350 * <code>leaf</code> mapping
1352 * leaf schema node which is mapped as getter method which is
1353 * added to <code>typeBuilder</code>
1355 * Module in which type was defined
1356 * @return boolean value
1358 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1360 * <li>true - in other cases</li>
1363 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1364 final ModuleContext context) {
1365 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1369 final Module parentModule = findParentModule(schemaContext, leaf);
1370 Type returnType = null;
1372 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1373 if (isInnerType(leaf, typeDef)) {
1374 if (typeDef instanceof EnumTypeDefinition) {
1375 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1376 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1377 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1378 typeBuilder, context);
1379 if (enumBuilder != null) {
1380 returnType = enumBuilder.toInstance(typeBuilder);
1382 typeProvider.putReferencedType(leaf.getPath(), returnType);
1383 } else if (typeDef instanceof UnionTypeDefinition) {
1384 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1386 if (genTOBuilder != null) {
1387 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1388 // Store the inner type within the union so that we can find the reference for it
1389 context.addInnerTypedefType(typeDef.getPath(), returnType);
1391 } else if (typeDef instanceof BitsTypeDefinition) {
1392 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1394 if (genTOBuilder != null) {
1395 returnType = genTOBuilder.build();
1398 // It is constrained version of already declared type (inner declared type exists,
1399 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1400 // In order to get proper class we need to look up closest derived type
1401 // and apply restrictions from leaf type
1402 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1403 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1405 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1408 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1409 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1410 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1413 if (returnType == null) {
1417 if (typeDef instanceof EnumTypeDefinition) {
1418 typeProvider.putReferencedType(leaf.getPath(), returnType);
1421 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1422 processContextRefExtension(leaf, getter, parentModule);
1426 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1427 // Returns DerivedType in case of new parser.
1428 final TypeDefinition<?> baseType = typeDef.getBaseType();
1429 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1432 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1433 final Module module) {
1434 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1435 final QName nodeType = node.getNodeType();
1436 if ("context-reference".equals(nodeType.getLocalName())) {
1437 final String nodeParam = node.getNodeParameter();
1438 IdentitySchemaNode identity = null;
1439 String basePackageName = null;
1440 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1441 final Iterator<String> iterator = splittedElement.iterator();
1442 final int length = Iterables.size(splittedElement);
1444 identity = findIdentityByName(module.getIdentities(), iterator.next());
1445 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1446 } else if (length == 2) {
1447 final String prefix = iterator.next();
1448 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1449 if (dependentModule == null) {
1450 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1453 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1454 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1456 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1459 if (identity == null) {
1460 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1464 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1465 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1466 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1467 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1472 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1473 for (final IdentitySchemaNode id : identities) {
1474 if (id.getQName().getLocalName().equals(name)) {
1481 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1482 for (final ModuleImport imp : imports) {
1483 if (imp.getPrefix().equals(prefix)) {
1484 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1490 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1491 final boolean isReadOnly) {
1492 if (leaf != null && toBuilder != null) {
1494 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1495 if (typeDef instanceof UnionTypeDefinition) {
1496 // GeneratedType for this type definition should have be already created
1497 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1498 returnType = mc.getTypedefs().get(typeDef.getPath());
1499 if (returnType == null) {
1500 // This may still be an inner type, try to find it
1501 returnType = mc.getInnerType(typeDef.getPath());
1503 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1504 // Annonymous enumeration (already generated, since it is inherited via uses).
1505 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1506 QName qname = originalLeaf.getQName();
1507 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1509 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1511 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1517 * Converts <code>leaf</code> schema node to property of generated TO
1521 * generated TO builder to which is <code>leaf</code> added as
1524 * leaf schema node which is added to <code>toBuilder</code> as
1529 * boolean value which says if leaf property is|isn't read only
1530 * @return boolean value
1532 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1533 * name equals null or if leaf is added by <i>uses</i>.</li>
1534 * <li>true - other cases</li>
1537 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1538 final Type returnType, final boolean isReadOnly) {
1539 if (returnType == null) {
1542 final String leafName = leaf.getQName().getLocalName();
1543 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1544 propBuilder.setReadOnly(isReadOnly);
1545 propBuilder.setReturnType(returnType);
1546 addComment(propBuilder, leaf);
1548 toBuilder.addEqualsIdentity(propBuilder);
1549 toBuilder.addHashIdentity(propBuilder);
1550 toBuilder.addToStringProperty(propBuilder);
1555 * Converts <code>node</code> leaf list schema node to getter method of
1556 * <code>typeBuilder</code>.
1558 * @param typeBuilder
1559 * generated type builder to which is <code>node</code> added as
1562 * leaf list schema node which is added to
1563 * <code>typeBuilder</code> as getter method
1564 * @param module module
1565 * @return boolean value
1567 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1568 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1569 * <li>false - other cases</li>
1572 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1573 final ModuleContext context) {
1574 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1578 final QName nodeName = node.getQName();
1580 final TypeDefinition<?> typeDef = node.getType();
1581 final Module parentModule = findParentModule(schemaContext, node);
1583 Type returnType = null;
1584 if (typeDef.getBaseType() == null) {
1585 if (typeDef instanceof EnumTypeDefinition) {
1586 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1587 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1588 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1589 typeBuilder, context);
1590 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1591 typeProvider.putReferencedType(node.getPath(), returnType);
1592 } else if (typeDef instanceof UnionTypeDefinition) {
1593 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1594 node, parentModule);
1595 if (genTOBuilder != null) {
1596 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1598 } else if (typeDef instanceof BitsTypeDefinition) {
1599 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1600 node, parentModule);
1601 returnType = genTOBuilder.build();
1603 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1604 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1605 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1608 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1609 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1610 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1613 final ParameterizedType listType = listTypeFor(returnType);
1614 constructGetter(typeBuilder, listType, node);
1618 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1619 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1620 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1622 addCodegenInformation(returnType, parentModule, typeDef);
1623 returnType.setSchemaPath(typeDef.getPath());
1624 returnType.setModuleName(parentModule.getName());
1626 genTOBuilder.setTypedef(true);
1627 genTOBuilder.setIsUnion(true);
1628 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1632 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1635 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1636 method.setReturnType(returnType);
1637 method.addParameter(Types.STRING, "defaultValue");
1638 method.setAccessModifier(AccessModifier.PUBLIC);
1639 method.setStatic(true);
1641 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1642 if (types == null) {
1643 typeProvider.getAdditionalTypes().put(parentModule,
1644 Sets.newHashSet(unionBuilder.build()));
1646 types.add(unionBuilder.build());
1648 return returnType.build();
1651 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1652 final GeneratedTypeBuilder typeBuilder) {
1653 // Append enclosing path hierarchy without dots
1654 final StringBuilder sb = new StringBuilder();
1655 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1656 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1657 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1658 unionBuilder.setIsUnionBuilder(true);
1659 return unionBuilder;
1662 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1663 final SchemaNode schemaNode) {
1664 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1667 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1668 final SchemaNode schemaNode, final Type baseInterface) {
1669 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1670 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1675 * Instantiates generated type builder with <code>packageName</code> and
1676 * <code>schemaNode</code>.
1678 * The new builder always implements
1679 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1680 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1681 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1683 * If <code>schemaNode</code> is instance of
1684 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1685 * DataNodeContainer} it can also implement nodes which are specified in
1688 * @param packageName
1689 * string with the name of the package to which
1690 * <code>schemaNode</code> belongs.
1692 * schema node for which is created generated type builder
1694 * parent type (can be null)
1695 * @return generated type builder <code>schemaNode</code>
1697 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1698 final Type baseInterface, final ModuleContext context) {
1699 JavaTypeName name = renames.get(schemaNode);
1701 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1704 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1706 it.addImplementsType(baseInterface);
1707 if (!(schemaNode instanceof GroupingDefinition)) {
1708 it.addImplementsType(augmentable(it));
1710 if (schemaNode instanceof DataNodeContainer) {
1711 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1712 groupingsToGenTypes(context, containerSchema.getGroupings());
1713 addImplementedInterfaceFromUses(containerSchema, it);
1720 * Wraps the calling of the same overloaded method.
1722 * @param packageName
1723 * string with the package name to which returning generated type
1726 * schema node which provide data about the schema node name
1727 * @return generated type builder for <code>schemaNode</code>
1729 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1730 final String prefix) {
1731 return addRawInterfaceDefinition(
1732 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1733 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1737 * Returns reference to generated type builder for specified
1738 * <code>schemaNode</code> with <code>packageName</code>.
1740 * Firstly the generated type builder is searched in
1741 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1742 * found it is created and added to <code>genTypeBuilders</code>.
1744 * @param packageName
1745 * string with the package name to which returning generated type
1748 * schema node which provide data about the schema node name
1750 * return type name prefix
1751 * @return generated type builder for <code>schemaNode</code>
1752 * @throws IllegalArgumentException
1754 * <li>if <code>schemaNode</code> is null</li>
1755 * <li>if <code>packageName</code> is null</li>
1756 * <li>if QName of schema node is null</li>
1757 * <li>if schemaNode name is null</li>
1761 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1762 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1763 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1764 final String schemaNodeName = schemaNode.getQName().getLocalName();
1765 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1767 // FIXME: Validation of name conflict
1768 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1769 final Module module = findParentModule(schemaContext, schemaNode);
1770 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1771 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1773 addCodegenInformation(newType, module, schemaNode);
1774 newType.setSchemaPath(schemaNode.getPath());
1775 newType.setModuleName(module.getName());
1777 final String packageName = identifier.packageName();
1778 final String simpleName = identifier.simpleName();
1779 if (!genTypeBuilders.containsKey(packageName)) {
1780 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1781 builders.put(simpleName, newType);
1782 genTypeBuilders.put(packageName, builders);
1784 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1785 if (!builders.containsKey(simpleName)) {
1786 builders.put(simpleName, newType);
1793 * Creates the name of the getter method name from <code>localName</code>.
1796 * string with the name of the getter method
1799 * @return string with the name of the getter method for
1800 * <code>methodName</code> in JAVA method format
1802 public static String getterMethodName(final String localName, final Type returnType) {
1803 final StringBuilder method = new StringBuilder();
1804 if (BOOLEAN.equals(returnType)) {
1805 method.append("is");
1807 method.append("get");
1809 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1810 method.append(name);
1811 return method.toString();
1815 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1817 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1818 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1820 * @param interfaceBuilder generated type builder for which the getter method should be created
1821 * @param returnType type which represents the return type of the getter method
1822 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1823 * @param comment string with comment for the getter method
1824 * @param status status from yang file, for deprecated annotation
1825 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1827 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1828 final SchemaNode node) {
1829 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1830 getterMethodName(node.getQName().getLocalName(), returnType));
1831 getMethod.setReturnType(returnType);
1833 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1834 if (!returnType.getPackageName().isEmpty()) {
1835 // The return type has a package, so it's not a primitive type
1836 getMethod.addAnnotation("javax.annotation", "Nullable");
1838 addComment(getMethod, node);
1844 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1845 * or to <code>genTOBuilder</code> as property.
1847 * @param basePackageName
1848 * string contains the module package name
1850 * data schema node which should be added as getter method to
1851 * <code>typeBuilder</code> or as a property to
1852 * <code>genTOBuilder</code> if is part of the list key
1853 * @param typeBuilder
1854 * generated type builder for the list schema node
1855 * @param genTOBuilder
1856 * generated TO builder for the list keys
1858 * list of string which contains names of the list keys
1861 * @throws IllegalArgumentException
1863 * <li>if <code>schemaNode</code> equals null</li>
1864 * <li>if <code>typeBuilder</code> equals null</li>
1867 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1868 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1869 final List<String> listKeys) {
1870 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1871 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1873 if (schemaNode instanceof LeafSchemaNode) {
1874 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1875 final String leafName = leaf.getQName().getLocalName();
1876 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1877 if (listKeys.contains(leafName)) {
1879 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1881 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1884 } else if (!schemaNode.isAddedByUses()) {
1885 if (schemaNode instanceof LeafListSchemaNode) {
1886 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1887 } else if (schemaNode instanceof ContainerSchemaNode) {
1888 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1889 (ContainerSchemaNode) schemaNode);
1890 } else if (schemaNode instanceof ChoiceSchemaNode) {
1891 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1892 } else if (schemaNode instanceof ListSchemaNode) {
1893 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1898 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1899 final GeneratedTOBuilder genTOBuilder) {
1900 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1902 if (genTOBuilder != null) {
1903 final GeneratedTransferObject genTO = genTOBuilder.build();
1904 // Add Identifiable.getKey() for items
1905 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1906 .addAnnotation(OVERRIDE_ANNOTATION);
1907 context.addGeneratedTOBuilder(genTOBuilder);
1912 * Selects the names of the list keys from <code>list</code> and returns
1913 * them as the list of the strings
1916 * of string with names of the list keys
1917 * @return list of string which represents names of the list keys. If the
1918 * <code>list</code> contains no keys then the empty list is
1921 private static List<String> listKeys(final ListSchemaNode list) {
1922 final List<String> listKeys = new ArrayList<>();
1924 final List<QName> keyDefinition = list.getKeyDefinition();
1925 if (keyDefinition != null) {
1926 for (final QName keyDef : keyDefinition) {
1927 listKeys.add(keyDef.getLocalName());
1934 * Generates for the <code>list</code> which contains any list keys special
1935 * generated TO builder.
1937 * @param packageName
1938 * string with package name to which the list belongs
1940 * list schema node which is source of data about the list name
1941 * @return generated TO builder which represents the keys of the
1942 * <code>list</code> or null if <code>list</code> is null or list of
1943 * key definitions is null or empty.
1945 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1946 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1947 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1948 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1949 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1955 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1957 * If more then one generated TO builder is created for enclosing then all
1958 * of the generated TO builders are added to <code>typeBuilder</code> as
1959 * enclosing transfer objects.
1962 * type definition which can be of type <code>UnionType</code> or
1963 * <code>BitsTypeDefinition</code>
1964 * @param typeBuilder
1965 * generated type builder to which is added generated TO created
1966 * from <code>typeDef</code>
1968 * string with name for generated TO builder
1969 * @param parentModule
1971 * @return generated TO builder for <code>typeDef</code>
1973 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1974 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1975 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1976 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1979 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1980 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1981 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1982 for (final GeneratedTOBuilder genTOBuilder : types) {
1983 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1986 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1987 return resultTOBuilder;
1991 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1992 * also added to <code>typeBuilder</code> as enclosing transfer object.
1994 * If more then one generated TO builder is created for enclosing then all
1995 * of the generated TO builders are added to <code>typeBuilder</code> as
1996 * enclosing transfer objects.
1999 * type definition which can be of type <code>UnionType</code> or
2000 * <code>BitsTypeDefinition</code>
2001 * @param typeBuilder
2002 * generated type builder to which is added generated TO created
2003 * from <code>typeDef</code>
2005 * string with name for generated TO builder
2006 * @param parentModule
2008 * @return generated TO builder for <code>typeDef</code>
2010 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
2011 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2012 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
2013 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
2014 typeDef, parentModule.getName());
2015 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2016 return genTOBuilder;
2020 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
2021 final List<GeneratedTOBuilder> genTOBuilders) {
2022 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2023 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2025 return genTOBuilders.get(0);
2029 * Adds the implemented types to type builder.
2031 * The method passes through the list of <i>uses</i> in
2032 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2033 * generated type from {@link ModuleContext#groupings
2034 * allGroupings} which is added as <i>implements type</i> to
2035 * <code>builder</code>
2037 * @param dataNodeContainer
2038 * element which contains the list of used YANG groupings
2040 * builder to which are added implemented types according to
2041 * <code>dataNodeContainer</code>
2042 * @return generated type builder with all implemented types
2044 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2045 final GeneratedTypeBuilder builder) {
2046 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2047 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2048 if (genType == null) {
2049 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2050 + builder.getName());
2053 builder.addImplementsType(genType);
2058 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2059 for (final ModuleContext ctx : genCtx.values()) {
2060 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2061 if (result != null) {
2068 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2069 for (final ModuleContext ctx : genCtx.values()) {
2070 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2071 if (result != null) {
2078 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2079 for (final ModuleContext ctx : genCtx.values()) {
2080 final GeneratedTypeBuilder result = ctx.getCase(path);
2081 if (result != null) {
2088 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2089 if (status == Status.DEPRECATED) {
2090 builder.addAnnotation(DEPRECATED_ANNOTATION);