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_SERVICE;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
30 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
31 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
32 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
33 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
34 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
35 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
37 import com.google.common.base.Splitter;
38 import com.google.common.collect.Iterables;
39 import com.google.common.collect.Sets;
40 import java.util.AbstractMap.SimpleImmutableEntry;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.Comparator;
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.List;
48 import java.util.Optional;
50 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
51 import org.opendaylight.mdsal.binding.model.api.Constant;
52 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
53 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
54 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
55 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
56 import org.opendaylight.mdsal.binding.model.api.Restrictions;
57 import org.opendaylight.mdsal.binding.model.api.Type;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
67 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
68 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
69 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
70 import org.opendaylight.mdsal.binding.model.util.Types;
71 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
72 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
73 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
74 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
75 import org.opendaylight.yangtools.yang.binding.BindingMapping;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.QNameModule;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
105 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
107 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
113 abstract class AbstractTypeGenerator {
114 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
115 private static final Splitter COLON_SPLITTER = Splitter.on(':');
116 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
117 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
120 * Comparator based on augment target path.
122 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
123 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
124 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
126 while (thisIt.hasNext()) {
127 if (!otherIt.hasNext()) {
131 final int comp = thisIt.next().compareTo(otherIt.next());
137 return otherIt.hasNext() ? -1 : 0;
141 * Constant with the concrete name of identifier.
143 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
146 * Constant with the concrete name of namespace.
148 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
150 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
153 * Outer key represents the package name. Outer value represents map of all
154 * builders in the same package. Inner key represents the schema node name
155 * (in JAVA class/interface name format). Inner value represents instance of
156 * builder for schema node specified in key part.
158 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
161 * Provide methods for converting YANG types to JAVA types.
163 private final AbstractTypeProvider typeProvider;
166 * Holds reference to schema context to resolve data of augmented element
167 * when creating augmentation builder
169 private final SchemaContext schemaContext;
171 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
172 this.schemaContext = requireNonNull(context);
173 this.typeProvider = requireNonNull(typeProvider);
175 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
176 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
177 for (final Module contextModule : contextModules) {
178 contexts.add(moduleToGenTypes(contextModule));
181 contexts.forEach(this::allAugmentsToGenTypes);
184 final Collection<ModuleContext> moduleContexts() {
185 return genCtx.values();
188 final ModuleContext moduleContext(final QNameModule module) {
189 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
192 final AbstractTypeProvider typeProvider() {
196 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
198 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
200 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
201 Set<? extends SchemaNode> nodes);
203 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
205 private ModuleContext moduleToGenTypes(final Module module) {
206 final ModuleContext context = new ModuleContext(module);
207 genCtx.put(module.getQNameModule(), context);
208 allTypeDefinitionsToGenTypes(context);
209 groupingsToGenTypes(context, module.getGroupings());
210 rpcMethodsToGenType(context);
211 allIdentitiesToGenTypes(context);
212 notificationsToGenType(context);
214 if (!module.getChildNodes().isEmpty()) {
215 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
216 context.addModuleNode(moduleType);
217 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
223 * Converts all extended type definitions of module to the list of
224 * <code>Type</code> objects.
227 * module from which is obtained set of type definitions
228 * @throws IllegalArgumentException
230 * <li>if module is null</li>
231 * <li>if name of module is null</li>
233 * @throws IllegalStateException
234 * if set of type definitions from module is null
236 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
237 final Module module = context.module();
238 checkArgument(module.getName() != null, "Module name cannot be NULL.");
239 final DataNodeIterator it = new DataNodeIterator(module);
240 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
241 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
243 for (final TypeDefinition<?> typedef : typeDefinitions) {
244 if (typedef != null) {
245 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
247 context.addTypedefType(typedef.getPath(), type);
248 context.addTypeToSchema(type,typedef);
254 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type childOf,
255 final DataSchemaNode node) {
256 if (node.isAugmenting() || node.isAddedByUses()) {
259 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
260 annotateDeprecatedIfNecessary(node.getStatus(), genType);
262 final Module module = context.module();
263 genType.setModuleName(module.getName());
264 addCodegenInformation(genType, module, node);
265 genType.setSchemaPath(node.getPath());
266 if (node instanceof DataNodeContainer) {
267 context.addChildNodeType(node, genType);
268 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
269 processUsesAugments((DataNodeContainer) node, context);
274 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
275 final Type childOf, final ContainerSchemaNode node) {
276 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
277 if (genType != null) {
278 constructGetter(parent, genType, node);
279 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
283 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent, final Type childOf,
284 final ListSchemaNode node) {
285 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
286 if (genType != null) {
287 constructGetter(parent, Types.listTypeFor(genType), node);
289 final List<String> listKeys = listKeys(node);
290 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
291 if (genTOBuilder != null) {
292 final Type identifierMarker = identifier(genType);
293 final Type identifiableMarker = identifiable(genTOBuilder);
294 genTOBuilder.addImplementsType(identifierMarker);
295 genType.addImplementsType(identifiableMarker);
298 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
299 if (!schemaNode.isAugmenting()) {
300 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
305 if (genTOBuilder != null) {
306 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
307 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
308 genTOBuilder.setSUID(prop);
311 typeBuildersToGenTypes(context, genType, genTOBuilder);
315 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
316 for (final UsesNode usesNode : node.getUses()) {
317 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
318 usesAugmentationToGenTypes(context, augment, usesNode, node);
319 processUsesAugments(augment, context);
325 * Converts all <b>augmentation</b> of the module to the list
326 * <code>Type</code> objects.
329 * module from which is obtained list of all augmentation objects
330 * to iterate over them
331 * @throws IllegalArgumentException
333 * <li>if the module is null</li>
334 * <li>if the name of module is null</li>
336 * @throws IllegalStateException
337 * if set of augmentations from module is null
339 private void allAugmentsToGenTypes(final ModuleContext context) {
340 final Module module = context.module();
341 checkArgument(module != null, "Module reference cannot be NULL.");
342 checkArgument(module.getName() != null, "Module name cannot be NULL.");
343 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
345 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
346 augmentationToGenTypes(context, augment);
351 * Returns list of <code>AugmentationSchema</code> objects. The objects are
352 * sorted according to the length of their target path from the shortest to
356 * module from which is obtained list of all augmentation objects
357 * @return list of sorted <code>AugmentationSchema</code> objects obtained
358 * from <code>module</code>
359 * @throws IllegalArgumentException
361 * @throws IllegalStateException
362 * if set of module augmentations is null
364 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
365 checkArgument(module != null, "Module reference cannot be NULL.");
366 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
368 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
369 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
370 sortedAugmentations.sort(AUGMENT_COMP);
372 return sortedAugmentations;
376 * Create GeneratedTypeBuilder object from module argument.
379 * Module object from which builder will be created
380 * @return <code>GeneratedTypeBuilder</code> which is internal
381 * representation of the module
382 * @throws IllegalArgumentException
385 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
386 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
387 final Module module = context.module();
388 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
389 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
391 addCodegenInformation(moduleDataTypeBuilder, module);
392 return moduleDataTypeBuilder;
396 * Converts all <b>RPCs</b> input and output substatements of the module
397 * to the list of <code>Type</code> objects. In addition are to containers
398 * and lists which belong to input or output also part of returning list.
401 * module from which is obtained set of all rpc objects to
403 * @throws IllegalArgumentException
405 * <li>if the module is null</li>
406 * <li>if the name of module is null</li>
408 * @throws IllegalStateException
409 * if set of rpcs from module is null
411 private void rpcMethodsToGenType(final ModuleContext context) {
412 final Module module = context.module();
413 checkArgument(module.getName() != null, "Module name cannot be NULL.");
414 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
415 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
416 if (rpcDefinitions.isEmpty()) {
420 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
421 interfaceBuilder.addImplementsType(RPC_SERVICE);
423 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
425 for (final RpcDefinition rpc : rpcDefinitions) {
427 final String rpcName = BindingMapping.getClassName(rpc.getQName());
428 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
429 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
431 // Do not refer to annotation class, as it may not be available at runtime
432 method.addAnnotation("javax.annotation", "CheckReturnValue");
433 addComment(method, rpc);
435 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
436 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
437 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
441 context.addTopLevelNodeType(interfaceBuilder);
444 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
445 final ContainerSchemaNode schema) {
446 processUsesAugments(schema, context);
447 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
448 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
450 addImplementedInterfaceFromUses(schema, outType);
451 outType.addImplementsType(DATA_OBJECT);
452 outType.addImplementsType(augmentable(outType));
453 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
454 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
455 context.addChildNodeType(schema, outType);
456 return outType.build();
460 * Converts all <b>notifications</b> of the module to the list of
461 * <code>Type</code> objects. In addition are to this list added containers
462 * and lists which are part of this notification.
465 * module from which is obtained set of all notification objects
466 * to iterate over them
467 * @throws IllegalArgumentException
469 * <li>if the module equals null</li>
470 * <li>if the name of module equals null</li>
472 * @throws IllegalStateException
473 * if set of notifications from module is null
475 private void notificationsToGenType(final ModuleContext context) {
476 final Module module = context.module();
477 checkArgument(module.getName() != null, "Module name cannot be NULL.");
478 final Set<NotificationDefinition> notifications = module.getNotifications();
479 if (notifications.isEmpty()) {
483 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
484 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
486 for (final NotificationDefinition notification : notifications) {
487 if (notification != null) {
488 processUsesAugments(notification, context);
490 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
491 context.modulePackageName(), notification, null, context);
492 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
493 notificationInterface.addImplementsType(NOTIFICATION);
494 context.addChildNodeType(notification, notificationInterface);
496 // Notification object
497 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
498 notification.getChildNodes());
500 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
501 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
502 .setReturnType(Types.primitiveVoidType()), notification);
506 addCodegenInformation(listenerInterface, module, "notifications", notifications);
507 context.addTopLevelNodeType(listenerInterface);
511 * Converts all <b>identities</b> of the module to the list of
512 * <code>Type</code> objects.
515 * module from which is obtained set of all identity objects to
517 * @param schemaContext
518 * schema context only used as input parameter for method
519 * {@link BindingGeneratorImpl#identityToGenType}
522 private void allIdentitiesToGenTypes(final ModuleContext context) {
523 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
525 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
526 for (final IdentitySchemaNode identity : schemaIdentities) {
527 identityToGenType(context, identity);
533 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
534 * created transport object builder. If identity contains base identity then
535 * reference to base identity is added to superior identity as its extend.
536 * If identity doesn't contain base identity then only reference to abstract
537 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
538 * BaseIdentity} is added
542 * @param basePackageName
543 * string contains the module package name
545 * IdentitySchemaNode which contains data about identity
547 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
548 if (identity == null) {
551 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
552 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
553 BindingMapping.getClassName(identity.getQName())));
554 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
555 if (!baseIdentities.isEmpty()) {
556 for (IdentitySchemaNode baseIdentity : baseIdentities) {
557 final QName qname = baseIdentity.getQName();
558 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
559 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
560 newType.addImplementsType(gto);
563 newType.addImplementsType(BASE_IDENTITY);
566 final Module module = context.module();
567 addCodegenInformation(newType, module, identity);
568 newType.setModuleName(module.getName());
569 newType.setSchemaPath(identity.getPath());
571 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
572 identity.getQName().getLocalName());
574 context.addIdentityType(identity.getQName(), newType);
577 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
578 final JavaTypeName yangModuleInfo, final String localName) {
579 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
580 new SimpleImmutableEntry<>(yangModuleInfo, localName));
584 * Converts all <b>groupings</b> of the module to the list of
585 * <code>Type</code> objects. Firstly are groupings sorted according mutual
586 * dependencies. At least dependent (independent) groupings are in the list
587 * saved at first positions. For every grouping the record is added to map
588 * {@link ModuleContext#groupings allGroupings}
593 * collection of groupings from which types will be generated
596 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
597 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
598 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
599 // node of grouping is resolved to the method.
600 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
601 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
602 context.addGroupingType(grouping.getPath(), genType);
603 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
604 groupingsToGenTypes(context, grouping.getGroupings());
605 processUsesAugments(grouping, context);
610 * Adds enumeration builder created from <code>enumTypeDef</code> to
611 * <code>typeBuilder</code>.
613 * Each <code>enumTypeDef</code> item is added to builder with its name and
617 * EnumTypeDefinition contains enum data
619 * string contains name which will be assigned to enumeration
622 * GeneratedTypeBuilder to which will be enum builder assigned
624 * Module in which type should be generated
625 * @return enumeration builder which contains data from
626 * <code>enumTypeDef</code>
628 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
629 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
630 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
631 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
632 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
633 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
634 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
641 * Generates type builder for <code>module</code>.
644 * Module which is source of package name for generated type
647 * string which is added to the module class name representation
649 * @return instance of GeneratedTypeBuilder which represents
650 * <code>module</code>.
651 * @throws IllegalArgumentException
652 * if <code>module</code> is null
654 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
655 final Module module = context.module();
656 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
657 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
658 JavaTypeName.create(context.modulePackageName(), moduleName));
660 moduleBuilder.setModuleName(moduleName);
661 addCodegenInformation(moduleBuilder, module);
662 return moduleBuilder;
666 * Converts <code>augSchema</code> to list of <code>Type</code> which
667 * contains generated type for augmentation. In addition there are also
668 * generated types for all containers, list and choices which are child of
669 * <code>augSchema</code> node or a generated types for cases are added if
670 * augmented node is choice.
672 * @param augmentPackageName
673 * string with the name of the package to which the augmentation
676 * AugmentationSchema which is contains data about augmentation
677 * (target path, childs...)
680 * @throws IllegalArgumentException
682 * <li>if <code>augmentPackageName</code> equals null</li>
683 * <li>if <code>augSchema</code> equals null</li>
685 * @throws IllegalStateException
686 * if augment target path is null
688 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
689 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
690 checkState(augSchema.getTargetPath() != null,
691 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
693 processUsesAugments(augSchema, context);
694 final SchemaPath targetPath = augSchema.getTargetPath();
695 SchemaNode targetSchemaNode = null;
697 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
698 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
699 if (targetSchemaNode instanceof DerivableSchemaNode) {
700 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
702 if (targetSchemaNode == null) {
703 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
704 + " in module " + context.module().getName());
707 if (targetSchemaNode == null) {
708 throw new IllegalArgumentException("augment target not found: " + targetPath);
711 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
712 if (targetTypeBuilder == null) {
713 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
715 if (targetTypeBuilder == null) {
716 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
719 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
720 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
721 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
724 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
725 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
729 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
730 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
731 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
732 checkState(augSchema.getTargetPath() != null,
733 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
735 processUsesAugments(augSchema, context);
736 final SchemaPath targetPath = augSchema.getTargetPath();
737 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
738 if (targetSchemaNode == null) {
739 throw new IllegalArgumentException("augment target not found: " + targetPath);
742 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
743 if (targetTypeBuilder == null) {
744 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
746 if (targetTypeBuilder == null) {
747 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
750 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
751 if (usesNodeParent instanceof SchemaNode) {
752 addRawAugmentGenTypeDefinition(context,
753 packageNameForAugmentedGeneratedType(context.modulePackageName(),
754 ((SchemaNode) usesNodeParent).getPath()),
755 targetTypeBuilder.build(), augSchema);
757 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
760 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
761 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
766 * Convenient method to find node added by uses statement.
770 * @param parentUsesNode
771 * parent of uses node
772 * @return node from its original location in grouping
774 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
775 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
777 if (!(targetGrouping instanceof GroupingDefinition)) {
778 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
781 SchemaNode result = targetGrouping;
782 for (final QName node : targetPath.getPathFromRoot()) {
783 if (result instanceof DataNodeContainer) {
784 final QName resultNode = node.withModule(result.getQName().getModule());
785 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
786 } else if (result instanceof ChoiceSchemaNode) {
787 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
790 if (result == null) {
794 if (result instanceof DerivableSchemaNode) {
795 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
796 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
797 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
798 result = originalNode.get();
802 if (result instanceof DataSchemaNode) {
803 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
804 if (resultDataSchemaNode.isAddedByUses()) {
805 // The original node is required, but we have only the copy of
806 // the original node.
807 // Maybe this indicates a bug in Yang parser.
808 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
811 return resultDataSchemaNode;
814 throw new IllegalStateException(
815 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
820 * Returns a generated type builder for an augmentation.
822 * The name of the type builder is equal to the name of augmented node with
823 * serial number as suffix.
827 * @param augmentPackageName
828 * string with contains the package name to which the augment
830 * @param basePackageName
831 * string with the package name to which the augmented node
833 * @param targetTypeRef
836 * augmentation schema which contains data about the child nodes
837 * and uses of augment
838 * @return generated type builder for augment
840 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
841 final String augmentPackageName, final Type targetTypeRef,
842 final AugmentationSchemaNode augSchema) {
843 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
844 if (augmentBuilders == null) {
845 augmentBuilders = new HashMap<>();
846 genTypeBuilders.put(augmentPackageName, augmentBuilders);
848 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
851 if (augIdentifier != null) {
852 augTypeName = BindingMapping.getClassName(augIdentifier);
854 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
857 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
858 JavaTypeName.create(augmentPackageName, augTypeName));
860 augTypeBuilder.addImplementsType(DATA_OBJECT);
861 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
862 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
863 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
865 augSchemaNodeToMethods(context, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
866 augmentBuilders.put(augTypeName, augTypeBuilder);
868 if (!augSchema.getChildNodes().isEmpty()) {
869 context.addTypeToAugmentation(augTypeBuilder, augSchema);
872 context.addAugmentType(augTypeBuilder);
873 return augTypeBuilder;
876 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
877 final AugmentationSchemaNode augSchema) {
878 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
883 * @param unknownSchemaNodes
884 * @return nodeParameter of UnknownSchemaNode
886 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
887 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
888 final QName nodeType = unknownSchemaNode.getNodeType();
889 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
890 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
891 return unknownSchemaNode.getNodeParameter();
898 * Returns first unique name for the augment generated type builder. The
899 * generated type builder name for augment consists from name of augmented
900 * node and serial number of its augmentation.
903 * map of builders which were created in the package to which the
904 * augmentation belongs
906 * string with name of augmented node
907 * @return string with unique name for augmentation builder
909 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
911 if (builders != null) {
912 while (builders.containsKey(genTypeName + index)) {
916 return genTypeName + index;
920 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
921 * node for which <code>typeBuilder</code> was created.
923 * The subnodes aren't mapped to the methods if they are part of grouping or
924 * augment (in this case are already part of them).
929 * generated type builder which represents any node. The subnodes
930 * of this node are added to the <code>typeBuilder</code> as
931 * methods. The subnode can be of type leaf, leaf-list, list,
936 * set of data schema nodes which are the children of the node
937 * for which <code>typeBuilder</code> was created
938 * @return generated type builder which is the same builder as input
939 * parameter. The getter methods (representing child nodes) could be
942 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
943 final Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
944 if (schemaNodes != null && parent != null) {
945 for (final DataSchemaNode schemaNode : schemaNodes) {
946 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
947 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
955 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
956 * node for which <code>typeBuilder</code> was created.
961 * generated type builder which represents any node. The subnodes
962 * of this node are added to the <code>typeBuilder</code> as
963 * methods. The subnode can be of type leaf, leaf-list, list,
968 * set of data schema nodes which are the children of the node
969 * for which <code>typeBuilder</code> was created
970 * @return generated type builder which is the same object as the input
971 * parameter <code>typeBuilder</code>. The getter method could be
974 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
975 final GeneratedTypeBuilder typeBuilder, final Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
976 if (schemaNodes != null && typeBuilder != null) {
977 for (final DataSchemaNode schemaNode : schemaNodes) {
978 if (!schemaNode.isAugmenting()) {
979 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
987 * Adds to <code>typeBuilder</code> a method which is derived from
988 * <code>schemaNode</code>.
991 * data schema node which is added to <code>typeBuilder</code> as
994 * generated type builder to which is <code>schemaNode</code>
1001 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1002 final GeneratedTypeBuilder typeBuilder, final Type childOf) {
1003 if (node != null && typeBuilder != null) {
1004 if (node instanceof LeafSchemaNode) {
1005 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1006 } else if (node instanceof LeafListSchemaNode) {
1007 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1008 } else if (node instanceof ContainerSchemaNode) {
1009 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1010 } else if (node instanceof ListSchemaNode) {
1011 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1012 } else if (node instanceof ChoiceSchemaNode) {
1013 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1015 // TODO: anyxml not yet supported
1016 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1017 typeBuilder.getFullyQualifiedName());
1023 * Converts <code>choiceNode</code> to the list of generated types for
1024 * choice and its cases.
1026 * The package names for choice and for its cases are created as
1027 * concatenation of the module package (<code>basePackageName</code>) and
1028 * names of all parents node.
1032 * @param basePackageName
1033 * string with the module package name
1037 * choice node which is mapped to generated type. Also child
1038 * nodes - cases are mapped to generated types.
1039 * @throws IllegalArgumentException
1041 * <li>if <code>basePackageName</code> is null</li>
1042 * <li>if <code>choiceNode</code> is null</li>
1045 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1046 final ChoiceSchemaNode choiceNode) {
1047 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1049 if (!choiceNode.isAddedByUses()) {
1050 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1051 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1052 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1053 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1054 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1055 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1057 final GeneratedType choiceType = choiceTypeBuilder.build();
1058 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1060 constructGetter(parent, choiceType, choiceNode);
1065 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1067 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1068 * The package names for the builder is created as concatenation of the module package and names of all parents
1069 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1070 * and <i>choice</i> type
1073 * current module context
1074 * @param refChoiceType
1075 * type which represents superior <i>case</i>
1077 * choice case node which is mapped to generated type
1078 * @throws IllegalArgumentException
1080 * <li>if <code>refChoiceType</code> equals null</li>
1081 * <li>if <code>caseNodes</code> equals null</li>
1084 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1085 final ChoiceSchemaNode choiceNode) {
1086 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1087 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1089 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1090 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1091 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1092 caseTypeBuilder.addImplementsType(refChoiceType);
1093 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1094 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1095 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1096 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1097 if (caseChildNodes != null) {
1098 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1100 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1101 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1103 if (parent instanceof AugmentationSchemaNode) {
1104 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1105 final SchemaPath targetPath = augSchema.getTargetPath();
1106 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1107 if (targetSchemaNode instanceof DataSchemaNode
1108 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1109 if (targetSchemaNode instanceof DerivableSchemaNode) {
1110 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1113 if (targetSchemaNode == null) {
1114 throw new IllegalStateException(
1115 "Failed to find target node from grouping for augmentation " + augSchema
1116 + " in module " + context.module().getName());
1119 parent = targetSchemaNode;
1122 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1123 Type childOfType = findChildNodeByPath(parent.getPath());
1124 if (childOfType == null) {
1125 childOfType = findGroupingByPath(parent.getPath());
1127 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1129 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1133 processUsesAugments(caseNode, context);
1138 * Generates list of generated types for all the cases of a choice which are
1139 * added to the choice through the augment.
1143 * @param basePackageName
1144 * string contains name of package to which augment belongs. If
1145 * an augmented choice is from an other package (pcg1) than an
1146 * augmenting choice (pcg2) then case's of the augmenting choice
1147 * will belong to pcg2.
1149 * Type which represents target choice
1151 * node which represents target choice
1152 * @param augmentedNodes
1153 * set of choice case nodes for which is checked if are/aren't
1154 * added to choice through augmentation
1155 * @throws IllegalArgumentException
1157 * <li>if <code>basePackageName</code> is null</li>
1158 * <li>if <code>targetType</code> is null</li>
1159 * <li>if <code>augmentedNodes</code> is null</li>
1162 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1163 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1164 final DataNodeContainer usesNodeParent) {
1165 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1166 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1168 for (final DataSchemaNode caseNode : augmentedNodes) {
1169 if (caseNode != null) {
1170 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1171 caseTypeBuilder.addImplementsType(targetType);
1173 final Type childOfType = findChildOfType(targetNode);
1174 CaseSchemaNode node = null;
1175 final String caseLocalName = caseNode.getQName().getLocalName();
1176 if (caseNode instanceof CaseSchemaNode) {
1177 node = (CaseSchemaNode) caseNode;
1178 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1179 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1180 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1181 if (dataSchemaNode instanceof ChoiceSchemaNode
1182 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1183 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1188 node = findNamedCase(targetNode, caseLocalName);
1190 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1191 if (childNodes != null) {
1192 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1194 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1195 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1200 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1201 final SchemaPath nodePath = targetNode.getPath();
1202 final SchemaPath parentSp = nodePath.getParent();
1203 if (parentSp.getParent() == null) {
1204 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1207 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1208 GeneratedTypeBuilder childOfType = null;
1209 if (parent instanceof CaseSchemaNode) {
1210 childOfType = findCaseByPath(parent.getPath());
1211 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1212 childOfType = findChildNodeByPath(parent.getPath());
1213 } else if (parent instanceof GroupingDefinition) {
1214 childOfType = findGroupingByPath(parent.getPath());
1217 if (childOfType == null) {
1218 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1224 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1225 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1226 return cases.isEmpty() ? null : cases.get(0);
1229 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1230 // New parser with encapsulated type
1231 if (leaf.getPath().equals(type.getPath())) {
1235 // Embedded type definition with new parser. Also takes care of the old parser with bits
1236 if (leaf.getPath().equals(type.getPath().getParent())) {
1243 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1244 final List<PatternConstraint> patternConstraints) {
1245 if (!patternConstraints.isEmpty()) {
1246 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1247 .append(BindingMapping.getPropertyName(leafName));
1248 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1249 typeProvider.resolveRegExpressions(patternConstraints));
1254 * Converts <code>leaf</code> to the getter method which is added to
1255 * <code>typeBuilder</code>.
1257 * @param typeBuilder
1258 * generated type builder to which is added getter method as
1259 * <code>leaf</code> mapping
1261 * leaf schema node which is mapped as getter method which is
1262 * added to <code>typeBuilder</code>
1264 * Module in which type was defined
1265 * @return boolean value
1267 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1269 * <li>true - in other cases</li>
1272 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1273 final ModuleContext context) {
1274 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1278 final Module parentModule = findParentModule(schemaContext, leaf);
1279 Type returnType = null;
1281 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1282 if (isInnerType(leaf, typeDef)) {
1283 if (typeDef instanceof EnumTypeDefinition) {
1284 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1285 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1286 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1287 typeBuilder, context);
1288 if (enumBuilder != null) {
1289 returnType = enumBuilder.toInstance(typeBuilder);
1291 typeProvider.putReferencedType(leaf.getPath(), returnType);
1292 } else if (typeDef instanceof UnionTypeDefinition) {
1293 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1295 if (genTOBuilder != null) {
1296 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1297 // Store the inner type within the union so that we can find the reference for it
1298 context.addInnerTypedefType(typeDef.getPath(), returnType);
1300 } else if (typeDef instanceof BitsTypeDefinition) {
1301 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1303 if (genTOBuilder != null) {
1304 returnType = genTOBuilder.build();
1307 // It is constrained version of already declared type (inner declared type exists,
1308 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1309 // In order to get proper class we need to look up closest derived type
1310 // and apply restrictions from leaf type
1311 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1312 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1314 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1317 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1318 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1319 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1322 if (returnType == null) {
1326 if (typeDef instanceof EnumTypeDefinition) {
1327 typeProvider.putReferencedType(leaf.getPath(), returnType);
1330 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1331 processContextRefExtension(leaf, getter, parentModule);
1335 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1336 // Returns DerivedType in case of new parser.
1337 final TypeDefinition<?> baseType = typeDef.getBaseType();
1338 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1341 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1342 final Module module) {
1343 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1344 final QName nodeType = node.getNodeType();
1345 if ("context-reference".equals(nodeType.getLocalName())) {
1346 final String nodeParam = node.getNodeParameter();
1347 IdentitySchemaNode identity = null;
1348 String basePackageName = null;
1349 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1350 final Iterator<String> iterator = splittedElement.iterator();
1351 final int length = Iterables.size(splittedElement);
1353 identity = findIdentityByName(module.getIdentities(), iterator.next());
1354 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1355 } else if (length == 2) {
1356 final String prefix = iterator.next();
1357 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1358 if (dependentModule == null) {
1359 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1362 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1363 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1365 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1368 if (identity == null) {
1369 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1373 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1374 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1375 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1376 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1381 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1382 for (final IdentitySchemaNode id : identities) {
1383 if (id.getQName().getLocalName().equals(name)) {
1390 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1391 for (final ModuleImport imp : imports) {
1392 if (imp.getPrefix().equals(prefix)) {
1393 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1399 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1400 final boolean isReadOnly) {
1401 if (leaf != null && toBuilder != null) {
1403 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1404 if (typeDef instanceof UnionTypeDefinition) {
1405 // GeneratedType for this type definition should have be already created
1406 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1407 returnType = mc.getTypedefs().get(typeDef.getPath());
1408 if (returnType == null) {
1409 // This may still be an inner type, try to find it
1410 returnType = mc.getInnerType(typeDef.getPath());
1412 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1413 // Annonymous enumeration (already generated, since it is inherited via uses).
1414 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1415 QName qname = originalLeaf.getQName();
1416 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1418 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1420 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1426 * Converts <code>leaf</code> schema node to property of generated TO
1430 * generated TO builder to which is <code>leaf</code> added as
1433 * leaf schema node which is added to <code>toBuilder</code> as
1438 * boolean value which says if leaf property is|isn't read only
1439 * @return boolean value
1441 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1442 * name equals null or if leaf is added by <i>uses</i>.</li>
1443 * <li>true - other cases</li>
1446 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1447 final Type returnType, final boolean isReadOnly) {
1448 if (returnType == null) {
1451 final String leafName = leaf.getQName().getLocalName();
1452 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1453 propBuilder.setReadOnly(isReadOnly);
1454 propBuilder.setReturnType(returnType);
1455 addComment(propBuilder, leaf);
1457 toBuilder.addEqualsIdentity(propBuilder);
1458 toBuilder.addHashIdentity(propBuilder);
1459 toBuilder.addToStringProperty(propBuilder);
1464 * Converts <code>node</code> leaf list schema node to getter method of
1465 * <code>typeBuilder</code>.
1467 * @param typeBuilder
1468 * generated type builder to which is <code>node</code> added as
1471 * leaf list schema node which is added to
1472 * <code>typeBuilder</code> as getter method
1473 * @param module module
1474 * @return boolean value
1476 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1477 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1478 * <li>false - other cases</li>
1481 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1482 final ModuleContext context) {
1483 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1487 final QName nodeName = node.getQName();
1489 final TypeDefinition<?> typeDef = node.getType();
1490 final Module parentModule = findParentModule(schemaContext, node);
1492 Type returnType = null;
1493 if (typeDef.getBaseType() == null) {
1494 if (typeDef instanceof EnumTypeDefinition) {
1495 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1496 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1497 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1498 typeBuilder, context);
1499 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1500 typeProvider.putReferencedType(node.getPath(), returnType);
1501 } else if (typeDef instanceof UnionTypeDefinition) {
1502 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1503 node, parentModule);
1504 if (genTOBuilder != null) {
1505 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1507 } else if (typeDef instanceof BitsTypeDefinition) {
1508 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1509 node, parentModule);
1510 returnType = genTOBuilder.build();
1512 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1513 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1514 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1517 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1518 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1519 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1522 final ParameterizedType listType = Types.listTypeFor(returnType);
1523 constructGetter(typeBuilder, listType, node);
1527 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1528 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1529 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1531 addCodegenInformation(returnType, parentModule, typeDef);
1532 returnType.setSchemaPath(typeDef.getPath());
1533 returnType.setModuleName(parentModule.getName());
1535 genTOBuilder.setTypedef(true);
1536 genTOBuilder.setIsUnion(true);
1537 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1541 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1544 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1545 method.setReturnType(returnType);
1546 method.addParameter(Types.STRING, "defaultValue");
1547 method.setAccessModifier(AccessModifier.PUBLIC);
1548 method.setStatic(true);
1550 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1551 if (types == null) {
1552 typeProvider.getAdditionalTypes().put(parentModule,
1553 Sets.newHashSet(unionBuilder.build()));
1555 types.add(unionBuilder.build());
1557 return returnType.build();
1560 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1561 final GeneratedTypeBuilder typeBuilder) {
1562 // Append enclosing path hierarchy without dots
1563 final StringBuilder sb = new StringBuilder();
1564 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1565 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1566 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1567 unionBuilder.setIsUnionBuilder(true);
1568 return unionBuilder;
1571 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1572 final SchemaNode schemaNode) {
1573 return addDefaultInterfaceDefinition(context, schemaNode, null);
1576 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1577 final SchemaNode schemaNode, final Type childOf) {
1578 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1579 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1584 * Instantiates generated type builder with <code>packageName</code> and
1585 * <code>schemaNode</code>.
1587 * The new builder always implements
1588 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1589 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1590 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1592 * If <code>schemaNode</code> is instance of
1593 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1594 * DataNodeContainer} it can also implement nodes which are specified in
1597 * @param packageName
1598 * string with the name of the package to which
1599 * <code>schemaNode</code> belongs.
1601 * schema node for which is created generated type builder
1603 * parent type (can be null)
1604 * @return generated type builder <code>schemaNode</code>
1606 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1607 final Type parent, final ModuleContext context) {
1608 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1609 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1611 it.addImplementsType(parent == null ? DATA_OBJECT : childOf(parent));
1612 if (!(schemaNode instanceof GroupingDefinition)) {
1613 it.addImplementsType(augmentable(it));
1615 if (schemaNode instanceof DataNodeContainer) {
1616 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1617 groupingsToGenTypes(context, containerSchema.getGroupings());
1618 addImplementedInterfaceFromUses(containerSchema, it);
1625 * Wraps the calling of the same overloaded method.
1627 * @param packageName
1628 * string with the package name to which returning generated type
1631 * schema node which provide data about the schema node name
1632 * @return generated type builder for <code>schemaNode</code>
1634 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1635 final String prefix) {
1636 return addRawInterfaceDefinition(
1637 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1638 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1642 * Returns reference to generated type builder for specified
1643 * <code>schemaNode</code> with <code>packageName</code>.
1645 * Firstly the generated type builder is searched in
1646 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1647 * found it is created and added to <code>genTypeBuilders</code>.
1649 * @param packageName
1650 * string with the package name to which returning generated type
1653 * schema node which provide data about the schema node name
1655 * return type name prefix
1656 * @return generated type builder for <code>schemaNode</code>
1657 * @throws IllegalArgumentException
1659 * <li>if <code>schemaNode</code> is null</li>
1660 * <li>if <code>packageName</code> is null</li>
1661 * <li>if QName of schema node is null</li>
1662 * <li>if schemaNode name is null</li>
1666 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1667 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1668 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1669 final String schemaNodeName = schemaNode.getQName().getLocalName();
1670 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1672 // FIXME: Validation of name conflict
1673 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1674 final Module module = findParentModule(schemaContext, schemaNode);
1675 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1676 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1678 addCodegenInformation(newType, module, schemaNode);
1679 newType.setSchemaPath(schemaNode.getPath());
1680 newType.setModuleName(module.getName());
1682 final String packageName = identifier.packageName();
1683 final String simpleName = identifier.simpleName();
1684 if (!genTypeBuilders.containsKey(packageName)) {
1685 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1686 builders.put(simpleName, newType);
1687 genTypeBuilders.put(packageName, builders);
1689 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1690 if (!builders.containsKey(simpleName)) {
1691 builders.put(simpleName, newType);
1698 * Creates the name of the getter method name from <code>localName</code>.
1701 * string with the name of the getter method
1704 * @return string with the name of the getter method for
1705 * <code>methodName</code> in JAVA method format
1707 public static String getterMethodName(final String localName, final Type returnType) {
1708 final StringBuilder method = new StringBuilder();
1709 if (BOOLEAN.equals(returnType)) {
1710 method.append("is");
1712 method.append("get");
1714 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1715 method.append(name);
1716 return method.toString();
1720 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1722 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1723 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1725 * @param interfaceBuilder generated type builder for which the getter method should be created
1726 * @param returnType type which represents the return type of the getter method
1727 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1728 * @param comment string with comment for the getter method
1729 * @param status status from yang file, for deprecated annotation
1730 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1732 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1733 final SchemaNode node) {
1734 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1735 getterMethodName(node.getQName().getLocalName(), returnType));
1736 getMethod.setReturnType(returnType);
1738 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1739 if (!returnType.getPackageName().isEmpty()) {
1740 // The return type has a package, so it's not a primitive type
1741 getMethod.addAnnotation("javax.annotation", "Nullable");
1743 addComment(getMethod, node);
1749 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1750 * or to <code>genTOBuilder</code> as property.
1752 * @param basePackageName
1753 * string contains the module package name
1755 * data schema node which should be added as getter method to
1756 * <code>typeBuilder</code> or as a property to
1757 * <code>genTOBuilder</code> if is part of the list key
1758 * @param typeBuilder
1759 * generated type builder for the list schema node
1760 * @param genTOBuilder
1761 * generated TO builder for the list keys
1763 * list of string which contains names of the list keys
1766 * @throws IllegalArgumentException
1768 * <li>if <code>schemaNode</code> equals null</li>
1769 * <li>if <code>typeBuilder</code> equals null</li>
1772 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1773 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1774 final List<String> listKeys) {
1775 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1776 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1778 if (schemaNode instanceof LeafSchemaNode) {
1779 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1780 final String leafName = leaf.getQName().getLocalName();
1781 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1782 if (listKeys.contains(leafName)) {
1784 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1786 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1789 } else if (!schemaNode.isAddedByUses()) {
1790 if (schemaNode instanceof LeafListSchemaNode) {
1791 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1792 } else if (schemaNode instanceof ContainerSchemaNode) {
1793 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1794 } else if (schemaNode instanceof ChoiceSchemaNode) {
1795 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1796 } else if (schemaNode instanceof ListSchemaNode) {
1797 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1802 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1803 final GeneratedTOBuilder genTOBuilder) {
1804 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1806 if (genTOBuilder != null) {
1807 final GeneratedTransferObject genTO = genTOBuilder.build();
1808 // Add Identifiable.getKey() for items
1809 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1810 .addAnnotation(OVERRIDE_ANNOTATION);
1811 context.addGeneratedTOBuilder(genTOBuilder);
1816 * Selects the names of the list keys from <code>list</code> and returns
1817 * them as the list of the strings
1820 * of string with names of the list keys
1821 * @return list of string which represents names of the list keys. If the
1822 * <code>list</code> contains no keys then the empty list is
1825 private static List<String> listKeys(final ListSchemaNode list) {
1826 final List<String> listKeys = new ArrayList<>();
1828 final List<QName> keyDefinition = list.getKeyDefinition();
1829 if (keyDefinition != null) {
1830 for (final QName keyDef : keyDefinition) {
1831 listKeys.add(keyDef.getLocalName());
1838 * Generates for the <code>list</code> which contains any list keys special
1839 * generated TO builder.
1841 * @param packageName
1842 * string with package name to which the list belongs
1844 * list schema node which is source of data about the list name
1845 * @return generated TO builder which represents the keys of the
1846 * <code>list</code> or null if <code>list</code> is null or list of
1847 * key definitions is null or empty.
1849 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1850 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1851 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1852 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1853 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1859 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1861 * If more then one generated TO builder is created for enclosing then all
1862 * of the generated TO builders are added to <code>typeBuilder</code> as
1863 * enclosing transfer objects.
1866 * type definition which can be of type <code>UnionType</code> or
1867 * <code>BitsTypeDefinition</code>
1868 * @param typeBuilder
1869 * generated type builder to which is added generated TO created
1870 * from <code>typeDef</code>
1872 * string with name for generated TO builder
1873 * @param parentModule
1875 * @return generated TO builder for <code>typeDef</code>
1877 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1878 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1879 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1880 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1883 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1884 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1885 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1886 for (final GeneratedTOBuilder genTOBuilder : types) {
1887 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1890 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1891 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1892 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1893 resultTOBuilder.addHashIdentity(genPropBuilder);
1894 resultTOBuilder.addToStringProperty(genPropBuilder);
1895 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1896 return resultTOBuilder;
1900 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1901 * also added to <code>typeBuilder</code> as enclosing transfer object.
1903 * If more then one generated TO builder is created for enclosing then all
1904 * of the generated TO builders are added to <code>typeBuilder</code> as
1905 * enclosing transfer objects.
1908 * type definition which can be of type <code>UnionType</code> or
1909 * <code>BitsTypeDefinition</code>
1910 * @param typeBuilder
1911 * generated type builder to which is added generated TO created
1912 * from <code>typeDef</code>
1914 * string with name for generated TO builder
1915 * @param parentModule
1917 * @return generated TO builder for <code>typeDef</code>
1919 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1920 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1921 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1922 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1923 typeDef, parentModule.getName());
1924 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1925 return genTOBuilder;
1929 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1930 final List<GeneratedTOBuilder> genTOBuilders) {
1931 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1932 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1934 return genTOBuilders.get(0);
1938 * Adds the implemented types to type builder.
1940 * The method passes through the list of <i>uses</i> in
1941 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1942 * generated type from {@link ModuleContext#groupings
1943 * allGroupings} which is added as <i>implements type</i> to
1944 * <code>builder</code>
1946 * @param dataNodeContainer
1947 * element which contains the list of used YANG groupings
1949 * builder to which are added implemented types according to
1950 * <code>dataNodeContainer</code>
1951 * @return generated type builder with all implemented types
1953 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1954 final GeneratedTypeBuilder builder) {
1955 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1956 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1957 if (genType == null) {
1958 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1959 + builder.getName());
1962 builder.addImplementsType(genType);
1967 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1968 for (final ModuleContext ctx : genCtx.values()) {
1969 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1970 if (result != null) {
1977 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1978 for (final ModuleContext ctx : genCtx.values()) {
1979 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1980 if (result != null) {
1987 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1988 for (final ModuleContext ctx : genCtx.values()) {
1989 final GeneratedTypeBuilder result = ctx.getCase(path);
1990 if (result != null) {
1997 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1998 if (status == Status.DEPRECATED) {
1999 builder.addAnnotation(DEPRECATED_ANNOTATION);