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.eclipse.jdt.annotation.Nullable;
51 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
52 import org.opendaylight.mdsal.binding.model.api.Constant;
53 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
54 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
55 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
56 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
57 import org.opendaylight.mdsal.binding.model.api.Restrictions;
58 import org.opendaylight.mdsal.binding.model.api.Type;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
68 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
69 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
70 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
71 import org.opendaylight.mdsal.binding.model.util.Types;
72 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
73 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
74 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
75 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
76 import org.opendaylight.yangtools.yang.binding.BindingMapping;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.QNameModule;
79 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
87 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
88 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.Module;
93 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
94 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
95 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
99 import org.opendaylight.yangtools.yang.model.api.Status;
100 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.UsesNode;
103 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
106 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
107 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
108 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
109 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
110 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
114 abstract class AbstractTypeGenerator {
115 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
116 private static final Splitter COLON_SPLITTER = Splitter.on(':');
117 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
118 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
121 * Comparator based on augment target path.
123 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
124 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
125 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
127 while (thisIt.hasNext()) {
128 if (!otherIt.hasNext()) {
132 final int comp = thisIt.next().compareTo(otherIt.next());
138 return otherIt.hasNext() ? -1 : 0;
142 * Constant with the concrete name of identifier.
144 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
147 * Constant with the concrete name of namespace.
149 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
151 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
154 * Outer key represents the package name. Outer value represents map of all
155 * builders in the same package. Inner key represents the schema node name
156 * (in JAVA class/interface name format). Inner value represents instance of
157 * builder for schema node specified in key part.
159 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
162 * Provide methods for converting YANG types to JAVA types.
164 private final AbstractTypeProvider typeProvider;
167 * Holds reference to schema context to resolve data of augmented element
168 * when creating augmentation builder
170 private final SchemaContext schemaContext;
172 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
173 this.schemaContext = requireNonNull(context);
174 this.typeProvider = requireNonNull(typeProvider);
176 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
177 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
178 for (final Module contextModule : contextModules) {
179 contexts.add(moduleToGenTypes(contextModule));
182 contexts.forEach(this::allAugmentsToGenTypes);
185 final Collection<ModuleContext> moduleContexts() {
186 return genCtx.values();
189 final ModuleContext moduleContext(final QNameModule module) {
190 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
193 final AbstractTypeProvider typeProvider() {
197 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
199 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
201 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
202 Set<? extends SchemaNode> nodes);
204 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
206 private ModuleContext moduleToGenTypes(final Module module) {
207 final ModuleContext context = new ModuleContext(module);
208 genCtx.put(module.getQNameModule(), context);
209 allTypeDefinitionsToGenTypes(context);
210 groupingsToGenTypes(context, module.getGroupings());
211 rpcMethodsToGenType(context);
212 allIdentitiesToGenTypes(context);
213 notificationsToGenType(context);
215 if (!module.getChildNodes().isEmpty()) {
216 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
217 context.addModuleNode(moduleType);
218 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
224 * Converts all extended type definitions of module to the list of
225 * <code>Type</code> objects.
228 * module from which is obtained set of type definitions
229 * @throws IllegalArgumentException
231 * <li>if module is null</li>
232 * <li>if name of module is null</li>
234 * @throws IllegalStateException
235 * if set of type definitions from module is null
237 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
238 final Module module = context.module();
239 checkArgument(module.getName() != null, "Module name cannot be NULL.");
240 final DataNodeIterator it = new DataNodeIterator(module);
241 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
242 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
244 for (final TypeDefinition<?> typedef : typeDefinitions) {
245 if (typedef != null) {
246 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
248 context.addTypedefType(typedef.getPath(), type);
249 context.addTypeToSchema(type,typedef);
255 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
256 final DataSchemaNode node) {
257 if (node.isAugmenting() || node.isAddedByUses()) {
260 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
261 annotateDeprecatedIfNecessary(node.getStatus(), genType);
263 final Module module = context.module();
264 genType.setModuleName(module.getName());
265 addCodegenInformation(genType, module, node);
266 genType.setSchemaPath(node.getPath());
267 if (node instanceof DataNodeContainer) {
268 context.addChildNodeType(node, genType);
269 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
270 processUsesAugments((DataNodeContainer) node, context);
275 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
276 final Type baseInterface, final ContainerSchemaNode node) {
277 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
278 if (genType != null) {
279 constructGetter(parent, genType, node);
280 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
284 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
285 final Type baseInterface, final ListSchemaNode node) {
286 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
287 if (genType != null) {
288 constructGetter(parent, Types.listTypeFor(genType), node);
290 final List<String> listKeys = listKeys(node);
291 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
292 if (genTOBuilder != null) {
293 final Type identifierMarker = identifier(genType);
294 final Type identifiableMarker = identifiable(genTOBuilder);
295 genTOBuilder.addImplementsType(identifierMarker);
296 genType.addImplementsType(identifiableMarker);
299 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
300 if (!schemaNode.isAugmenting()) {
301 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
306 if (genTOBuilder != null) {
307 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
308 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
309 genTOBuilder.setSUID(prop);
312 typeBuildersToGenTypes(context, genType, genTOBuilder);
316 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
317 for (final UsesNode usesNode : node.getUses()) {
318 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
319 usesAugmentationToGenTypes(context, augment, usesNode, node);
320 processUsesAugments(augment, context);
326 * Converts all <b>augmentation</b> of the module to the list
327 * <code>Type</code> objects.
330 * module from which is obtained list of all augmentation objects
331 * to iterate over them
332 * @throws IllegalArgumentException
334 * <li>if the module is null</li>
335 * <li>if the name of module is null</li>
337 * @throws IllegalStateException
338 * if set of augmentations from module is null
340 private void allAugmentsToGenTypes(final ModuleContext context) {
341 final Module module = context.module();
342 checkArgument(module != null, "Module reference cannot be NULL.");
343 checkArgument(module.getName() != null, "Module name cannot be NULL.");
344 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
346 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
347 augmentationToGenTypes(context, augment);
352 * Returns list of <code>AugmentationSchema</code> objects. The objects are
353 * sorted according to the length of their target path from the shortest to
357 * module from which is obtained list of all augmentation objects
358 * @return list of sorted <code>AugmentationSchema</code> objects obtained
359 * from <code>module</code>
360 * @throws IllegalArgumentException
362 * @throws IllegalStateException
363 * if set of module augmentations is null
365 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
366 checkArgument(module != null, "Module reference cannot be NULL.");
367 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
369 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
370 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
371 sortedAugmentations.sort(AUGMENT_COMP);
373 return sortedAugmentations;
377 * Create GeneratedTypeBuilder object from module argument.
380 * Module object from which builder will be created
381 * @return <code>GeneratedTypeBuilder</code> which is internal
382 * representation of the module
383 * @throws IllegalArgumentException
386 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
387 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
388 final Module module = context.module();
389 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
390 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
392 addCodegenInformation(moduleDataTypeBuilder, module);
393 return moduleDataTypeBuilder;
397 * Converts all <b>RPCs</b> input and output substatements of the module
398 * to the list of <code>Type</code> objects. In addition are to containers
399 * and lists which belong to input or output also part of returning list.
402 * module from which is obtained set of all rpc objects to
404 * @throws IllegalArgumentException
406 * <li>if the module is null</li>
407 * <li>if the name of module is null</li>
409 * @throws IllegalStateException
410 * if set of rpcs from module is null
412 private void rpcMethodsToGenType(final ModuleContext context) {
413 final Module module = context.module();
414 checkArgument(module.getName() != null, "Module name cannot be NULL.");
415 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
416 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
417 if (rpcDefinitions.isEmpty()) {
421 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
422 interfaceBuilder.addImplementsType(RPC_SERVICE);
424 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
426 for (final RpcDefinition rpc : rpcDefinitions) {
428 final String rpcName = BindingMapping.getClassName(rpc.getQName());
429 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
430 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
432 // Do not refer to annotation class, as it may not be available at runtime
433 method.addAnnotation("javax.annotation", "CheckReturnValue");
434 addComment(method, rpc);
436 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
437 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
438 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
442 context.addTopLevelNodeType(interfaceBuilder);
445 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
446 final ContainerSchemaNode schema) {
447 processUsesAugments(schema, context);
448 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
449 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
451 addImplementedInterfaceFromUses(schema, outType);
452 outType.addImplementsType(DATA_OBJECT);
453 outType.addImplementsType(augmentable(outType));
454 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
455 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
456 context.addChildNodeType(schema, outType);
457 return outType.build();
461 * Converts all <b>notifications</b> of the module to the list of
462 * <code>Type</code> objects. In addition are to this list added containers
463 * and lists which are part of this notification.
466 * module from which is obtained set of all notification objects
467 * to iterate over them
468 * @throws IllegalArgumentException
470 * <li>if the module equals null</li>
471 * <li>if the name of module equals null</li>
473 * @throws IllegalStateException
474 * if set of notifications from module is null
476 private void notificationsToGenType(final ModuleContext context) {
477 final Module module = context.module();
478 checkArgument(module.getName() != null, "Module name cannot be NULL.");
479 final Set<NotificationDefinition> notifications = module.getNotifications();
480 if (notifications.isEmpty()) {
484 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
485 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
487 for (final NotificationDefinition notification : notifications) {
488 if (notification != null) {
489 processUsesAugments(notification, context);
491 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
492 context.modulePackageName(), notification, DATA_OBJECT, context);
493 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
494 notificationInterface.addImplementsType(NOTIFICATION);
495 context.addChildNodeType(notification, notificationInterface);
497 // Notification object
498 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
499 notification.getChildNodes());
501 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
502 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
503 .setReturnType(Types.primitiveVoidType()), notification);
507 addCodegenInformation(listenerInterface, module, "notifications", notifications);
508 context.addTopLevelNodeType(listenerInterface);
512 * Converts all <b>identities</b> of the module to the list of
513 * <code>Type</code> objects.
516 * module from which is obtained set of all identity objects to
518 * @param schemaContext
519 * schema context only used as input parameter for method
520 * {@link BindingGeneratorImpl#identityToGenType}
523 private void allIdentitiesToGenTypes(final ModuleContext context) {
524 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
526 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
527 for (final IdentitySchemaNode identity : schemaIdentities) {
528 identityToGenType(context, identity);
534 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
535 * created transport object builder. If identity contains base identity then
536 * reference to base identity is added to superior identity as its extend.
537 * If identity doesn't contain base identity then only reference to abstract
538 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
539 * BaseIdentity} is added
543 * @param basePackageName
544 * string contains the module package name
546 * IdentitySchemaNode which contains data about identity
548 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
549 if (identity == null) {
552 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
553 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
554 BindingMapping.getClassName(identity.getQName())));
555 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
556 if (!baseIdentities.isEmpty()) {
557 for (IdentitySchemaNode baseIdentity : baseIdentities) {
558 final QName qname = baseIdentity.getQName();
559 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
560 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
561 newType.addImplementsType(gto);
564 newType.addImplementsType(BASE_IDENTITY);
567 final Module module = context.module();
568 addCodegenInformation(newType, module, identity);
569 newType.setModuleName(module.getName());
570 newType.setSchemaPath(identity.getPath());
572 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
573 identity.getQName().getLocalName());
575 context.addIdentityType(identity.getQName(), newType);
578 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
579 final JavaTypeName yangModuleInfo, final String localName) {
580 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
581 new SimpleImmutableEntry<>(yangModuleInfo, localName));
585 * Converts all <b>groupings</b> of the module to the list of
586 * <code>Type</code> objects. Firstly are groupings sorted according mutual
587 * dependencies. At least dependent (independent) groupings are in the list
588 * saved at first positions. For every grouping the record is added to map
589 * {@link ModuleContext#groupings allGroupings}
594 * collection of groupings from which types will be generated
597 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
598 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
599 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
600 // node of grouping is resolved to the method.
601 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
602 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
603 context.addGroupingType(grouping.getPath(), genType);
604 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
605 groupingsToGenTypes(context, grouping.getGroupings());
606 processUsesAugments(grouping, context);
611 * Adds enumeration builder created from <code>enumTypeDef</code> to
612 * <code>typeBuilder</code>.
614 * Each <code>enumTypeDef</code> item is added to builder with its name and
618 * EnumTypeDefinition contains enum data
620 * string contains name which will be assigned to enumeration
623 * GeneratedTypeBuilder to which will be enum builder assigned
625 * Module in which type should be generated
626 * @return enumeration builder which contains data from
627 * <code>enumTypeDef</code>
629 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
630 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
631 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
632 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
633 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
634 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
635 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
642 * Generates type builder for <code>module</code>.
645 * Module which is source of package name for generated type
648 * string which is added to the module class name representation
650 * @return instance of GeneratedTypeBuilder which represents
651 * <code>module</code>.
652 * @throws IllegalArgumentException
653 * if <code>module</code> is null
655 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
656 final Module module = context.module();
657 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
658 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
659 JavaTypeName.create(context.modulePackageName(), moduleName));
661 moduleBuilder.setModuleName(moduleName);
662 addCodegenInformation(moduleBuilder, module);
663 return moduleBuilder;
667 * Converts <code>augSchema</code> to list of <code>Type</code> which
668 * contains generated type for augmentation. In addition there are also
669 * generated types for all containers, list and choices which are child of
670 * <code>augSchema</code> node or a generated types for cases are added if
671 * augmented node is choice.
673 * @param augmentPackageName
674 * string with the name of the package to which the augmentation
677 * AugmentationSchema which is contains data about augmentation
678 * (target path, childs...)
681 * @throws IllegalArgumentException
683 * <li>if <code>augmentPackageName</code> equals null</li>
684 * <li>if <code>augSchema</code> equals null</li>
686 * @throws IllegalStateException
687 * if augment target path is null
689 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
690 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
691 checkState(augSchema.getTargetPath() != null,
692 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
694 processUsesAugments(augSchema, context);
695 final SchemaPath targetPath = augSchema.getTargetPath();
696 SchemaNode targetSchemaNode = null;
698 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
699 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
700 if (targetSchemaNode instanceof DerivableSchemaNode) {
701 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
703 if (targetSchemaNode == null) {
704 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
705 + " in module " + context.module().getName());
708 if (targetSchemaNode == null) {
709 throw new IllegalArgumentException("augment target not found: " + targetPath);
712 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
713 if (targetTypeBuilder == null) {
714 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
716 if (targetTypeBuilder == null) {
717 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
720 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
721 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
722 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
725 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
726 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
730 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
731 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
732 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
733 checkState(augSchema.getTargetPath() != null,
734 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
736 processUsesAugments(augSchema, context);
737 final SchemaPath targetPath = augSchema.getTargetPath();
738 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
739 if (targetSchemaNode == null) {
740 throw new IllegalArgumentException("augment target not found: " + targetPath);
743 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
744 if (targetTypeBuilder == null) {
745 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
747 if (targetTypeBuilder == null) {
748 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
751 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
752 if (usesNodeParent instanceof SchemaNode) {
753 addRawAugmentGenTypeDefinition(context,
754 packageNameForAugmentedGeneratedType(context.modulePackageName(),
755 ((SchemaNode) usesNodeParent).getPath()),
756 targetTypeBuilder.build(), augSchema);
758 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
761 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
762 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
767 * Convenient method to find node added by uses statement.
771 * @param parentUsesNode
772 * parent of uses node
773 * @return node from its original location in grouping
775 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
776 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
778 if (!(targetGrouping instanceof GroupingDefinition)) {
779 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
782 SchemaNode result = targetGrouping;
783 for (final QName node : targetPath.getPathFromRoot()) {
784 if (result instanceof DataNodeContainer) {
785 final QName resultNode = node.withModule(result.getQName().getModule());
786 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
787 } else if (result instanceof ChoiceSchemaNode) {
788 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
791 if (result == null) {
795 if (result instanceof DerivableSchemaNode) {
796 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
797 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
798 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
799 result = originalNode.get();
803 if (result instanceof DataSchemaNode) {
804 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
805 if (resultDataSchemaNode.isAddedByUses()) {
806 // The original node is required, but we have only the copy of
807 // the original node.
808 // Maybe this indicates a bug in Yang parser.
809 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
812 return resultDataSchemaNode;
815 throw new IllegalStateException(
816 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
821 * Returns a generated type builder for an augmentation.
823 * The name of the type builder is equal to the name of augmented node with
824 * serial number as suffix.
828 * @param augmentPackageName
829 * string with contains the package name to which the augment
831 * @param basePackageName
832 * string with the package name to which the augmented node
834 * @param targetTypeRef
837 * augmentation schema which contains data about the child nodes
838 * and uses of augment
839 * @return generated type builder for augment
841 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
842 final String augmentPackageName, final Type targetTypeRef,
843 final AugmentationSchemaNode augSchema) {
844 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
845 if (augmentBuilders == null) {
846 augmentBuilders = new HashMap<>();
847 genTypeBuilders.put(augmentPackageName, augmentBuilders);
849 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
852 if (augIdentifier != null) {
853 augTypeName = BindingMapping.getClassName(augIdentifier);
855 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
858 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
859 JavaTypeName.create(augmentPackageName, augTypeName));
861 augTypeBuilder.addImplementsType(DATA_OBJECT);
862 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
863 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
864 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
866 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
867 augmentBuilders.put(augTypeName, augTypeBuilder);
869 if (!augSchema.getChildNodes().isEmpty()) {
870 context.addTypeToAugmentation(augTypeBuilder, augSchema);
873 context.addAugmentType(augTypeBuilder);
874 return augTypeBuilder;
877 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
878 final AugmentationSchemaNode augSchema) {
879 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
884 * @param unknownSchemaNodes
885 * @return nodeParameter of UnknownSchemaNode
887 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
888 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
889 final QName nodeType = unknownSchemaNode.getNodeType();
890 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
891 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
892 return unknownSchemaNode.getNodeParameter();
899 * Returns first unique name for the augment generated type builder. The
900 * generated type builder name for augment consists from name of augmented
901 * node and serial number of its augmentation.
904 * map of builders which were created in the package to which the
905 * augmentation belongs
907 * string with name of augmented node
908 * @return string with unique name for augmentation builder
910 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
912 if (builders != null) {
913 while (builders.containsKey(genTypeName + index)) {
917 return genTypeName + index;
921 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
922 * node for which <code>typeBuilder</code> was created.
924 * The subnodes aren't mapped to the methods if they are part of grouping or
925 * augment (in this case are already part of them).
930 * generated type builder which represents any node. The subnodes
931 * of this node are added to the <code>typeBuilder</code> as
932 * methods. The subnode can be of type leaf, leaf-list, list,
937 * set of data schema nodes which are the children of the node
938 * for which <code>typeBuilder</code> was created
939 * @return generated type builder which is the same builder as input
940 * parameter. The getter methods (representing child nodes) could be
943 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
944 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
945 if (schemaNodes != null && parent != null) {
946 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
947 for (final DataSchemaNode schemaNode : schemaNodes) {
948 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
949 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
957 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
958 * node for which <code>typeBuilder</code> was created.
963 * generated type builder which represents any node. The subnodes
964 * of this node are added to the <code>typeBuilder</code> as
965 * methods. The subnode can be of type leaf, leaf-list, list,
970 * set of data schema nodes which are the children of the node
971 * for which <code>typeBuilder</code> was created
972 * @return generated type builder which is the same object as the input
973 * parameter <code>typeBuilder</code>. The getter method could be
976 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
977 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
978 if (schemaNodes != null && typeBuilder != null) {
979 final Type baseInterface = childOf(typeBuilder);
980 for (final DataSchemaNode schemaNode : schemaNodes) {
981 if (!schemaNode.isAugmenting()) {
982 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
990 * Adds to <code>typeBuilder</code> a method which is derived from
991 * <code>schemaNode</code>.
994 * data schema node which is added to <code>typeBuilder</code> as
997 * generated type builder to which is <code>schemaNode</code>
1004 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1005 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1006 if (node != null && typeBuilder != null) {
1007 if (node instanceof LeafSchemaNode) {
1008 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1009 } else if (node instanceof LeafListSchemaNode) {
1010 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1011 } else if (node instanceof ContainerSchemaNode) {
1012 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1013 } else if (node instanceof ListSchemaNode) {
1014 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1015 } else if (node instanceof ChoiceSchemaNode) {
1016 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1018 // TODO: anyxml not yet supported
1019 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1020 typeBuilder.getFullyQualifiedName());
1026 * Converts <code>choiceNode</code> to the list of generated types for
1027 * choice and its cases.
1029 * The package names for choice and for its cases are created as
1030 * concatenation of the module package (<code>basePackageName</code>) and
1031 * names of all parents node.
1035 * @param basePackageName
1036 * string with the module package name
1040 * choice node which is mapped to generated type. Also child
1041 * nodes - cases are mapped to generated types.
1042 * @throws IllegalArgumentException
1044 * <li>if <code>basePackageName</code> is null</li>
1045 * <li>if <code>choiceNode</code> is null</li>
1048 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1049 final ChoiceSchemaNode choiceNode) {
1050 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1052 if (!choiceNode.isAddedByUses()) {
1053 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1054 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1055 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1056 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1057 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1058 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1060 final GeneratedType choiceType = choiceTypeBuilder.build();
1061 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1063 constructGetter(parent, choiceType, choiceNode);
1068 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1070 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1071 * The package names for the builder is created as concatenation of the module package and names of all parents
1072 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1073 * and <i>choice</i> type
1076 * current module context
1077 * @param refChoiceType
1078 * type which represents superior <i>case</i>
1080 * choice case node which is mapped to generated type
1081 * @throws IllegalArgumentException
1083 * <li>if <code>refChoiceType</code> equals null</li>
1084 * <li>if <code>caseNodes</code> equals null</li>
1087 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1088 final ChoiceSchemaNode choiceNode) {
1089 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1090 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1092 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1093 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1094 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1095 caseTypeBuilder.addImplementsType(refChoiceType);
1096 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1097 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1098 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1099 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1100 if (caseChildNodes != null) {
1101 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1103 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1104 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1106 if (parent instanceof AugmentationSchemaNode) {
1107 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1108 final SchemaPath targetPath = augSchema.getTargetPath();
1109 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1110 if (targetSchemaNode instanceof DataSchemaNode
1111 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1112 if (targetSchemaNode instanceof DerivableSchemaNode) {
1113 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1116 if (targetSchemaNode == null) {
1117 throw new IllegalStateException(
1118 "Failed to find target node from grouping for augmentation " + augSchema
1119 + " in module " + context.module().getName());
1122 parent = targetSchemaNode;
1125 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1126 Type childOfType = findChildNodeByPath(parent.getPath());
1127 if (childOfType == null) {
1128 childOfType = findGroupingByPath(parent.getPath());
1130 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1132 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1136 processUsesAugments(caseNode, context);
1141 * Generates list of generated types for all the cases of a choice which are
1142 * added to the choice through the augment.
1146 * @param basePackageName
1147 * string contains name of package to which augment belongs. If
1148 * an augmented choice is from an other package (pcg1) than an
1149 * augmenting choice (pcg2) then case's of the augmenting choice
1150 * will belong to pcg2.
1152 * Type which represents target choice
1154 * node which represents target choice
1155 * @param augmentedNodes
1156 * set of choice case nodes for which is checked if are/aren't
1157 * added to choice through augmentation
1158 * @throws IllegalArgumentException
1160 * <li>if <code>basePackageName</code> is null</li>
1161 * <li>if <code>targetType</code> is null</li>
1162 * <li>if <code>augmentedNodes</code> is null</li>
1165 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1166 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1167 final DataNodeContainer usesNodeParent) {
1168 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1169 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1171 for (final DataSchemaNode caseNode : augmentedNodes) {
1172 if (caseNode != null) {
1173 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1174 caseTypeBuilder.addImplementsType(targetType);
1176 CaseSchemaNode node = null;
1177 final String caseLocalName = caseNode.getQName().getLocalName();
1178 if (caseNode instanceof CaseSchemaNode) {
1179 node = (CaseSchemaNode) caseNode;
1180 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1181 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1182 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1183 if (dataSchemaNode instanceof ChoiceSchemaNode
1184 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1185 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1190 node = findNamedCase(targetNode, caseLocalName);
1192 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1193 if (childNodes != null) {
1194 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1196 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1197 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1202 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1203 final SchemaPath nodePath = targetNode.getPath();
1204 final SchemaPath parentSp = nodePath.getParent();
1205 if (parentSp.getParent() == null) {
1206 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1209 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1210 GeneratedTypeBuilder childOfType = null;
1211 if (parent instanceof CaseSchemaNode) {
1212 childOfType = findCaseByPath(parent.getPath());
1213 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1214 childOfType = findChildNodeByPath(parent.getPath());
1215 } else if (parent instanceof GroupingDefinition) {
1216 childOfType = findGroupingByPath(parent.getPath());
1219 if (childOfType == null) {
1220 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1226 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1227 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1228 return cases.isEmpty() ? null : cases.get(0);
1231 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1232 // New parser with encapsulated type
1233 if (leaf.getPath().equals(type.getPath())) {
1237 // Embedded type definition with new parser. Also takes care of the old parser with bits
1238 if (leaf.getPath().equals(type.getPath().getParent())) {
1245 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1246 final List<PatternConstraint> patternConstraints) {
1247 if (!patternConstraints.isEmpty()) {
1248 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1249 .append(BindingMapping.getPropertyName(leafName));
1250 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1251 typeProvider.resolveRegExpressions(patternConstraints));
1256 * Converts <code>leaf</code> to the getter method which is added to
1257 * <code>typeBuilder</code>.
1259 * @param typeBuilder
1260 * generated type builder to which is added getter method as
1261 * <code>leaf</code> mapping
1263 * leaf schema node which is mapped as getter method which is
1264 * added to <code>typeBuilder</code>
1266 * Module in which type was defined
1267 * @return boolean value
1269 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1271 * <li>true - in other cases</li>
1274 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1275 final ModuleContext context) {
1276 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1280 final Module parentModule = findParentModule(schemaContext, leaf);
1281 Type returnType = null;
1283 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1284 if (isInnerType(leaf, typeDef)) {
1285 if (typeDef instanceof EnumTypeDefinition) {
1286 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1287 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1288 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1289 typeBuilder, context);
1290 if (enumBuilder != null) {
1291 returnType = enumBuilder.toInstance(typeBuilder);
1293 typeProvider.putReferencedType(leaf.getPath(), returnType);
1294 } else if (typeDef instanceof UnionTypeDefinition) {
1295 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1297 if (genTOBuilder != null) {
1298 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1299 // Store the inner type within the union so that we can find the reference for it
1300 context.addInnerTypedefType(typeDef.getPath(), returnType);
1302 } else if (typeDef instanceof BitsTypeDefinition) {
1303 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1305 if (genTOBuilder != null) {
1306 returnType = genTOBuilder.build();
1309 // It is constrained version of already declared type (inner declared type exists,
1310 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1311 // In order to get proper class we need to look up closest derived type
1312 // and apply restrictions from leaf type
1313 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1314 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1316 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1319 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1320 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1321 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1324 if (returnType == null) {
1328 if (typeDef instanceof EnumTypeDefinition) {
1329 typeProvider.putReferencedType(leaf.getPath(), returnType);
1332 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1333 processContextRefExtension(leaf, getter, parentModule);
1337 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1338 // Returns DerivedType in case of new parser.
1339 final TypeDefinition<?> baseType = typeDef.getBaseType();
1340 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1343 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1344 final Module module) {
1345 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1346 final QName nodeType = node.getNodeType();
1347 if ("context-reference".equals(nodeType.getLocalName())) {
1348 final String nodeParam = node.getNodeParameter();
1349 IdentitySchemaNode identity = null;
1350 String basePackageName = null;
1351 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1352 final Iterator<String> iterator = splittedElement.iterator();
1353 final int length = Iterables.size(splittedElement);
1355 identity = findIdentityByName(module.getIdentities(), iterator.next());
1356 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1357 } else if (length == 2) {
1358 final String prefix = iterator.next();
1359 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1360 if (dependentModule == null) {
1361 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1364 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1365 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1367 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1370 if (identity == null) {
1371 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1375 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1376 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1377 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1378 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1383 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1384 for (final IdentitySchemaNode id : identities) {
1385 if (id.getQName().getLocalName().equals(name)) {
1392 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1393 for (final ModuleImport imp : imports) {
1394 if (imp.getPrefix().equals(prefix)) {
1395 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1401 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1402 final boolean isReadOnly) {
1403 if (leaf != null && toBuilder != null) {
1405 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1406 if (typeDef instanceof UnionTypeDefinition) {
1407 // GeneratedType for this type definition should have be already created
1408 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1409 returnType = mc.getTypedefs().get(typeDef.getPath());
1410 if (returnType == null) {
1411 // This may still be an inner type, try to find it
1412 returnType = mc.getInnerType(typeDef.getPath());
1414 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1415 // Annonymous enumeration (already generated, since it is inherited via uses).
1416 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1417 QName qname = originalLeaf.getQName();
1418 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1420 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1422 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1428 * Converts <code>leaf</code> schema node to property of generated TO
1432 * generated TO builder to which is <code>leaf</code> added as
1435 * leaf schema node which is added to <code>toBuilder</code> as
1440 * boolean value which says if leaf property is|isn't read only
1441 * @return boolean value
1443 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1444 * name equals null or if leaf is added by <i>uses</i>.</li>
1445 * <li>true - other cases</li>
1448 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1449 final Type returnType, final boolean isReadOnly) {
1450 if (returnType == null) {
1453 final String leafName = leaf.getQName().getLocalName();
1454 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1455 propBuilder.setReadOnly(isReadOnly);
1456 propBuilder.setReturnType(returnType);
1457 addComment(propBuilder, leaf);
1459 toBuilder.addEqualsIdentity(propBuilder);
1460 toBuilder.addHashIdentity(propBuilder);
1461 toBuilder.addToStringProperty(propBuilder);
1466 * Converts <code>node</code> leaf list schema node to getter method of
1467 * <code>typeBuilder</code>.
1469 * @param typeBuilder
1470 * generated type builder to which is <code>node</code> added as
1473 * leaf list schema node which is added to
1474 * <code>typeBuilder</code> as getter method
1475 * @param module module
1476 * @return boolean value
1478 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1479 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1480 * <li>false - other cases</li>
1483 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1484 final ModuleContext context) {
1485 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1489 final QName nodeName = node.getQName();
1491 final TypeDefinition<?> typeDef = node.getType();
1492 final Module parentModule = findParentModule(schemaContext, node);
1494 Type returnType = null;
1495 if (typeDef.getBaseType() == null) {
1496 if (typeDef instanceof EnumTypeDefinition) {
1497 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1498 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1499 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1500 typeBuilder, context);
1501 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1502 typeProvider.putReferencedType(node.getPath(), returnType);
1503 } else if (typeDef instanceof UnionTypeDefinition) {
1504 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1505 node, parentModule);
1506 if (genTOBuilder != null) {
1507 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1509 } else if (typeDef instanceof BitsTypeDefinition) {
1510 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1511 node, parentModule);
1512 returnType = genTOBuilder.build();
1514 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1515 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1516 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1519 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1520 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1521 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1524 final ParameterizedType listType = Types.listTypeFor(returnType);
1525 constructGetter(typeBuilder, listType, node);
1529 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1530 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1531 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1533 addCodegenInformation(returnType, parentModule, typeDef);
1534 returnType.setSchemaPath(typeDef.getPath());
1535 returnType.setModuleName(parentModule.getName());
1537 genTOBuilder.setTypedef(true);
1538 genTOBuilder.setIsUnion(true);
1539 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1543 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1546 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1547 method.setReturnType(returnType);
1548 method.addParameter(Types.STRING, "defaultValue");
1549 method.setAccessModifier(AccessModifier.PUBLIC);
1550 method.setStatic(true);
1552 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1553 if (types == null) {
1554 typeProvider.getAdditionalTypes().put(parentModule,
1555 Sets.newHashSet(unionBuilder.build()));
1557 types.add(unionBuilder.build());
1559 return returnType.build();
1562 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1563 final GeneratedTypeBuilder typeBuilder) {
1564 // Append enclosing path hierarchy without dots
1565 final StringBuilder sb = new StringBuilder();
1566 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1567 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1568 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1569 unionBuilder.setIsUnionBuilder(true);
1570 return unionBuilder;
1573 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1574 final SchemaNode schemaNode) {
1575 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1578 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1579 final SchemaNode schemaNode, final Type baseInterface) {
1580 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1581 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1586 * Instantiates generated type builder with <code>packageName</code> and
1587 * <code>schemaNode</code>.
1589 * The new builder always implements
1590 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1591 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1592 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1594 * If <code>schemaNode</code> is instance of
1595 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1596 * DataNodeContainer} it can also implement nodes which are specified in
1599 * @param packageName
1600 * string with the name of the package to which
1601 * <code>schemaNode</code> belongs.
1603 * schema node for which is created generated type builder
1605 * parent type (can be null)
1606 * @return generated type builder <code>schemaNode</code>
1608 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1609 final Type baseInterface, final ModuleContext context) {
1610 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1611 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1613 it.addImplementsType(baseInterface);
1614 if (!(schemaNode instanceof GroupingDefinition)) {
1615 it.addImplementsType(augmentable(it));
1617 if (schemaNode instanceof DataNodeContainer) {
1618 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1619 groupingsToGenTypes(context, containerSchema.getGroupings());
1620 addImplementedInterfaceFromUses(containerSchema, it);
1627 * Wraps the calling of the same overloaded method.
1629 * @param packageName
1630 * string with the package name to which returning generated type
1633 * schema node which provide data about the schema node name
1634 * @return generated type builder for <code>schemaNode</code>
1636 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1637 final String prefix) {
1638 return addRawInterfaceDefinition(
1639 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1640 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1644 * Returns reference to generated type builder for specified
1645 * <code>schemaNode</code> with <code>packageName</code>.
1647 * Firstly the generated type builder is searched in
1648 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1649 * found it is created and added to <code>genTypeBuilders</code>.
1651 * @param packageName
1652 * string with the package name to which returning generated type
1655 * schema node which provide data about the schema node name
1657 * return type name prefix
1658 * @return generated type builder for <code>schemaNode</code>
1659 * @throws IllegalArgumentException
1661 * <li>if <code>schemaNode</code> is null</li>
1662 * <li>if <code>packageName</code> is null</li>
1663 * <li>if QName of schema node is null</li>
1664 * <li>if schemaNode name is null</li>
1668 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1669 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1670 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1671 final String schemaNodeName = schemaNode.getQName().getLocalName();
1672 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1674 // FIXME: Validation of name conflict
1675 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1676 final Module module = findParentModule(schemaContext, schemaNode);
1677 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1678 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1680 addCodegenInformation(newType, module, schemaNode);
1681 newType.setSchemaPath(schemaNode.getPath());
1682 newType.setModuleName(module.getName());
1684 final String packageName = identifier.packageName();
1685 final String simpleName = identifier.simpleName();
1686 if (!genTypeBuilders.containsKey(packageName)) {
1687 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1688 builders.put(simpleName, newType);
1689 genTypeBuilders.put(packageName, builders);
1691 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1692 if (!builders.containsKey(simpleName)) {
1693 builders.put(simpleName, newType);
1700 * Creates the name of the getter method name from <code>localName</code>.
1703 * string with the name of the getter method
1706 * @return string with the name of the getter method for
1707 * <code>methodName</code> in JAVA method format
1709 public static String getterMethodName(final String localName, final Type returnType) {
1710 final StringBuilder method = new StringBuilder();
1711 if (BOOLEAN.equals(returnType)) {
1712 method.append("is");
1714 method.append("get");
1716 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1717 method.append(name);
1718 return method.toString();
1722 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1724 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1725 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1727 * @param interfaceBuilder generated type builder for which the getter method should be created
1728 * @param returnType type which represents the return type of the getter method
1729 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1730 * @param comment string with comment for the getter method
1731 * @param status status from yang file, for deprecated annotation
1732 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1734 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1735 final SchemaNode node) {
1736 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1737 getterMethodName(node.getQName().getLocalName(), returnType));
1738 getMethod.setReturnType(returnType);
1740 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1741 if (!returnType.getPackageName().isEmpty()) {
1742 // The return type has a package, so it's not a primitive type
1743 getMethod.addAnnotation("javax.annotation", "Nullable");
1745 addComment(getMethod, node);
1751 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1752 * or to <code>genTOBuilder</code> as property.
1754 * @param basePackageName
1755 * string contains the module package name
1757 * data schema node which should be added as getter method to
1758 * <code>typeBuilder</code> or as a property to
1759 * <code>genTOBuilder</code> if is part of the list key
1760 * @param typeBuilder
1761 * generated type builder for the list schema node
1762 * @param genTOBuilder
1763 * generated TO builder for the list keys
1765 * list of string which contains names of the list keys
1768 * @throws IllegalArgumentException
1770 * <li>if <code>schemaNode</code> equals null</li>
1771 * <li>if <code>typeBuilder</code> equals null</li>
1774 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1775 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1776 final List<String> listKeys) {
1777 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1778 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1780 if (schemaNode instanceof LeafSchemaNode) {
1781 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1782 final String leafName = leaf.getQName().getLocalName();
1783 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1784 if (listKeys.contains(leafName)) {
1786 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1788 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1791 } else if (!schemaNode.isAddedByUses()) {
1792 if (schemaNode instanceof LeafListSchemaNode) {
1793 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1794 } else if (schemaNode instanceof ContainerSchemaNode) {
1795 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1796 (ContainerSchemaNode) schemaNode);
1797 } else if (schemaNode instanceof ChoiceSchemaNode) {
1798 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1799 } else if (schemaNode instanceof ListSchemaNode) {
1800 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1805 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1806 final GeneratedTOBuilder genTOBuilder) {
1807 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1809 if (genTOBuilder != null) {
1810 final GeneratedTransferObject genTO = genTOBuilder.build();
1811 // Add Identifiable.getKey() for items
1812 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1813 .addAnnotation(OVERRIDE_ANNOTATION);
1814 context.addGeneratedTOBuilder(genTOBuilder);
1819 * Selects the names of the list keys from <code>list</code> and returns
1820 * them as the list of the strings
1823 * of string with names of the list keys
1824 * @return list of string which represents names of the list keys. If the
1825 * <code>list</code> contains no keys then the empty list is
1828 private static List<String> listKeys(final ListSchemaNode list) {
1829 final List<String> listKeys = new ArrayList<>();
1831 final List<QName> keyDefinition = list.getKeyDefinition();
1832 if (keyDefinition != null) {
1833 for (final QName keyDef : keyDefinition) {
1834 listKeys.add(keyDef.getLocalName());
1841 * Generates for the <code>list</code> which contains any list keys special
1842 * generated TO builder.
1844 * @param packageName
1845 * string with package name to which the list belongs
1847 * list schema node which is source of data about the list name
1848 * @return generated TO builder which represents the keys of the
1849 * <code>list</code> or null if <code>list</code> is null or list of
1850 * key definitions is null or empty.
1852 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1853 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1854 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1855 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1856 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1862 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1864 * If more then one generated TO builder is created for enclosing then all
1865 * of the generated TO builders are added to <code>typeBuilder</code> as
1866 * enclosing transfer objects.
1869 * type definition which can be of type <code>UnionType</code> or
1870 * <code>BitsTypeDefinition</code>
1871 * @param typeBuilder
1872 * generated type builder to which is added generated TO created
1873 * from <code>typeDef</code>
1875 * string with name for generated TO builder
1876 * @param parentModule
1878 * @return generated TO builder for <code>typeDef</code>
1880 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1881 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1882 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1883 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1886 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1887 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1888 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1889 for (final GeneratedTOBuilder genTOBuilder : types) {
1890 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1893 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1894 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1895 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1896 resultTOBuilder.addHashIdentity(genPropBuilder);
1897 resultTOBuilder.addToStringProperty(genPropBuilder);
1898 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1899 return resultTOBuilder;
1903 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1904 * also added to <code>typeBuilder</code> as enclosing transfer object.
1906 * If more then one generated TO builder is created for enclosing then all
1907 * of the generated TO builders are added to <code>typeBuilder</code> as
1908 * enclosing transfer objects.
1911 * type definition which can be of type <code>UnionType</code> or
1912 * <code>BitsTypeDefinition</code>
1913 * @param typeBuilder
1914 * generated type builder to which is added generated TO created
1915 * from <code>typeDef</code>
1917 * string with name for generated TO builder
1918 * @param parentModule
1920 * @return generated TO builder for <code>typeDef</code>
1922 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1923 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1924 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1925 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1926 typeDef, parentModule.getName());
1927 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1928 return genTOBuilder;
1932 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1933 final List<GeneratedTOBuilder> genTOBuilders) {
1934 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1935 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1937 return genTOBuilders.get(0);
1941 * Adds the implemented types to type builder.
1943 * The method passes through the list of <i>uses</i> in
1944 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1945 * generated type from {@link ModuleContext#groupings
1946 * allGroupings} which is added as <i>implements type</i> to
1947 * <code>builder</code>
1949 * @param dataNodeContainer
1950 * element which contains the list of used YANG groupings
1952 * builder to which are added implemented types according to
1953 * <code>dataNodeContainer</code>
1954 * @return generated type builder with all implemented types
1956 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1957 final GeneratedTypeBuilder builder) {
1958 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1959 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1960 if (genType == null) {
1961 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1962 + builder.getName());
1965 builder.addImplementsType(genType);
1970 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1971 for (final ModuleContext ctx : genCtx.values()) {
1972 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1973 if (result != null) {
1980 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1981 for (final ModuleContext ctx : genCtx.values()) {
1982 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1983 if (result != null) {
1990 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1991 for (final ModuleContext ctx : genCtx.values()) {
1992 final GeneratedTypeBuilder result = ctx.getCase(path);
1993 if (result != null) {
2000 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2001 if (status == Status.DEPRECATED) {
2002 builder.addAnnotation(DEPRECATED_ANNOTATION);