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.IDENTIFIABLE;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
29 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
30 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
31 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
32 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
33 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
34 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
36 import com.google.common.base.Splitter;
37 import com.google.common.collect.Iterables;
38 import com.google.common.collect.Sets;
39 import java.util.AbstractMap.SimpleImmutableEntry;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Comparator;
43 import java.util.HashMap;
44 import java.util.Iterator;
45 import java.util.List;
47 import java.util.Optional;
49 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
50 import org.opendaylight.mdsal.binding.model.api.Constant;
51 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
52 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
53 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
54 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
55 import org.opendaylight.mdsal.binding.model.api.Restrictions;
56 import org.opendaylight.mdsal.binding.model.api.Type;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
66 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
67 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
68 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
69 import org.opendaylight.mdsal.binding.model.util.Types;
70 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
71 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
72 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
73 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
74 import org.opendaylight.yangtools.yang.binding.BindingMapping;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.QNameModule;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
105 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
107 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
113 abstract class AbstractTypeGenerator {
114 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
115 private static final Splitter COLON_SPLITTER = Splitter.on(':');
116 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
117 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
120 * Comparator based on augment target path.
122 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
123 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
124 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
126 while (thisIt.hasNext()) {
127 if (!otherIt.hasNext()) {
131 final int comp = thisIt.next().compareTo(otherIt.next());
137 return otherIt.hasNext() ? -1 : 0;
141 * Constant with the concrete name of identifier.
143 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
146 * Constant with the concrete name of namespace.
148 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
150 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
153 * Outer key represents the package name. Outer value represents map of all
154 * builders in the same package. Inner key represents the schema node name
155 * (in JAVA class/interface name format). Inner value represents instance of
156 * builder for schema node specified in key part.
158 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
161 * Provide methods for converting YANG types to JAVA types.
163 private final AbstractTypeProvider typeProvider;
166 * Holds reference to schema context to resolve data of augmented element
167 * when creating augmentation builder
169 private final SchemaContext schemaContext;
171 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
172 this.schemaContext = requireNonNull(context);
173 this.typeProvider = requireNonNull(typeProvider);
175 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
176 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
177 for (final Module contextModule : contextModules) {
178 contexts.add(moduleToGenTypes(contextModule));
181 contexts.forEach(this::allAugmentsToGenTypes);
184 final Collection<ModuleContext> moduleContexts() {
185 return genCtx.values();
188 final ModuleContext moduleContext(final QNameModule module) {
189 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
192 final AbstractTypeProvider typeProvider() {
196 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
198 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
200 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
201 Set<? extends SchemaNode> nodes);
203 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
205 private ModuleContext moduleToGenTypes(final Module module) {
206 final ModuleContext context = new ModuleContext(module);
207 genCtx.put(module.getQNameModule(), context);
208 allTypeDefinitionsToGenTypes(context);
209 groupingsToGenTypes(context, module.getGroupings());
210 rpcMethodsToGenType(context);
211 allIdentitiesToGenTypes(context);
212 notificationsToGenType(context);
214 if (!module.getChildNodes().isEmpty()) {
215 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
216 context.addModuleNode(moduleType);
217 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
223 * Converts all extended type definitions of module to the list of
224 * <code>Type</code> objects.
227 * module from which is obtained set of type definitions
228 * @throws IllegalArgumentException
230 * <li>if module is null</li>
231 * <li>if name of module is null</li>
233 * @throws IllegalStateException
234 * if set of type definitions from module is null
236 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
237 final Module module = context.module();
238 checkArgument(module.getName() != null, "Module name cannot be NULL.");
239 final DataNodeIterator it = new DataNodeIterator(module);
240 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
241 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
243 for (final TypeDefinition<?> typedef : typeDefinitions) {
244 if (typedef != null) {
245 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
247 context.addTypedefType(typedef.getPath(), type);
248 context.addTypeToSchema(type,typedef);
254 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final GeneratedTypeBuilder childOf,
255 final DataSchemaNode node) {
256 if (node.isAugmenting() || node.isAddedByUses()) {
259 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
260 annotateDeprecatedIfNecessary(node.getStatus(), genType);
262 final Module module = context.module();
263 genType.setModuleName(module.getName());
264 addCodegenInformation(genType, module, node);
265 genType.setSchemaPath(node.getPath());
266 if (node instanceof DataNodeContainer) {
267 context.addChildNodeType(node, genType);
268 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
269 processUsesAugments((DataNodeContainer) node, context);
274 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
275 final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
276 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
277 if (genType != null) {
278 constructGetter(parent, genType, node);
279 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
283 private void listToGenType(final ModuleContext context,
284 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
285 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
286 if (genType != null) {
287 constructGetter(parent, Types.listTypeFor(genType), node);
289 final List<String> listKeys = listKeys(node);
290 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
291 if (genTOBuilder != null) {
292 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
293 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
294 genTOBuilder.addImplementsType(identifierMarker);
295 genType.addImplementsType(identifiableMarker);
298 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
299 if (!schemaNode.isAugmenting()) {
300 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
305 if (genTOBuilder != null) {
306 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
307 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
308 genTOBuilder.setSUID(prop);
311 typeBuildersToGenTypes(context, genType, genTOBuilder);
315 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
316 for (final UsesNode usesNode : node.getUses()) {
317 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
318 usesAugmentationToGenTypes(context, augment, usesNode, node);
319 processUsesAugments(augment, context);
325 * Converts all <b>augmentation</b> of the module to the list
326 * <code>Type</code> objects.
329 * module from which is obtained list of all augmentation objects
330 * to iterate over them
331 * @throws IllegalArgumentException
333 * <li>if the module is null</li>
334 * <li>if the name of module is null</li>
336 * @throws IllegalStateException
337 * if set of augmentations from module is null
339 private void allAugmentsToGenTypes(final ModuleContext context) {
340 final Module module = context.module();
341 checkArgument(module != null, "Module reference cannot be NULL.");
342 checkArgument(module.getName() != null, "Module name cannot be NULL.");
343 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
345 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
346 augmentationToGenTypes(context, augment);
351 * Returns list of <code>AugmentationSchema</code> objects. The objects are
352 * sorted according to the length of their target path from the shortest to
356 * module from which is obtained list of all augmentation objects
357 * @return list of sorted <code>AugmentationSchema</code> objects obtained
358 * from <code>module</code>
359 * @throws IllegalArgumentException
361 * @throws IllegalStateException
362 * if set of module augmentations is null
364 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
365 checkArgument(module != null, "Module reference cannot be NULL.");
366 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
368 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
369 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
370 sortedAugmentations.sort(AUGMENT_COMP);
372 return sortedAugmentations;
376 * Create GeneratedTypeBuilder object from module argument.
379 * Module object from which builder will be created
380 * @return <code>GeneratedTypeBuilder</code> which is internal
381 * representation of the module
382 * @throws IllegalArgumentException
385 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
386 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
387 final Module module = context.module();
388 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
389 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
391 addCodegenInformation(moduleDataTypeBuilder, module);
392 return moduleDataTypeBuilder;
396 * Converts all <b>RPCs</b> input and output substatements of the module
397 * to the list of <code>Type</code> objects. In addition are to containers
398 * and lists which belong to input or output also part of returning list.
401 * module from which is obtained set of all rpc objects to
403 * @throws IllegalArgumentException
405 * <li>if the module is null</li>
406 * <li>if the name of module is null</li>
408 * @throws IllegalStateException
409 * if set of rpcs from module is null
411 private void rpcMethodsToGenType(final ModuleContext context) {
412 final Module module = context.module();
413 checkArgument(module.getName() != null, "Module name cannot be NULL.");
414 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
415 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
416 if (rpcDefinitions.isEmpty()) {
420 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
421 interfaceBuilder.addImplementsType(RPC_SERVICE);
423 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
425 for (final RpcDefinition rpc : rpcDefinitions) {
427 final String rpcName = BindingMapping.getClassName(rpc.getQName());
428 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
429 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
431 // Do not refer to annotation class, as it may not be available at runtime
432 method.addAnnotation("javax.annotation", "CheckReturnValue");
433 addComment(method, rpc);
435 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
436 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
437 Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class),
438 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, null, 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, 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 GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
945 if (schemaNodes != null && parent != null) {
946 for (final DataSchemaNode schemaNode : schemaNodes) {
947 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
948 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
956 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
957 * node for which <code>typeBuilder</code> was created.
962 * generated type builder which represents any node. The subnodes
963 * of this node are added to the <code>typeBuilder</code> as
964 * methods. The subnode can be of type leaf, leaf-list, list,
969 * set of data schema nodes which are the children of the node
970 * for which <code>typeBuilder</code> was created
971 * @return generated type builder which is the same object as the input
972 * parameter <code>typeBuilder</code>. The getter method could be
975 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
976 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
977 final Iterable<DataSchemaNode> schemaNodes) {
978 if (schemaNodes != null && typeBuilder != null) {
979 for (final DataSchemaNode schemaNode : schemaNodes) {
980 if (!schemaNode.isAugmenting()) {
981 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
989 * Adds to <code>typeBuilder</code> a method which is derived from
990 * <code>schemaNode</code>.
993 * data schema node which is added to <code>typeBuilder</code> as
996 * generated type builder to which is <code>schemaNode</code>
1003 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1004 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf) {
1005 if (node != null && typeBuilder != null) {
1006 if (node instanceof LeafSchemaNode) {
1007 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1008 } else if (node instanceof LeafListSchemaNode) {
1009 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1010 } else if (node instanceof ContainerSchemaNode) {
1011 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1012 } else if (node instanceof ListSchemaNode) {
1013 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1014 } else if (node instanceof ChoiceSchemaNode) {
1015 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1017 // TODO: anyxml not yet supported
1018 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1019 typeBuilder.getFullyQualifiedName());
1025 * Converts <code>choiceNode</code> to the list of generated types for
1026 * choice and its cases.
1028 * The package names for choice and for its cases are created as
1029 * concatenation of the module package (<code>basePackageName</code>) and
1030 * names of all parents node.
1034 * @param basePackageName
1035 * string with the module package name
1039 * choice node which is mapped to generated type. Also child
1040 * nodes - cases are mapped to generated types.
1041 * @throws IllegalArgumentException
1043 * <li>if <code>basePackageName</code> is null</li>
1044 * <li>if <code>choiceNode</code> is null</li>
1047 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1048 final ChoiceSchemaNode choiceNode) {
1049 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1051 if (!choiceNode.isAddedByUses()) {
1052 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1053 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1054 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1055 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1056 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1057 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1059 final GeneratedType choiceType = choiceTypeBuilder.build();
1060 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1062 constructGetter(parent, choiceType, choiceNode);
1067 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1069 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1070 * The package names for the builder is created as concatenation of the module package and names of all parents
1071 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1072 * and <i>choice</i> type
1075 * current module context
1076 * @param refChoiceType
1077 * type which represents superior <i>case</i>
1079 * choice case node which is mapped to generated type
1080 * @throws IllegalArgumentException
1082 * <li>if <code>refChoiceType</code> equals null</li>
1083 * <li>if <code>caseNodes</code> equals null</li>
1086 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1087 final ChoiceSchemaNode choiceNode) {
1088 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1089 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1091 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1092 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1093 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1094 caseTypeBuilder.addImplementsType(refChoiceType);
1095 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1096 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1097 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1098 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1099 if (caseChildNodes != null) {
1100 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1102 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1103 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1105 if (parent instanceof AugmentationSchemaNode) {
1106 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1107 final SchemaPath targetPath = augSchema.getTargetPath();
1108 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1109 if (targetSchemaNode instanceof DataSchemaNode
1110 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1111 if (targetSchemaNode instanceof DerivableSchemaNode) {
1112 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1115 if (targetSchemaNode == null) {
1116 throw new IllegalStateException(
1117 "Failed to find target node from grouping for augmentation " + augSchema
1118 + " in module " + context.module().getName());
1121 parent = targetSchemaNode;
1124 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1125 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1126 if (childOfType == null) {
1127 childOfType = findGroupingByPath(parent.getPath());
1129 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1131 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1135 processUsesAugments(caseNode, context);
1140 * Generates list of generated types for all the cases of a choice which are
1141 * added to the choice through the augment.
1145 * @param basePackageName
1146 * string contains name of package to which augment belongs. If
1147 * an augmented choice is from an other package (pcg1) than an
1148 * augmenting choice (pcg2) then case's of the augmenting choice
1149 * will belong to pcg2.
1151 * Type which represents target choice
1153 * node which represents target choice
1154 * @param augmentedNodes
1155 * set of choice case nodes for which is checked if are/aren't
1156 * added to choice through augmentation
1157 * @throws IllegalArgumentException
1159 * <li>if <code>basePackageName</code> is null</li>
1160 * <li>if <code>targetType</code> is null</li>
1161 * <li>if <code>augmentedNodes</code> is null</li>
1164 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1165 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1166 final DataNodeContainer usesNodeParent) {
1167 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1168 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1170 for (final DataSchemaNode caseNode : augmentedNodes) {
1171 if (caseNode != null) {
1172 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1173 caseTypeBuilder.addImplementsType(targetType);
1175 GeneratedTypeBuilder childOfType = findChildOfType(targetNode);
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, childOfType, 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, null);
1578 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1579 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1580 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1581 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, 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 parent, final ModuleContext context) {
1610 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1611 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1613 it.addImplementsType(parent == null ? DATA_OBJECT : childOf(parent));
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, typeBuilder, (ContainerSchemaNode) schemaNode);
1796 } else if (schemaNode instanceof ChoiceSchemaNode) {
1797 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1798 } else if (schemaNode instanceof ListSchemaNode) {
1799 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1804 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1805 final GeneratedTOBuilder genTOBuilder) {
1806 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1808 if (genTOBuilder != null) {
1809 final GeneratedTransferObject genTO = genTOBuilder.build();
1810 // Add Identifiable.getKey() for items
1811 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1812 .addAnnotation(OVERRIDE_ANNOTATION);
1813 context.addGeneratedTOBuilder(genTOBuilder);
1818 * Selects the names of the list keys from <code>list</code> and returns
1819 * them as the list of the strings
1822 * of string with names of the list keys
1823 * @return list of string which represents names of the list keys. If the
1824 * <code>list</code> contains no keys then the empty list is
1827 private static List<String> listKeys(final ListSchemaNode list) {
1828 final List<String> listKeys = new ArrayList<>();
1830 final List<QName> keyDefinition = list.getKeyDefinition();
1831 if (keyDefinition != null) {
1832 for (final QName keyDef : keyDefinition) {
1833 listKeys.add(keyDef.getLocalName());
1840 * Generates for the <code>list</code> which contains any list keys special
1841 * generated TO builder.
1843 * @param packageName
1844 * string with package name to which the list belongs
1846 * list schema node which is source of data about the list name
1847 * @return generated TO builder which represents the keys of the
1848 * <code>list</code> or null if <code>list</code> is null or list of
1849 * key definitions is null or empty.
1851 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1852 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1853 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1854 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1855 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1861 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1863 * If more then one generated TO builder is created for enclosing then all
1864 * of the generated TO builders are added to <code>typeBuilder</code> as
1865 * enclosing transfer objects.
1868 * type definition which can be of type <code>UnionType</code> or
1869 * <code>BitsTypeDefinition</code>
1870 * @param typeBuilder
1871 * generated type builder to which is added generated TO created
1872 * from <code>typeDef</code>
1874 * string with name for generated TO builder
1875 * @param parentModule
1877 * @return generated TO builder for <code>typeDef</code>
1879 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1880 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1881 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1882 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1885 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1886 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1887 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1888 for (final GeneratedTOBuilder genTOBuilder : types) {
1889 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1892 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1893 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1894 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1895 resultTOBuilder.addHashIdentity(genPropBuilder);
1896 resultTOBuilder.addToStringProperty(genPropBuilder);
1897 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1898 return resultTOBuilder;
1902 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1903 * also added to <code>typeBuilder</code> as enclosing transfer object.
1905 * If more then one generated TO builder is created for enclosing then all
1906 * of the generated TO builders are added to <code>typeBuilder</code> as
1907 * enclosing transfer objects.
1910 * type definition which can be of type <code>UnionType</code> or
1911 * <code>BitsTypeDefinition</code>
1912 * @param typeBuilder
1913 * generated type builder to which is added generated TO created
1914 * from <code>typeDef</code>
1916 * string with name for generated TO builder
1917 * @param parentModule
1919 * @return generated TO builder for <code>typeDef</code>
1921 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1922 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1923 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1924 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1925 typeDef, parentModule.getName());
1926 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1927 return genTOBuilder;
1931 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1932 final List<GeneratedTOBuilder> genTOBuilders) {
1933 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1934 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1936 return genTOBuilders.get(0);
1940 * Adds the implemented types to type builder.
1942 * The method passes through the list of <i>uses</i> in
1943 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1944 * generated type from {@link ModuleContext#groupings
1945 * allGroupings} which is added as <i>implements type</i> to
1946 * <code>builder</code>
1948 * @param dataNodeContainer
1949 * element which contains the list of used YANG groupings
1951 * builder to which are added implemented types according to
1952 * <code>dataNodeContainer</code>
1953 * @return generated type builder with all implemented types
1955 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1956 final GeneratedTypeBuilder builder) {
1957 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1958 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1959 if (genType == null) {
1960 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1961 + builder.getName());
1964 builder.addImplementsType(genType);
1969 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1970 for (final ModuleContext ctx : genCtx.values()) {
1971 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1972 if (result != null) {
1979 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1980 for (final ModuleContext ctx : genCtx.values()) {
1981 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1982 if (result != null) {
1989 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1990 for (final ModuleContext ctx : genCtx.values()) {
1991 final GeneratedTypeBuilder result = ctx.getCase(path);
1992 if (result != null) {
1999 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2000 if (status == Status.DEPRECATED) {
2001 builder.addAnnotation(DEPRECATED_ANNOTATION);