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.listTypeFor;
32 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
33 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
34 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
35 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
36 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
38 import com.google.common.base.Splitter;
39 import com.google.common.collect.Iterables;
40 import com.google.common.collect.Sets;
41 import java.util.AbstractMap.SimpleImmutableEntry;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.Comparator;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
49 import java.util.Optional;
51 import org.eclipse.jdt.annotation.Nullable;
52 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
53 import org.opendaylight.mdsal.binding.model.api.Constant;
54 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
55 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
56 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
57 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
58 import org.opendaylight.mdsal.binding.model.api.Restrictions;
59 import org.opendaylight.mdsal.binding.model.api.Type;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
69 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
70 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
71 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
72 import org.opendaylight.mdsal.binding.model.util.Types;
73 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
74 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
75 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
76 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
77 import org.opendaylight.yangtools.yang.binding.BindingMapping;
78 import org.opendaylight.yangtools.yang.common.QName;
79 import org.opendaylight.yangtools.yang.common.QNameModule;
80 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
88 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
89 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.Module;
94 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
95 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
96 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
97 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
98 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
100 import org.opendaylight.yangtools.yang.model.api.Status;
101 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.UsesNode;
104 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
107 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
108 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
109 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
110 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
111 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 abstract class AbstractTypeGenerator {
116 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
117 private static final Splitter COLON_SPLITTER = Splitter.on(':');
118 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
119 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
120 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
123 * Comparator based on augment target path.
125 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
126 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
127 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
129 while (thisIt.hasNext()) {
130 if (!otherIt.hasNext()) {
134 final int comp = thisIt.next().compareTo(otherIt.next());
140 return otherIt.hasNext() ? -1 : 0;
144 * Constant with the concrete name of identifier.
146 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
149 * Constant with the concrete name of namespace.
151 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
153 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
156 * Outer key represents the package name. Outer value represents map of all
157 * builders in the same package. Inner key represents the schema node name
158 * (in JAVA class/interface name format). Inner value represents instance of
159 * builder for schema node specified in key part.
161 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
164 * Provide methods for converting YANG types to JAVA types.
166 private final AbstractTypeProvider typeProvider;
169 * Holds reference to schema context to resolve data of augmented element
170 * when creating augmentation builder
172 private final SchemaContext schemaContext;
174 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
175 this.schemaContext = requireNonNull(context);
176 this.typeProvider = requireNonNull(typeProvider);
178 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
179 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
180 for (final Module contextModule : contextModules) {
181 contexts.add(moduleToGenTypes(contextModule));
184 contexts.forEach(this::allAugmentsToGenTypes);
187 final Collection<ModuleContext> moduleContexts() {
188 return genCtx.values();
191 final ModuleContext moduleContext(final QNameModule module) {
192 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
195 final AbstractTypeProvider typeProvider() {
199 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
201 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
203 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
204 Set<? extends SchemaNode> nodes);
206 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
208 private ModuleContext moduleToGenTypes(final Module module) {
209 final ModuleContext context = new ModuleContext(module);
210 genCtx.put(module.getQNameModule(), context);
211 allTypeDefinitionsToGenTypes(context);
212 groupingsToGenTypes(context, module.getGroupings());
213 rpcMethodsToGenType(context);
214 allIdentitiesToGenTypes(context);
215 notificationsToGenType(context);
217 if (!module.getChildNodes().isEmpty()) {
218 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
219 context.addModuleNode(moduleType);
220 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
226 * Converts all extended type definitions of module to the list of
227 * <code>Type</code> objects.
230 * module from which is obtained set of type definitions
231 * @throws IllegalArgumentException
233 * <li>if module is null</li>
234 * <li>if name of module is null</li>
236 * @throws IllegalStateException
237 * if set of type definitions from module is null
239 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
240 final Module module = context.module();
241 checkArgument(module.getName() != null, "Module name cannot be NULL.");
242 final DataNodeIterator it = new DataNodeIterator(module);
243 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
244 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
246 for (final TypeDefinition<?> typedef : typeDefinitions) {
247 if (typedef != null) {
248 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
250 context.addTypedefType(typedef.getPath(), type);
251 context.addTypeToSchema(type,typedef);
257 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
258 final DataSchemaNode node) {
259 if (node.isAugmenting() || node.isAddedByUses()) {
262 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
263 annotateDeprecatedIfNecessary(node.getStatus(), genType);
265 final Module module = context.module();
266 genType.setModuleName(module.getName());
267 addCodegenInformation(genType, module, node);
268 genType.setSchemaPath(node.getPath());
269 if (node instanceof DataNodeContainer) {
270 context.addChildNodeType(node, genType);
271 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
272 processUsesAugments((DataNodeContainer) node, context);
277 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
278 final Type baseInterface, final ContainerSchemaNode node) {
279 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
280 if (genType != null) {
281 constructGetter(parent, genType, node);
282 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
286 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
287 final Type baseInterface, final ListSchemaNode node) {
288 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
289 if (genType != null) {
290 constructGetter(parent, listTypeFor(genType), node);
292 final List<String> listKeys = listKeys(node);
293 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
294 if (genTOBuilder != null) {
295 final Type identifierMarker = identifier(genType);
296 final Type identifiableMarker = identifiable(genTOBuilder);
297 genTOBuilder.addImplementsType(identifierMarker);
298 genType.addImplementsType(identifiableMarker);
301 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
302 if (!schemaNode.isAugmenting()) {
303 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
308 if (genTOBuilder != null) {
309 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
310 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
311 genTOBuilder.setSUID(prop);
314 typeBuildersToGenTypes(context, genType, genTOBuilder);
318 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
319 for (final UsesNode usesNode : node.getUses()) {
320 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
321 usesAugmentationToGenTypes(context, augment, usesNode, node);
322 processUsesAugments(augment, context);
328 * Converts all <b>augmentation</b> of the module to the list
329 * <code>Type</code> objects.
332 * module from which is obtained list of all augmentation objects
333 * to iterate over them
334 * @throws IllegalArgumentException
336 * <li>if the module is null</li>
337 * <li>if the name of module is null</li>
339 * @throws IllegalStateException
340 * if set of augmentations from module is null
342 private void allAugmentsToGenTypes(final ModuleContext context) {
343 final Module module = context.module();
344 checkArgument(module != null, "Module reference cannot be NULL.");
345 checkArgument(module.getName() != null, "Module name cannot be NULL.");
346 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
348 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
349 augmentationToGenTypes(context, augment);
354 * Returns list of <code>AugmentationSchema</code> objects. The objects are
355 * sorted according to the length of their target path from the shortest to
359 * module from which is obtained list of all augmentation objects
360 * @return list of sorted <code>AugmentationSchema</code> objects obtained
361 * from <code>module</code>
362 * @throws IllegalArgumentException
364 * @throws IllegalStateException
365 * if set of module augmentations is null
367 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
368 checkArgument(module != null, "Module reference cannot be NULL.");
369 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
371 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
372 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
373 sortedAugmentations.sort(AUGMENT_COMP);
375 return sortedAugmentations;
379 * Create GeneratedTypeBuilder object from module argument.
382 * Module object from which builder will be created
383 * @return <code>GeneratedTypeBuilder</code> which is internal
384 * representation of the module
385 * @throws IllegalArgumentException
388 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
389 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
390 final Module module = context.module();
391 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
392 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
394 addCodegenInformation(moduleDataTypeBuilder, module);
395 return moduleDataTypeBuilder;
399 * Converts all <b>RPCs</b> input and output substatements of the module
400 * to the list of <code>Type</code> objects. In addition are to containers
401 * and lists which belong to input or output also part of returning list.
404 * module from which is obtained set of all rpc objects to
406 * @throws IllegalArgumentException
408 * <li>if the module is null</li>
409 * <li>if the name of module is null</li>
411 * @throws IllegalStateException
412 * if set of rpcs from module is null
414 private void rpcMethodsToGenType(final ModuleContext context) {
415 final Module module = context.module();
416 checkArgument(module.getName() != null, "Module name cannot be NULL.");
417 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
418 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
419 if (rpcDefinitions.isEmpty()) {
423 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
424 interfaceBuilder.addImplementsType(RPC_SERVICE);
426 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
428 for (final RpcDefinition rpc : rpcDefinitions) {
430 final String rpcName = BindingMapping.getClassName(rpc.getQName());
431 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
432 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
434 // Do not refer to annotation class, as it may not be available at runtime
435 method.addAnnotation("javax.annotation", "CheckReturnValue");
436 addComment(method, rpc);
438 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
439 method.setReturnType(listenableFutureTypeFor(
440 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
444 context.addTopLevelNodeType(interfaceBuilder);
447 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
448 final ContainerSchemaNode schema) {
449 processUsesAugments(schema, context);
450 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
451 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
453 addImplementedInterfaceFromUses(schema, outType);
454 outType.addImplementsType(DATA_OBJECT);
455 outType.addImplementsType(augmentable(outType));
456 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
457 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
458 context.addChildNodeType(schema, outType);
459 return outType.build();
463 * Converts all <b>notifications</b> of the module to the list of
464 * <code>Type</code> objects. In addition are to this list added containers
465 * and lists which are part of this notification.
468 * module from which is obtained set of all notification objects
469 * to iterate over them
470 * @throws IllegalArgumentException
472 * <li>if the module equals null</li>
473 * <li>if the name of module equals null</li>
475 * @throws IllegalStateException
476 * if set of notifications from module is null
478 private void notificationsToGenType(final ModuleContext context) {
479 final Module module = context.module();
480 checkArgument(module.getName() != null, "Module name cannot be NULL.");
481 final Set<NotificationDefinition> notifications = module.getNotifications();
482 if (notifications.isEmpty()) {
486 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
487 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
489 for (final NotificationDefinition notification : notifications) {
490 if (notification != null) {
491 processUsesAugments(notification, context);
493 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
494 context.modulePackageName(), notification, DATA_OBJECT, context);
495 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
496 notificationInterface.addImplementsType(NOTIFICATION);
497 context.addChildNodeType(notification, notificationInterface);
499 // Notification object
500 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
501 notification.getChildNodes());
503 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
504 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
505 .setReturnType(Types.primitiveVoidType()), notification);
509 addCodegenInformation(listenerInterface, module, "notifications", notifications);
510 context.addTopLevelNodeType(listenerInterface);
514 * Converts all <b>identities</b> of the module to the list of
515 * <code>Type</code> objects.
518 * module from which is obtained set of all identity objects to
520 * @param schemaContext
521 * schema context only used as input parameter for method
522 * {@link BindingGeneratorImpl#identityToGenType}
525 private void allIdentitiesToGenTypes(final ModuleContext context) {
526 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
528 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
529 for (final IdentitySchemaNode identity : schemaIdentities) {
530 identityToGenType(context, identity);
536 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
537 * created transport object builder. If identity contains base identity then
538 * reference to base identity is added to superior identity as its extend.
539 * If identity doesn't contain base identity then only reference to abstract
540 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
541 * BaseIdentity} is added
545 * @param basePackageName
546 * string contains the module package name
548 * IdentitySchemaNode which contains data about identity
550 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
551 if (identity == null) {
554 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
555 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
556 BindingMapping.getClassName(identity.getQName())));
557 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
558 if (!baseIdentities.isEmpty()) {
559 for (IdentitySchemaNode baseIdentity : baseIdentities) {
560 final QName qname = baseIdentity.getQName();
561 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
562 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
563 newType.addImplementsType(gto);
566 newType.addImplementsType(BASE_IDENTITY);
569 final Module module = context.module();
570 addCodegenInformation(newType, module, identity);
571 newType.setModuleName(module.getName());
572 newType.setSchemaPath(identity.getPath());
574 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
575 identity.getQName().getLocalName());
577 context.addIdentityType(identity.getQName(), newType);
580 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
581 final JavaTypeName yangModuleInfo, final String localName) {
582 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
583 new SimpleImmutableEntry<>(yangModuleInfo, localName));
587 * Converts all <b>groupings</b> of the module to the list of
588 * <code>Type</code> objects. Firstly are groupings sorted according mutual
589 * dependencies. At least dependent (independent) groupings are in the list
590 * saved at first positions. For every grouping the record is added to map
591 * {@link ModuleContext#groupings allGroupings}
596 * collection of groupings from which types will be generated
599 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
600 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
601 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
602 // node of grouping is resolved to the method.
603 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
604 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
605 context.addGroupingType(grouping.getPath(), genType);
606 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
607 groupingsToGenTypes(context, grouping.getGroupings());
608 processUsesAugments(grouping, context);
613 * Adds enumeration builder created from <code>enumTypeDef</code> to
614 * <code>typeBuilder</code>.
616 * Each <code>enumTypeDef</code> item is added to builder with its name and
620 * EnumTypeDefinition contains enum data
622 * string contains name which will be assigned to enumeration
625 * GeneratedTypeBuilder to which will be enum builder assigned
627 * Module in which type should be generated
628 * @return enumeration builder which contains data from
629 * <code>enumTypeDef</code>
631 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
632 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
633 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
634 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
635 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
636 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
637 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
644 * Generates type builder for <code>module</code>.
647 * Module which is source of package name for generated type
650 * string which is added to the module class name representation
652 * @return instance of GeneratedTypeBuilder which represents
653 * <code>module</code>.
654 * @throws IllegalArgumentException
655 * if <code>module</code> is null
657 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
658 final Module module = context.module();
659 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
660 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
661 JavaTypeName.create(context.modulePackageName(), moduleName));
663 moduleBuilder.setModuleName(moduleName);
664 addCodegenInformation(moduleBuilder, module);
665 return moduleBuilder;
669 * Converts <code>augSchema</code> to list of <code>Type</code> which
670 * contains generated type for augmentation. In addition there are also
671 * generated types for all containers, list and choices which are child of
672 * <code>augSchema</code> node or a generated types for cases are added if
673 * augmented node is choice.
675 * @param augmentPackageName
676 * string with the name of the package to which the augmentation
679 * AugmentationSchema which is contains data about augmentation
680 * (target path, childs...)
683 * @throws IllegalArgumentException
685 * <li>if <code>augmentPackageName</code> equals null</li>
686 * <li>if <code>augSchema</code> equals null</li>
688 * @throws IllegalStateException
689 * if augment target path is null
691 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
692 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
693 checkState(augSchema.getTargetPath() != null,
694 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
696 processUsesAugments(augSchema, context);
697 final SchemaPath targetPath = augSchema.getTargetPath();
698 SchemaNode targetSchemaNode = null;
700 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
701 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
702 if (targetSchemaNode instanceof DerivableSchemaNode) {
703 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
705 if (targetSchemaNode == null) {
706 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
707 + " in module " + context.module().getName());
710 if (targetSchemaNode == null) {
711 throw new IllegalArgumentException("augment target not found: " + targetPath);
714 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
715 if (targetTypeBuilder == null) {
716 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
718 if (targetTypeBuilder == null) {
719 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
722 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
723 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
724 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
727 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
728 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
732 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
733 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
734 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
735 checkState(augSchema.getTargetPath() != null,
736 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
738 processUsesAugments(augSchema, context);
739 final SchemaPath targetPath = augSchema.getTargetPath();
740 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
741 if (targetSchemaNode == null) {
742 throw new IllegalArgumentException("augment target not found: " + targetPath);
745 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
746 if (targetTypeBuilder == null) {
747 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
749 if (targetTypeBuilder == null) {
750 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
753 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
754 if (usesNodeParent instanceof SchemaNode) {
755 addRawAugmentGenTypeDefinition(context,
756 packageNameForAugmentedGeneratedType(context.modulePackageName(),
757 ((SchemaNode) usesNodeParent).getPath()),
758 targetTypeBuilder.build(), augSchema);
760 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
763 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
764 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
769 * Convenient method to find node added by uses statement.
773 * @param parentUsesNode
774 * parent of uses node
775 * @return node from its original location in grouping
777 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
778 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
780 if (!(targetGrouping instanceof GroupingDefinition)) {
781 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
784 SchemaNode result = targetGrouping;
785 for (final QName node : targetPath.getPathFromRoot()) {
786 if (result instanceof DataNodeContainer) {
787 final QName resultNode = node.withModule(result.getQName().getModule());
788 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
789 } else if (result instanceof ChoiceSchemaNode) {
790 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
793 if (result == null) {
797 if (result instanceof DerivableSchemaNode) {
798 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
799 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
800 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
801 result = originalNode.get();
805 if (result instanceof DataSchemaNode) {
806 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
807 if (resultDataSchemaNode.isAddedByUses()) {
808 // The original node is required, but we have only the copy of
809 // the original node.
810 // Maybe this indicates a bug in Yang parser.
811 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
814 return resultDataSchemaNode;
817 throw new IllegalStateException(
818 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
823 * Returns a generated type builder for an augmentation.
825 * The name of the type builder is equal to the name of augmented node with
826 * serial number as suffix.
830 * @param augmentPackageName
831 * string with contains the package name to which the augment
833 * @param basePackageName
834 * string with the package name to which the augmented node
836 * @param targetTypeRef
839 * augmentation schema which contains data about the child nodes
840 * and uses of augment
841 * @return generated type builder for augment
843 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
844 final String augmentPackageName, final Type targetTypeRef,
845 final AugmentationSchemaNode augSchema) {
846 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
847 if (augmentBuilders == null) {
848 augmentBuilders = new HashMap<>();
849 genTypeBuilders.put(augmentPackageName, augmentBuilders);
851 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
854 if (augIdentifier != null) {
855 augTypeName = BindingMapping.getClassName(augIdentifier);
857 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
860 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
861 JavaTypeName.create(augmentPackageName, augTypeName));
863 augTypeBuilder.addImplementsType(DATA_OBJECT);
864 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
865 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
866 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
868 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
869 augmentBuilders.put(augTypeName, augTypeBuilder);
871 if (!augSchema.getChildNodes().isEmpty()) {
872 context.addTypeToAugmentation(augTypeBuilder, augSchema);
875 context.addAugmentType(augTypeBuilder);
876 return augTypeBuilder;
879 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
880 final AugmentationSchemaNode augSchema) {
881 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
886 * @param unknownSchemaNodes
887 * @return nodeParameter of UnknownSchemaNode
889 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
890 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
891 final QName nodeType = unknownSchemaNode.getNodeType();
892 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
893 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
894 return unknownSchemaNode.getNodeParameter();
901 * Returns first unique name for the augment generated type builder. The
902 * generated type builder name for augment consists from name of augmented
903 * node and serial number of its augmentation.
906 * map of builders which were created in the package to which the
907 * augmentation belongs
909 * string with name of augmented node
910 * @return string with unique name for augmentation builder
912 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
914 if (builders != null) {
915 while (builders.containsKey(genTypeName + index)) {
919 return genTypeName + index;
923 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
924 * node for which <code>typeBuilder</code> was created.
926 * The subnodes aren't mapped to the methods if they are part of grouping or
927 * augment (in this case are already part of them).
932 * generated type builder which represents any node. The subnodes
933 * of this node are added to the <code>typeBuilder</code> as
934 * methods. The subnode can be of type leaf, leaf-list, list,
939 * set of data schema nodes which are the children of the node
940 * for which <code>typeBuilder</code> was created
941 * @return generated type builder which is the same builder as input
942 * parameter. The getter methods (representing child nodes) could be
945 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
946 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
947 if (schemaNodes != null && parent != null) {
948 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
949 for (final DataSchemaNode schemaNode : schemaNodes) {
950 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
951 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
959 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
960 * node for which <code>typeBuilder</code> was created.
965 * generated type builder which represents any node. The subnodes
966 * of this node are added to the <code>typeBuilder</code> as
967 * methods. The subnode can be of type leaf, leaf-list, list,
972 * set of data schema nodes which are the children of the node
973 * for which <code>typeBuilder</code> was created
974 * @return generated type builder which is the same object as the input
975 * parameter <code>typeBuilder</code>. The getter method could be
978 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
979 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
980 if (schemaNodes != null && typeBuilder != null) {
981 final Type baseInterface = childOf(typeBuilder);
982 for (final DataSchemaNode schemaNode : schemaNodes) {
983 if (!schemaNode.isAugmenting()) {
984 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
992 * Adds to <code>typeBuilder</code> a method which is derived from
993 * <code>schemaNode</code>.
996 * data schema node which is added to <code>typeBuilder</code> as
999 * generated type builder to which is <code>schemaNode</code>
1000 * added as a method.
1006 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1007 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1008 if (node != null && typeBuilder != null) {
1009 if (node instanceof LeafSchemaNode) {
1010 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1011 } else if (node instanceof LeafListSchemaNode) {
1012 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1013 } else if (node instanceof ContainerSchemaNode) {
1014 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1015 } else if (node instanceof ListSchemaNode) {
1016 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1017 } else if (node instanceof ChoiceSchemaNode) {
1018 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1020 // TODO: anyxml not yet supported
1021 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1022 typeBuilder.getFullyQualifiedName());
1028 * Converts <code>choiceNode</code> to the list of generated types for
1029 * choice and its cases.
1031 * The package names for choice and for its cases are created as
1032 * concatenation of the module package (<code>basePackageName</code>) and
1033 * names of all parents node.
1037 * @param basePackageName
1038 * string with the module package name
1042 * choice node which is mapped to generated type. Also child
1043 * nodes - cases are mapped to generated types.
1044 * @throws IllegalArgumentException
1046 * <li>if <code>basePackageName</code> is null</li>
1047 * <li>if <code>choiceNode</code> is null</li>
1050 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1051 final ChoiceSchemaNode choiceNode) {
1052 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1054 if (!choiceNode.isAddedByUses()) {
1055 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1056 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1057 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1058 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1059 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1060 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1062 final GeneratedType choiceType = choiceTypeBuilder.build();
1063 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1065 constructGetter(parent, choiceType, choiceNode);
1070 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1072 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1073 * The package names for the builder is created as concatenation of the module package and names of all parents
1074 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1075 * and <i>choice</i> type
1078 * current module context
1079 * @param refChoiceType
1080 * type which represents superior <i>case</i>
1082 * choice case node which is mapped to generated type
1083 * @throws IllegalArgumentException
1085 * <li>if <code>refChoiceType</code> equals null</li>
1086 * <li>if <code>caseNodes</code> equals null</li>
1089 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1090 final ChoiceSchemaNode choiceNode) {
1091 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1092 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1094 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1095 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1096 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1097 caseTypeBuilder.addImplementsType(refChoiceType);
1098 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1099 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1100 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1101 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1102 if (caseChildNodes != null) {
1103 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1105 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1106 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1108 if (parent instanceof AugmentationSchemaNode) {
1109 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1110 final SchemaPath targetPath = augSchema.getTargetPath();
1111 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1112 if (targetSchemaNode instanceof DataSchemaNode
1113 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1114 if (targetSchemaNode instanceof DerivableSchemaNode) {
1115 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1118 if (targetSchemaNode == null) {
1119 throw new IllegalStateException(
1120 "Failed to find target node from grouping for augmentation " + augSchema
1121 + " in module " + context.module().getName());
1124 parent = targetSchemaNode;
1127 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1128 Type childOfType = findChildNodeByPath(parent.getPath());
1129 if (childOfType == null) {
1130 childOfType = findGroupingByPath(parent.getPath());
1132 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1134 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1138 processUsesAugments(caseNode, context);
1143 * Generates list of generated types for all the cases of a choice which are
1144 * added to the choice through the augment.
1148 * @param basePackageName
1149 * string contains name of package to which augment belongs. If
1150 * an augmented choice is from an other package (pcg1) than an
1151 * augmenting choice (pcg2) then case's of the augmenting choice
1152 * will belong to pcg2.
1154 * Type which represents target choice
1156 * node which represents target choice
1157 * @param augmentedNodes
1158 * set of choice case nodes for which is checked if are/aren't
1159 * added to choice through augmentation
1160 * @throws IllegalArgumentException
1162 * <li>if <code>basePackageName</code> is null</li>
1163 * <li>if <code>targetType</code> is null</li>
1164 * <li>if <code>augmentedNodes</code> is null</li>
1167 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1168 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1169 final DataNodeContainer usesNodeParent) {
1170 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1171 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1173 for (final DataSchemaNode caseNode : augmentedNodes) {
1174 if (caseNode != null) {
1175 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1176 caseTypeBuilder.addImplementsType(targetType);
1178 CaseSchemaNode node = null;
1179 final String caseLocalName = caseNode.getQName().getLocalName();
1180 if (caseNode instanceof CaseSchemaNode) {
1181 node = (CaseSchemaNode) caseNode;
1182 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1183 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1184 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1185 if (dataSchemaNode instanceof ChoiceSchemaNode
1186 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1187 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1192 node = findNamedCase(targetNode, caseLocalName);
1194 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1195 if (childNodes != null) {
1196 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1198 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1199 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1204 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1205 final SchemaPath nodePath = targetNode.getPath();
1206 final SchemaPath parentSp = nodePath.getParent();
1207 if (parentSp.getParent() == null) {
1208 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1211 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1212 GeneratedTypeBuilder childOfType = null;
1213 if (parent instanceof CaseSchemaNode) {
1214 childOfType = findCaseByPath(parent.getPath());
1215 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1216 childOfType = findChildNodeByPath(parent.getPath());
1217 } else if (parent instanceof GroupingDefinition) {
1218 childOfType = findGroupingByPath(parent.getPath());
1221 if (childOfType == null) {
1222 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1228 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1229 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1230 return cases.isEmpty() ? null : cases.get(0);
1233 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1234 // New parser with encapsulated type
1235 if (leaf.getPath().equals(type.getPath())) {
1239 // Embedded type definition with new parser. Also takes care of the old parser with bits
1240 if (leaf.getPath().equals(type.getPath().getParent())) {
1247 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1248 final List<PatternConstraint> patternConstraints) {
1249 if (!patternConstraints.isEmpty()) {
1250 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1251 .append(BindingMapping.getPropertyName(leafName));
1252 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1253 typeProvider.resolveRegExpressions(patternConstraints));
1258 * Converts <code>leaf</code> to the getter method which is added to
1259 * <code>typeBuilder</code>.
1261 * @param typeBuilder
1262 * generated type builder to which is added getter method as
1263 * <code>leaf</code> mapping
1265 * leaf schema node which is mapped as getter method which is
1266 * added to <code>typeBuilder</code>
1268 * Module in which type was defined
1269 * @return boolean value
1271 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1273 * <li>true - in other cases</li>
1276 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1277 final ModuleContext context) {
1278 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1282 final Module parentModule = findParentModule(schemaContext, leaf);
1283 Type returnType = null;
1285 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1286 if (isInnerType(leaf, typeDef)) {
1287 if (typeDef instanceof EnumTypeDefinition) {
1288 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1289 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1290 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1291 typeBuilder, context);
1292 if (enumBuilder != null) {
1293 returnType = enumBuilder.toInstance(typeBuilder);
1295 typeProvider.putReferencedType(leaf.getPath(), returnType);
1296 } else if (typeDef instanceof UnionTypeDefinition) {
1297 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1299 if (genTOBuilder != null) {
1300 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1301 // Store the inner type within the union so that we can find the reference for it
1302 context.addInnerTypedefType(typeDef.getPath(), returnType);
1304 } else if (typeDef instanceof BitsTypeDefinition) {
1305 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1307 if (genTOBuilder != null) {
1308 returnType = genTOBuilder.build();
1311 // It is constrained version of already declared type (inner declared type exists,
1312 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1313 // In order to get proper class we need to look up closest derived type
1314 // and apply restrictions from leaf type
1315 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1316 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1318 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1321 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1322 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1323 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1326 if (returnType == null) {
1330 if (typeDef instanceof EnumTypeDefinition) {
1331 typeProvider.putReferencedType(leaf.getPath(), returnType);
1334 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1335 processContextRefExtension(leaf, getter, parentModule);
1339 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1340 // Returns DerivedType in case of new parser.
1341 final TypeDefinition<?> baseType = typeDef.getBaseType();
1342 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1345 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1346 final Module module) {
1347 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1348 final QName nodeType = node.getNodeType();
1349 if ("context-reference".equals(nodeType.getLocalName())) {
1350 final String nodeParam = node.getNodeParameter();
1351 IdentitySchemaNode identity = null;
1352 String basePackageName = null;
1353 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1354 final Iterator<String> iterator = splittedElement.iterator();
1355 final int length = Iterables.size(splittedElement);
1357 identity = findIdentityByName(module.getIdentities(), iterator.next());
1358 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1359 } else if (length == 2) {
1360 final String prefix = iterator.next();
1361 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1362 if (dependentModule == null) {
1363 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1366 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1367 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1369 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1372 if (identity == null) {
1373 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1377 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1378 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1379 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1380 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1385 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1386 for (final IdentitySchemaNode id : identities) {
1387 if (id.getQName().getLocalName().equals(name)) {
1394 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1395 for (final ModuleImport imp : imports) {
1396 if (imp.getPrefix().equals(prefix)) {
1397 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1403 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1404 final boolean isReadOnly) {
1405 if (leaf != null && toBuilder != null) {
1407 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1408 if (typeDef instanceof UnionTypeDefinition) {
1409 // GeneratedType for this type definition should have be already created
1410 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1411 returnType = mc.getTypedefs().get(typeDef.getPath());
1412 if (returnType == null) {
1413 // This may still be an inner type, try to find it
1414 returnType = mc.getInnerType(typeDef.getPath());
1416 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1417 // Annonymous enumeration (already generated, since it is inherited via uses).
1418 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1419 QName qname = originalLeaf.getQName();
1420 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1422 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1424 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1430 * Converts <code>leaf</code> schema node to property of generated TO
1434 * generated TO builder to which is <code>leaf</code> added as
1437 * leaf schema node which is added to <code>toBuilder</code> as
1442 * boolean value which says if leaf property is|isn't read only
1443 * @return boolean value
1445 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1446 * name equals null or if leaf is added by <i>uses</i>.</li>
1447 * <li>true - other cases</li>
1450 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1451 final Type returnType, final boolean isReadOnly) {
1452 if (returnType == null) {
1455 final String leafName = leaf.getQName().getLocalName();
1456 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1457 propBuilder.setReadOnly(isReadOnly);
1458 propBuilder.setReturnType(returnType);
1459 addComment(propBuilder, leaf);
1461 toBuilder.addEqualsIdentity(propBuilder);
1462 toBuilder.addHashIdentity(propBuilder);
1463 toBuilder.addToStringProperty(propBuilder);
1468 * Converts <code>node</code> leaf list schema node to getter method of
1469 * <code>typeBuilder</code>.
1471 * @param typeBuilder
1472 * generated type builder to which is <code>node</code> added as
1475 * leaf list schema node which is added to
1476 * <code>typeBuilder</code> as getter method
1477 * @param module module
1478 * @return boolean value
1480 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1481 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1482 * <li>false - other cases</li>
1485 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1486 final ModuleContext context) {
1487 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1491 final QName nodeName = node.getQName();
1493 final TypeDefinition<?> typeDef = node.getType();
1494 final Module parentModule = findParentModule(schemaContext, node);
1496 Type returnType = null;
1497 if (typeDef.getBaseType() == null) {
1498 if (typeDef instanceof EnumTypeDefinition) {
1499 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1500 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1501 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1502 typeBuilder, context);
1503 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1504 typeProvider.putReferencedType(node.getPath(), returnType);
1505 } else if (typeDef instanceof UnionTypeDefinition) {
1506 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1507 node, parentModule);
1508 if (genTOBuilder != null) {
1509 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1511 } else if (typeDef instanceof BitsTypeDefinition) {
1512 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1513 node, parentModule);
1514 returnType = genTOBuilder.build();
1516 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1517 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1518 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1521 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1522 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1523 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1526 final ParameterizedType listType = listTypeFor(returnType);
1527 constructGetter(typeBuilder, listType, node);
1531 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1532 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1533 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1535 addCodegenInformation(returnType, parentModule, typeDef);
1536 returnType.setSchemaPath(typeDef.getPath());
1537 returnType.setModuleName(parentModule.getName());
1539 genTOBuilder.setTypedef(true);
1540 genTOBuilder.setIsUnion(true);
1541 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1545 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1548 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1549 method.setReturnType(returnType);
1550 method.addParameter(Types.STRING, "defaultValue");
1551 method.setAccessModifier(AccessModifier.PUBLIC);
1552 method.setStatic(true);
1554 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1555 if (types == null) {
1556 typeProvider.getAdditionalTypes().put(parentModule,
1557 Sets.newHashSet(unionBuilder.build()));
1559 types.add(unionBuilder.build());
1561 return returnType.build();
1564 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1565 final GeneratedTypeBuilder typeBuilder) {
1566 // Append enclosing path hierarchy without dots
1567 final StringBuilder sb = new StringBuilder();
1568 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1569 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1570 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1571 unionBuilder.setIsUnionBuilder(true);
1572 return unionBuilder;
1575 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1576 final SchemaNode schemaNode) {
1577 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1580 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1581 final SchemaNode schemaNode, final Type baseInterface) {
1582 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1583 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1588 * Instantiates generated type builder with <code>packageName</code> and
1589 * <code>schemaNode</code>.
1591 * The new builder always implements
1592 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1593 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1594 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1596 * If <code>schemaNode</code> is instance of
1597 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1598 * DataNodeContainer} it can also implement nodes which are specified in
1601 * @param packageName
1602 * string with the name of the package to which
1603 * <code>schemaNode</code> belongs.
1605 * schema node for which is created generated type builder
1607 * parent type (can be null)
1608 * @return generated type builder <code>schemaNode</code>
1610 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1611 final Type baseInterface, final ModuleContext context) {
1612 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1613 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1615 it.addImplementsType(baseInterface);
1616 if (!(schemaNode instanceof GroupingDefinition)) {
1617 it.addImplementsType(augmentable(it));
1619 if (schemaNode instanceof DataNodeContainer) {
1620 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1621 groupingsToGenTypes(context, containerSchema.getGroupings());
1622 addImplementedInterfaceFromUses(containerSchema, it);
1629 * Wraps the calling of the same overloaded method.
1631 * @param packageName
1632 * string with the package name to which returning generated type
1635 * schema node which provide data about the schema node name
1636 * @return generated type builder for <code>schemaNode</code>
1638 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1639 final String prefix) {
1640 return addRawInterfaceDefinition(
1641 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1642 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1646 * Returns reference to generated type builder for specified
1647 * <code>schemaNode</code> with <code>packageName</code>.
1649 * Firstly the generated type builder is searched in
1650 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1651 * found it is created and added to <code>genTypeBuilders</code>.
1653 * @param packageName
1654 * string with the package name to which returning generated type
1657 * schema node which provide data about the schema node name
1659 * return type name prefix
1660 * @return generated type builder for <code>schemaNode</code>
1661 * @throws IllegalArgumentException
1663 * <li>if <code>schemaNode</code> is null</li>
1664 * <li>if <code>packageName</code> is null</li>
1665 * <li>if QName of schema node is null</li>
1666 * <li>if schemaNode name is null</li>
1670 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1671 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1672 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1673 final String schemaNodeName = schemaNode.getQName().getLocalName();
1674 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1676 // FIXME: Validation of name conflict
1677 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1678 final Module module = findParentModule(schemaContext, schemaNode);
1679 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1680 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1682 addCodegenInformation(newType, module, schemaNode);
1683 newType.setSchemaPath(schemaNode.getPath());
1684 newType.setModuleName(module.getName());
1686 final String packageName = identifier.packageName();
1687 final String simpleName = identifier.simpleName();
1688 if (!genTypeBuilders.containsKey(packageName)) {
1689 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1690 builders.put(simpleName, newType);
1691 genTypeBuilders.put(packageName, builders);
1693 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1694 if (!builders.containsKey(simpleName)) {
1695 builders.put(simpleName, newType);
1702 * Creates the name of the getter method name from <code>localName</code>.
1705 * string with the name of the getter method
1708 * @return string with the name of the getter method for
1709 * <code>methodName</code> in JAVA method format
1711 public static String getterMethodName(final String localName, final Type returnType) {
1712 final StringBuilder method = new StringBuilder();
1713 if (BOOLEAN.equals(returnType)) {
1714 method.append("is");
1716 method.append("get");
1718 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1719 method.append(name);
1720 return method.toString();
1724 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1726 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1727 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1729 * @param interfaceBuilder generated type builder for which the getter method should be created
1730 * @param returnType type which represents the return type of the getter method
1731 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1732 * @param comment string with comment for the getter method
1733 * @param status status from yang file, for deprecated annotation
1734 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1736 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1737 final SchemaNode node) {
1738 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1739 getterMethodName(node.getQName().getLocalName(), returnType));
1740 getMethod.setReturnType(returnType);
1742 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1743 if (!returnType.getPackageName().isEmpty()) {
1744 // The return type has a package, so it's not a primitive type
1745 getMethod.addAnnotation("javax.annotation", "Nullable");
1747 addComment(getMethod, node);
1753 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1754 * or to <code>genTOBuilder</code> as property.
1756 * @param basePackageName
1757 * string contains the module package name
1759 * data schema node which should be added as getter method to
1760 * <code>typeBuilder</code> or as a property to
1761 * <code>genTOBuilder</code> if is part of the list key
1762 * @param typeBuilder
1763 * generated type builder for the list schema node
1764 * @param genTOBuilder
1765 * generated TO builder for the list keys
1767 * list of string which contains names of the list keys
1770 * @throws IllegalArgumentException
1772 * <li>if <code>schemaNode</code> equals null</li>
1773 * <li>if <code>typeBuilder</code> equals null</li>
1776 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1777 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1778 final List<String> listKeys) {
1779 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1780 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1782 if (schemaNode instanceof LeafSchemaNode) {
1783 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1784 final String leafName = leaf.getQName().getLocalName();
1785 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1786 if (listKeys.contains(leafName)) {
1788 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1790 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1793 } else if (!schemaNode.isAddedByUses()) {
1794 if (schemaNode instanceof LeafListSchemaNode) {
1795 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1796 } else if (schemaNode instanceof ContainerSchemaNode) {
1797 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1798 (ContainerSchemaNode) schemaNode);
1799 } else if (schemaNode instanceof ChoiceSchemaNode) {
1800 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1801 } else if (schemaNode instanceof ListSchemaNode) {
1802 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1807 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1808 final GeneratedTOBuilder genTOBuilder) {
1809 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1811 if (genTOBuilder != null) {
1812 final GeneratedTransferObject genTO = genTOBuilder.build();
1813 // Add Identifiable.getKey() for items
1814 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1815 .addAnnotation(OVERRIDE_ANNOTATION);
1816 context.addGeneratedTOBuilder(genTOBuilder);
1821 * Selects the names of the list keys from <code>list</code> and returns
1822 * them as the list of the strings
1825 * of string with names of the list keys
1826 * @return list of string which represents names of the list keys. If the
1827 * <code>list</code> contains no keys then the empty list is
1830 private static List<String> listKeys(final ListSchemaNode list) {
1831 final List<String> listKeys = new ArrayList<>();
1833 final List<QName> keyDefinition = list.getKeyDefinition();
1834 if (keyDefinition != null) {
1835 for (final QName keyDef : keyDefinition) {
1836 listKeys.add(keyDef.getLocalName());
1843 * Generates for the <code>list</code> which contains any list keys special
1844 * generated TO builder.
1846 * @param packageName
1847 * string with package name to which the list belongs
1849 * list schema node which is source of data about the list name
1850 * @return generated TO builder which represents the keys of the
1851 * <code>list</code> or null if <code>list</code> is null or list of
1852 * key definitions is null or empty.
1854 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1855 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1856 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1857 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1858 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1864 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1866 * If more then one generated TO builder is created for enclosing then all
1867 * of the generated TO builders are added to <code>typeBuilder</code> as
1868 * enclosing transfer objects.
1871 * type definition which can be of type <code>UnionType</code> or
1872 * <code>BitsTypeDefinition</code>
1873 * @param typeBuilder
1874 * generated type builder to which is added generated TO created
1875 * from <code>typeDef</code>
1877 * string with name for generated TO builder
1878 * @param parentModule
1880 * @return generated TO builder for <code>typeDef</code>
1882 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1883 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1884 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1885 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1888 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1889 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1890 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1891 for (final GeneratedTOBuilder genTOBuilder : types) {
1892 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1895 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1896 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1897 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1898 resultTOBuilder.addHashIdentity(genPropBuilder);
1899 resultTOBuilder.addToStringProperty(genPropBuilder);
1900 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1901 return resultTOBuilder;
1905 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1906 * also added to <code>typeBuilder</code> as enclosing transfer object.
1908 * If more then one generated TO builder is created for enclosing then all
1909 * of the generated TO builders are added to <code>typeBuilder</code> as
1910 * enclosing transfer objects.
1913 * type definition which can be of type <code>UnionType</code> or
1914 * <code>BitsTypeDefinition</code>
1915 * @param typeBuilder
1916 * generated type builder to which is added generated TO created
1917 * from <code>typeDef</code>
1919 * string with name for generated TO builder
1920 * @param parentModule
1922 * @return generated TO builder for <code>typeDef</code>
1924 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1925 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1926 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1927 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1928 typeDef, parentModule.getName());
1929 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1930 return genTOBuilder;
1934 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1935 final List<GeneratedTOBuilder> genTOBuilders) {
1936 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1937 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1939 return genTOBuilders.get(0);
1943 * Adds the implemented types to type builder.
1945 * The method passes through the list of <i>uses</i> in
1946 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1947 * generated type from {@link ModuleContext#groupings
1948 * allGroupings} which is added as <i>implements type</i> to
1949 * <code>builder</code>
1951 * @param dataNodeContainer
1952 * element which contains the list of used YANG groupings
1954 * builder to which are added implemented types according to
1955 * <code>dataNodeContainer</code>
1956 * @return generated type builder with all implemented types
1958 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1959 final GeneratedTypeBuilder builder) {
1960 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1961 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1962 if (genType == null) {
1963 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1964 + builder.getName());
1967 builder.addImplementsType(genType);
1972 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1973 for (final ModuleContext ctx : genCtx.values()) {
1974 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1975 if (result != null) {
1982 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1983 for (final ModuleContext ctx : genCtx.values()) {
1984 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1985 if (result != null) {
1992 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1993 for (final ModuleContext ctx : genCtx.values()) {
1994 final GeneratedTypeBuilder result = ctx.getCase(path);
1995 if (result != null) {
2002 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2003 if (status == Status.DEPRECATED) {
2004 builder.addAnnotation(DEPRECATED_ANNOTATION);