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.DATA_OBJECT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
23 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
24 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
25 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.base.Splitter;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Sets;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Comparator;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Optional;
42 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
43 import org.opendaylight.mdsal.binding.model.api.Constant;
44 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
45 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
46 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
47 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
48 import org.opendaylight.mdsal.binding.model.api.Restrictions;
49 import org.opendaylight.mdsal.binding.model.api.Type;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
53 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
54 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
55 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
58 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
59 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
60 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
61 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
62 import org.opendaylight.mdsal.binding.model.util.Types;
63 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
64 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
65 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
66 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
68 import org.opendaylight.yangtools.yang.binding.BindingMapping;
69 import org.opendaylight.yangtools.yang.binding.DataContainer;
70 import org.opendaylight.yangtools.yang.binding.RpcService;
71 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.common.QNameModule;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
83 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
84 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.Module;
89 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
90 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
95 import org.opendaylight.yangtools.yang.model.api.Status;
96 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.UsesNode;
99 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
102 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
104 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
105 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
106 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
110 abstract class AbstractTypeGenerator {
111 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
112 private static final Splitter COLON_SPLITTER = Splitter.on(':');
115 * Comparator based on augment target path.
117 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
118 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
119 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
121 while (thisIt.hasNext()) {
122 if (!otherIt.hasNext()) {
126 final int comp = thisIt.next().compareTo(otherIt.next());
132 return otherIt.hasNext() ? -1 : 0;
136 * Constant with the concrete name of identifier.
138 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
141 * Constant with the concrete name of namespace.
143 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
145 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
148 * Outer key represents the package name. Outer value represents map of all
149 * builders in the same package. Inner key represents the schema node name
150 * (in JAVA class/interface name format). Inner value represents instance of
151 * builder for schema node specified in key part.
153 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
156 * Provide methods for converting YANG types to JAVA types.
158 private final AbstractTypeProvider typeProvider;
161 * Holds reference to schema context to resolve data of augmented element
162 * when creating augmentation builder
164 private final SchemaContext schemaContext;
166 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
167 this.schemaContext = requireNonNull(context);
168 this.typeProvider = requireNonNull(typeProvider);
170 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
171 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
172 for (final Module contextModule : contextModules) {
173 contexts.add(moduleToGenTypes(contextModule));
176 contexts.forEach(this::allAugmentsToGenTypes);
179 final Collection<ModuleContext> moduleContexts() {
180 return genCtx.values();
183 final ModuleContext moduleContext(final QNameModule module) {
184 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
187 final AbstractTypeProvider typeProvider() {
191 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
193 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
195 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
196 Set<? extends SchemaNode> nodes);
198 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
200 private ModuleContext moduleToGenTypes(final Module module) {
201 final ModuleContext context = new ModuleContext(module);
202 genCtx.put(module.getQNameModule(), context);
203 allTypeDefinitionsToGenTypes(context);
204 groupingsToGenTypes(context, module.getGroupings());
205 rpcMethodsToGenType(context);
206 allIdentitiesToGenTypes(context);
207 notificationsToGenType(context);
209 if (!module.getChildNodes().isEmpty()) {
210 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
211 context.addModuleNode(moduleType);
212 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
218 * Converts all extended type definitions of module to the list of
219 * <code>Type</code> objects.
222 * module from which is obtained set of type definitions
223 * @throws IllegalArgumentException
225 * <li>if module is null</li>
226 * <li>if name of module is null</li>
228 * @throws IllegalStateException
229 * if set of type definitions from module is null
231 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
232 final Module module = context.module();
233 checkArgument(module.getName() != null, "Module name cannot be NULL.");
234 final DataNodeIterator it = new DataNodeIterator(module);
235 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
236 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
238 for (final TypeDefinition<?> typedef : typeDefinitions) {
239 if (typedef != null) {
240 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
242 context.addTypedefType(typedef.getPath(), type);
243 context.addTypeToSchema(type,typedef);
249 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final GeneratedTypeBuilder childOf,
250 final DataSchemaNode node) {
251 if (node.isAugmenting() || node.isAddedByUses()) {
254 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
255 annotateDeprecatedIfNecessary(node.getStatus(), genType);
257 final Module module = context.module();
258 genType.setModuleName(module.getName());
259 addCodegenInformation(genType, module, node);
260 genType.setSchemaPath(node.getPath());
261 if (node instanceof DataNodeContainer) {
262 context.addChildNodeType(node, genType);
263 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
264 processUsesAugments((DataNodeContainer) node, context);
269 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
270 final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
271 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
272 if (genType != null) {
273 constructGetter(parent, genType, node);
274 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
278 private void listToGenType(final ModuleContext context,
279 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
280 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
281 if (genType != null) {
282 constructGetter(parent, Types.listTypeFor(genType), node);
284 final List<String> listKeys = listKeys(node);
285 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
286 if (genTOBuilder != null) {
287 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
288 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
289 genTOBuilder.addImplementsType(identifierMarker);
290 genType.addImplementsType(identifiableMarker);
293 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
294 if (!schemaNode.isAugmenting()) {
295 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
300 if (genTOBuilder != null) {
301 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
302 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
303 genTOBuilder.setSUID(prop);
306 typeBuildersToGenTypes(context, genType, genTOBuilder);
310 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
311 for (final UsesNode usesNode : node.getUses()) {
312 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
313 usesAugmentationToGenTypes(context, augment, usesNode, node);
314 processUsesAugments(augment, context);
320 * Converts all <b>augmentation</b> of the module to the list
321 * <code>Type</code> objects.
324 * module from which is obtained list of all augmentation objects
325 * to iterate over them
326 * @throws IllegalArgumentException
328 * <li>if the module is null</li>
329 * <li>if the name of module is null</li>
331 * @throws IllegalStateException
332 * if set of augmentations from module is null
334 private void allAugmentsToGenTypes(final ModuleContext context) {
335 final Module module = context.module();
336 checkArgument(module != null, "Module reference cannot be NULL.");
337 checkArgument(module.getName() != null, "Module name cannot be NULL.");
338 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
340 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
341 augmentationToGenTypes(context, augment);
346 * Returns list of <code>AugmentationSchema</code> objects. The objects are
347 * sorted according to the length of their target path from the shortest to
351 * module from which is obtained list of all augmentation objects
352 * @return list of sorted <code>AugmentationSchema</code> objects obtained
353 * from <code>module</code>
354 * @throws IllegalArgumentException
356 * @throws IllegalStateException
357 * if set of module augmentations is null
359 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
360 checkArgument(module != null, "Module reference cannot be NULL.");
361 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
363 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
364 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
365 sortedAugmentations.sort(AUGMENT_COMP);
367 return sortedAugmentations;
371 * Create GeneratedTypeBuilder object from module argument.
374 * Module object from which builder will be created
375 * @return <code>GeneratedTypeBuilder</code> which is internal
376 * representation of the module
377 * @throws IllegalArgumentException
380 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
381 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
382 final Module module = context.module();
383 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
384 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
386 addCodegenInformation(moduleDataTypeBuilder, module);
387 return moduleDataTypeBuilder;
391 * Converts all <b>RPCs</b> input and output substatements of the module
392 * to the list of <code>Type</code> objects. In addition are to containers
393 * and lists which belong to input or output also part of returning list.
396 * module from which is obtained set of all rpc objects to
398 * @throws IllegalArgumentException
400 * <li>if the module is null</li>
401 * <li>if the name of module is null</li>
403 * @throws IllegalStateException
404 * if set of rpcs from module is null
406 private void rpcMethodsToGenType(final ModuleContext context) {
407 final Module module = context.module();
408 checkArgument(module.getName() != null, "Module name cannot be NULL.");
409 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
410 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
411 if (rpcDefinitions.isEmpty()) {
415 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
416 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
418 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
420 for (final RpcDefinition rpc : rpcDefinitions) {
422 final String rpcName = BindingMapping.getClassName(rpc.getQName());
423 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
424 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
426 // Do not refer to annotation class, as it may not be available at runtime
427 method.addAnnotation("javax.annotation", "CheckReturnValue");
428 addComment(method, rpc);
430 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
431 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
432 Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class),
433 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
437 context.addTopLevelNodeType(interfaceBuilder);
440 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
441 final ContainerSchemaNode schema) {
442 processUsesAugments(schema, context);
443 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
444 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
446 addImplementedInterfaceFromUses(schema, outType);
447 outType.addImplementsType(DATA_OBJECT);
448 outType.addImplementsType(augmentable(outType));
449 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
450 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
451 context.addChildNodeType(schema, outType);
452 return outType.build();
456 * Converts all <b>notifications</b> of the module to the list of
457 * <code>Type</code> objects. In addition are to this list added containers
458 * and lists which are part of this notification.
461 * module from which is obtained set of all notification objects
462 * to iterate over them
463 * @throws IllegalArgumentException
465 * <li>if the module equals null</li>
466 * <li>if the name of module equals null</li>
468 * @throws IllegalStateException
469 * if set of notifications from module is null
471 private void notificationsToGenType(final ModuleContext context) {
472 final Module module = context.module();
473 checkArgument(module.getName() != null, "Module name cannot be NULL.");
474 final Set<NotificationDefinition> notifications = module.getNotifications();
475 if (notifications.isEmpty()) {
479 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
480 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
482 for (final NotificationDefinition notification : notifications) {
483 if (notification != null) {
484 processUsesAugments(notification, context);
486 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
487 context.modulePackageName(), notification, null, context);
488 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
489 notificationInterface.addImplementsType(NOTIFICATION);
490 context.addChildNodeType(notification, notificationInterface);
492 // Notification object
493 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
494 notification.getChildNodes());
496 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
497 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
498 .setReturnType(Types.primitiveVoidType()), notification);
502 addCodegenInformation(listenerInterface, module, "notifications", notifications);
503 context.addTopLevelNodeType(listenerInterface);
507 * Converts all <b>identities</b> of the module to the list of
508 * <code>Type</code> objects.
511 * module from which is obtained set of all identity objects to
513 * @param schemaContext
514 * schema context only used as input parameter for method
515 * {@link BindingGeneratorImpl#identityToGenType}
518 private void allIdentitiesToGenTypes(final ModuleContext context) {
519 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
521 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
522 for (final IdentitySchemaNode identity : schemaIdentities) {
523 identityToGenType(context, identity);
529 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
530 * created transport object builder. If identity contains base identity then
531 * reference to base identity is added to superior identity as its extend.
532 * If identity doesn't contain base identity then only reference to abstract
533 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
534 * BaseIdentity} is added
538 * @param basePackageName
539 * string contains the module package name
541 * IdentitySchemaNode which contains data about identity
543 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
544 if (identity == null) {
547 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
548 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
549 BindingMapping.getClassName(identity.getQName())));
550 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
551 if (baseIdentities.isEmpty()) {
552 final GeneratedTOBuilder gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(BaseIdentity.class));
553 newType.addImplementsType(gto.build());
555 for (IdentitySchemaNode baseIdentity : baseIdentities) {
556 final QName qname = baseIdentity.getQName();
557 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
558 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
559 newType.addImplementsType(gto);
563 final Module module = context.module();
564 addCodegenInformation(newType, module, identity);
565 newType.setModuleName(module.getName());
566 newType.setSchemaPath(identity.getPath());
568 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, identity.getQName());
570 context.addIdentityType(identity.getQName(), newType);
574 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
576 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
580 * Converts all <b>groupings</b> of the module to the list of
581 * <code>Type</code> objects. Firstly are groupings sorted according mutual
582 * dependencies. At least dependent (independent) groupings are in the list
583 * saved at first positions. For every grouping the record is added to map
584 * {@link ModuleContext#groupings allGroupings}
589 * collection of groupings from which types will be generated
592 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
593 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
594 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
595 // node of grouping is resolved to the method.
596 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
597 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
598 context.addGroupingType(grouping.getPath(), genType);
599 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
600 groupingsToGenTypes(context, grouping.getGroupings());
601 processUsesAugments(grouping, context);
606 * Adds enumeration builder created from <code>enumTypeDef</code> to
607 * <code>typeBuilder</code>.
609 * Each <code>enumTypeDef</code> item is added to builder with its name and
613 * EnumTypeDefinition contains enum data
615 * string contains name which will be assigned to enumeration
618 * GeneratedTypeBuilder to which will be enum builder assigned
620 * Module in which type should be generated
621 * @return enumeration builder which contains data from
622 * <code>enumTypeDef</code>
624 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
625 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
626 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
627 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
628 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
629 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
630 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
637 * Generates type builder for <code>module</code>.
640 * Module which is source of package name for generated type
643 * string which is added to the module class name representation
645 * @return instance of GeneratedTypeBuilder which represents
646 * <code>module</code>.
647 * @throws IllegalArgumentException
648 * if <code>module</code> is null
650 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
651 final Module module = context.module();
652 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
653 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
654 JavaTypeName.create(context.modulePackageName(), moduleName));
656 moduleBuilder.setModuleName(moduleName);
657 addCodegenInformation(moduleBuilder, module);
658 return moduleBuilder;
662 * Converts <code>augSchema</code> to list of <code>Type</code> which
663 * contains generated type for augmentation. In addition there are also
664 * generated types for all containers, list and choices which are child of
665 * <code>augSchema</code> node or a generated types for cases are added if
666 * augmented node is choice.
668 * @param augmentPackageName
669 * string with the name of the package to which the augmentation
672 * AugmentationSchema which is contains data about augmentation
673 * (target path, childs...)
676 * @throws IllegalArgumentException
678 * <li>if <code>augmentPackageName</code> equals null</li>
679 * <li>if <code>augSchema</code> equals null</li>
681 * @throws IllegalStateException
682 * if augment target path is null
684 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
685 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
686 checkState(augSchema.getTargetPath() != null,
687 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
689 processUsesAugments(augSchema, context);
690 final SchemaPath targetPath = augSchema.getTargetPath();
691 SchemaNode targetSchemaNode = null;
693 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
694 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
695 if (targetSchemaNode instanceof DerivableSchemaNode) {
696 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
698 if (targetSchemaNode == null) {
699 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
700 + " in module " + context.module().getName());
703 if (targetSchemaNode == null) {
704 throw new IllegalArgumentException("augment target not found: " + targetPath);
707 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
708 if (targetTypeBuilder == null) {
709 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
711 if (targetTypeBuilder == null) {
712 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
715 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
716 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
717 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
720 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
721 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
725 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
726 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
727 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
728 checkState(augSchema.getTargetPath() != null,
729 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
731 processUsesAugments(augSchema, context);
732 final SchemaPath targetPath = augSchema.getTargetPath();
733 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
734 if (targetSchemaNode == null) {
735 throw new IllegalArgumentException("augment target not found: " + targetPath);
738 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
739 if (targetTypeBuilder == null) {
740 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
742 if (targetTypeBuilder == null) {
743 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
746 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
747 if (usesNodeParent instanceof SchemaNode) {
748 addRawAugmentGenTypeDefinition(context,
749 packageNameForAugmentedGeneratedType(context.modulePackageName(),
750 ((SchemaNode) usesNodeParent).getPath()),
751 targetTypeBuilder.build(), augSchema);
753 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
756 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
757 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
762 * Convenient method to find node added by uses statement.
766 * @param parentUsesNode
767 * parent of uses node
768 * @return node from its original location in grouping
770 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
771 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
773 if (!(targetGrouping instanceof GroupingDefinition)) {
774 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
777 SchemaNode result = targetGrouping;
778 for (final QName node : targetPath.getPathFromRoot()) {
779 if (result instanceof DataNodeContainer) {
780 final QName resultNode = node.withModule(result.getQName().getModule());
781 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
782 } else if (result instanceof ChoiceSchemaNode) {
783 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
786 if (result == null) {
790 if (result instanceof DerivableSchemaNode) {
791 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
792 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
793 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
794 result = originalNode.get();
798 if (result instanceof DataSchemaNode) {
799 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
800 if (resultDataSchemaNode.isAddedByUses()) {
801 // The original node is required, but we have only the copy of
802 // the original node.
803 // Maybe this indicates a bug in Yang parser.
804 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
807 return resultDataSchemaNode;
810 throw new IllegalStateException(
811 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
816 * Returns a generated type builder for an augmentation.
818 * The name of the type builder is equal to the name of augmented node with
819 * serial number as suffix.
823 * @param augmentPackageName
824 * string with contains the package name to which the augment
826 * @param basePackageName
827 * string with the package name to which the augmented node
829 * @param targetTypeRef
832 * augmentation schema which contains data about the child nodes
833 * and uses of augment
834 * @return generated type builder for augment
836 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
837 final String augmentPackageName, final Type targetTypeRef,
838 final AugmentationSchemaNode augSchema) {
839 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
840 if (augmentBuilders == null) {
841 augmentBuilders = new HashMap<>();
842 genTypeBuilders.put(augmentPackageName, augmentBuilders);
844 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
847 if (augIdentifier != null) {
848 augTypeName = BindingMapping.getClassName(augIdentifier);
850 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
853 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
854 JavaTypeName.create(augmentPackageName, augTypeName));
856 augTypeBuilder.addImplementsType(DATA_OBJECT);
857 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
858 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
859 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
861 augSchemaNodeToMethods(context,augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
862 augmentBuilders.put(augTypeName, augTypeBuilder);
864 if (!augSchema.getChildNodes().isEmpty()) {
865 context.addTypeToAugmentation(augTypeBuilder, augSchema);
868 context.addAugmentType(augTypeBuilder);
869 return augTypeBuilder;
872 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
873 final AugmentationSchemaNode augSchema) {
874 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
879 * @param unknownSchemaNodes
880 * @return nodeParameter of UnknownSchemaNode
882 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
883 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
884 final QName nodeType = unknownSchemaNode.getNodeType();
885 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
886 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
887 return unknownSchemaNode.getNodeParameter();
894 * Returns first unique name for the augment generated type builder. The
895 * generated type builder name for augment consists from name of augmented
896 * node and serial number of its augmentation.
899 * map of builders which were created in the package to which the
900 * augmentation belongs
902 * string with name of augmented node
903 * @return string with unique name for augmentation builder
905 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
907 if (builders != null) {
908 while (builders.containsKey(genTypeName + index)) {
912 return genTypeName + index;
916 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
917 * node for which <code>typeBuilder</code> was created.
919 * The subnodes aren't mapped to the methods if they are part of grouping or
920 * augment (in this case are already part of them).
925 * generated type builder which represents any node. The subnodes
926 * of this node are added to the <code>typeBuilder</code> as
927 * methods. The subnode can be of type leaf, leaf-list, list,
932 * set of data schema nodes which are the children of the node
933 * for which <code>typeBuilder</code> was created
934 * @return generated type builder which is the same builder as input
935 * parameter. The getter methods (representing child nodes) could be
938 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
939 final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
940 if (schemaNodes != null && parent != null) {
941 for (final DataSchemaNode schemaNode : schemaNodes) {
942 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
943 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
951 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
952 * node for which <code>typeBuilder</code> was created.
957 * generated type builder which represents any node. The subnodes
958 * of this node are added to the <code>typeBuilder</code> as
959 * methods. The subnode can be of type leaf, leaf-list, list,
964 * set of data schema nodes which are the children of the node
965 * for which <code>typeBuilder</code> was created
966 * @return generated type builder which is the same object as the input
967 * parameter <code>typeBuilder</code>. The getter method could be
970 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
971 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
972 final Iterable<DataSchemaNode> schemaNodes) {
973 if (schemaNodes != null && typeBuilder != null) {
974 for (final DataSchemaNode schemaNode : schemaNodes) {
975 if (!schemaNode.isAugmenting()) {
976 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
984 * Adds to <code>typeBuilder</code> a method which is derived from
985 * <code>schemaNode</code>.
988 * data schema node which is added to <code>typeBuilder</code> as
991 * generated type builder to which is <code>schemaNode</code>
998 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
999 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf) {
1000 if (node != null && typeBuilder != null) {
1001 if (node instanceof LeafSchemaNode) {
1002 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1003 } else if (node instanceof LeafListSchemaNode) {
1004 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1005 } else if (node instanceof ContainerSchemaNode) {
1006 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1007 } else if (node instanceof ListSchemaNode) {
1008 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1009 } else if (node instanceof ChoiceSchemaNode) {
1010 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1012 // TODO: anyxml not yet supported
1013 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1014 typeBuilder.getFullyQualifiedName());
1020 * Converts <code>choiceNode</code> to the list of generated types for
1021 * choice and its cases.
1023 * The package names for choice and for its cases are created as
1024 * concatenation of the module package (<code>basePackageName</code>) and
1025 * names of all parents node.
1029 * @param basePackageName
1030 * string with the module package name
1034 * choice node which is mapped to generated type. Also child
1035 * nodes - cases are mapped to generated types.
1036 * @throws IllegalArgumentException
1038 * <li>if <code>basePackageName</code> is null</li>
1039 * <li>if <code>choiceNode</code> is null</li>
1042 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1043 final ChoiceSchemaNode choiceNode) {
1044 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1046 if (!choiceNode.isAddedByUses()) {
1047 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1048 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1049 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1050 constructGetter(parent, choiceTypeBuilder, choiceNode);
1051 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1052 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1053 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1054 generateTypesFromChoiceCases(context, choiceTypeBuilder.build(), choiceNode);
1059 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1061 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1062 * The package names for the builder is created as concatenation of the module package and names of all parents
1063 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1064 * and <i>choice</i> type
1067 * current module context
1068 * @param refChoiceType
1069 * type which represents superior <i>case</i>
1071 * choice case node which is mapped to generated type
1072 * @throws IllegalArgumentException
1074 * <li>if <code>refChoiceType</code> equals null</li>
1075 * <li>if <code>caseNodes</code> equals null</li>
1078 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1079 final ChoiceSchemaNode choiceNode) {
1080 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1081 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1083 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1084 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1085 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1086 caseTypeBuilder.addImplementsType(refChoiceType);
1087 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1088 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1089 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1090 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1091 if (caseChildNodes != null) {
1092 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1094 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1095 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1097 if (parent instanceof AugmentationSchemaNode) {
1098 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1099 final SchemaPath targetPath = augSchema.getTargetPath();
1100 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1101 if (targetSchemaNode instanceof DataSchemaNode
1102 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1103 if (targetSchemaNode instanceof DerivableSchemaNode) {
1104 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1107 if (targetSchemaNode == null) {
1108 throw new IllegalStateException(
1109 "Failed to find target node from grouping for augmentation " + augSchema
1110 + " in module " + context.module().getName());
1113 parent = targetSchemaNode;
1116 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1117 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1118 if (childOfType == null) {
1119 childOfType = findGroupingByPath(parent.getPath());
1121 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1123 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1127 processUsesAugments(caseNode, context);
1132 * Generates list of generated types for all the cases of a choice which are
1133 * added to the choice through the augment.
1137 * @param basePackageName
1138 * string contains name of package to which augment belongs. If
1139 * an augmented choice is from an other package (pcg1) than an
1140 * augmenting choice (pcg2) then case's of the augmenting choice
1141 * will belong to pcg2.
1143 * Type which represents target choice
1145 * node which represents target choice
1146 * @param augmentedNodes
1147 * set of choice case nodes for which is checked if are/aren't
1148 * added to choice through augmentation
1149 * @throws IllegalArgumentException
1151 * <li>if <code>basePackageName</code> is null</li>
1152 * <li>if <code>targetType</code> is null</li>
1153 * <li>if <code>augmentedNodes</code> is null</li>
1156 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1157 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1158 final DataNodeContainer usesNodeParent) {
1159 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1160 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1162 for (final DataSchemaNode caseNode : augmentedNodes) {
1163 if (caseNode != null) {
1164 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1165 caseTypeBuilder.addImplementsType(targetType);
1168 final SchemaPath nodeSp = targetNode.getPath();
1169 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1171 GeneratedTypeBuilder childOfType = null;
1172 if (parent instanceof Module) {
1173 childOfType = moduleContext(((Module) parent).getQNameModule()).getModuleNode();
1174 } else if (parent instanceof CaseSchemaNode) {
1175 childOfType = findCaseByPath(parent.getPath());
1176 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1177 childOfType = findChildNodeByPath(parent.getPath());
1178 } else if (parent instanceof GroupingDefinition) {
1179 childOfType = findGroupingByPath(parent.getPath());
1182 if (childOfType == null) {
1183 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1186 CaseSchemaNode node = null;
1187 final String caseLocalName = caseNode.getQName().getLocalName();
1188 if (caseNode instanceof CaseSchemaNode) {
1189 node = (CaseSchemaNode) caseNode;
1190 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1191 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1192 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1193 if (dataSchemaNode instanceof ChoiceSchemaNode
1194 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1195 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1200 node = findNamedCase(targetNode, caseLocalName);
1202 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1203 if (childNodes != null) {
1204 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1206 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1207 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1212 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1213 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1214 return cases.isEmpty() ? null : cases.get(0);
1217 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1218 // New parser with encapsulated type
1219 if (leaf.getPath().equals(type.getPath())) {
1223 // Embedded type definition with new parser. Also takes care of the old parser with bits
1224 if (leaf.getPath().equals(type.getPath().getParent())) {
1231 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1232 final List<PatternConstraint> patternConstraints) {
1233 if (!patternConstraints.isEmpty()) {
1234 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1235 .append(BindingMapping.getPropertyName(leafName));
1236 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1237 typeProvider.resolveRegExpressions(patternConstraints));
1242 * Converts <code>leaf</code> to the getter method which is added to
1243 * <code>typeBuilder</code>.
1245 * @param typeBuilder
1246 * generated type builder to which is added getter method as
1247 * <code>leaf</code> mapping
1249 * leaf schema node which is mapped as getter method which is
1250 * added to <code>typeBuilder</code>
1252 * Module in which type was defined
1253 * @return boolean value
1255 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1257 * <li>true - in other cases</li>
1260 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1261 final ModuleContext context) {
1262 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1266 final Module parentModule = findParentModule(schemaContext, leaf);
1267 Type returnType = null;
1269 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1270 if (isInnerType(leaf, typeDef)) {
1271 if (typeDef instanceof EnumTypeDefinition) {
1272 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1273 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1274 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1275 typeBuilder, context);
1276 if (enumBuilder != null) {
1277 returnType = enumBuilder.toInstance(typeBuilder);
1279 typeProvider.putReferencedType(leaf.getPath(), returnType);
1280 } else if (typeDef instanceof UnionTypeDefinition) {
1281 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1283 if (genTOBuilder != null) {
1284 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1285 // Store the inner type within the union so that we can find the reference for it
1286 context.addInnerTypedefType(typeDef.getPath(), returnType);
1288 } else if (typeDef instanceof BitsTypeDefinition) {
1289 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1291 if (genTOBuilder != null) {
1292 returnType = genTOBuilder.build();
1295 // It is constrained version of already declared type (inner declared type exists,
1296 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1297 // In order to get proper class we need to look up closest derived type
1298 // and apply restrictions from leaf type
1299 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1300 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1302 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1305 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1306 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1307 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1310 if (returnType == null) {
1314 if (typeDef instanceof EnumTypeDefinition) {
1315 typeProvider.putReferencedType(leaf.getPath(), returnType);
1318 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1319 processContextRefExtension(leaf, getter, parentModule);
1323 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1324 // Returns DerivedType in case of new parser.
1325 final TypeDefinition<?> baseType = typeDef.getBaseType();
1326 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1329 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1330 final Module module) {
1331 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1332 final QName nodeType = node.getNodeType();
1333 if ("context-reference".equals(nodeType.getLocalName())) {
1334 final String nodeParam = node.getNodeParameter();
1335 IdentitySchemaNode identity = null;
1336 String basePackageName = null;
1337 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1338 final Iterator<String> iterator = splittedElement.iterator();
1339 final int length = Iterables.size(splittedElement);
1341 identity = findIdentityByName(module.getIdentities(), iterator.next());
1342 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1343 } else if (length == 2) {
1344 final String prefix = iterator.next();
1345 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1346 if (dependentModule == null) {
1347 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1350 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1351 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1353 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1356 if (identity == null) {
1357 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1361 final AnnotationTypeBuilder rc = getter.addAnnotation(JavaTypeName.create(RoutingContext.class));
1362 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1363 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1364 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1369 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1370 for (final IdentitySchemaNode id : identities) {
1371 if (id.getQName().getLocalName().equals(name)) {
1378 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1379 for (final ModuleImport imp : imports) {
1380 if (imp.getPrefix().equals(prefix)) {
1381 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1387 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1388 final boolean isReadOnly) {
1389 if (leaf != null && toBuilder != null) {
1391 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1392 if (typeDef instanceof UnionTypeDefinition) {
1393 // GeneratedType for this type definition should have be already created
1394 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1395 returnType = mc.getTypedefs().get(typeDef.getPath());
1396 if (returnType == null) {
1397 // This may still be an inner type, try to find it
1398 returnType = mc.getInnerType(typeDef.getPath());
1400 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1401 // Annonymous enumeration (already generated, since it is inherited via uses).
1402 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1403 QName qname = originalLeaf.getQName();
1404 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1406 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1408 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1414 * Converts <code>leaf</code> schema node to property of generated TO
1418 * generated TO builder to which is <code>leaf</code> added as
1421 * leaf schema node which is added to <code>toBuilder</code> as
1426 * boolean value which says if leaf property is|isn't read only
1427 * @return boolean value
1429 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1430 * name equals null or if leaf is added by <i>uses</i>.</li>
1431 * <li>true - other cases</li>
1434 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1435 final Type returnType, final boolean isReadOnly) {
1436 if (returnType == null) {
1439 final String leafName = leaf.getQName().getLocalName();
1440 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1441 propBuilder.setReadOnly(isReadOnly);
1442 propBuilder.setReturnType(returnType);
1443 addComment(propBuilder, leaf);
1445 toBuilder.addEqualsIdentity(propBuilder);
1446 toBuilder.addHashIdentity(propBuilder);
1447 toBuilder.addToStringProperty(propBuilder);
1452 * Converts <code>node</code> leaf list schema node to getter method of
1453 * <code>typeBuilder</code>.
1455 * @param typeBuilder
1456 * generated type builder to which is <code>node</code> added as
1459 * leaf list schema node which is added to
1460 * <code>typeBuilder</code> as getter method
1461 * @param module module
1462 * @return boolean value
1464 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1465 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1466 * <li>false - other cases</li>
1469 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1470 final ModuleContext context) {
1471 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1475 final QName nodeName = node.getQName();
1477 final TypeDefinition<?> typeDef = node.getType();
1478 final Module parentModule = findParentModule(schemaContext, node);
1480 Type returnType = null;
1481 if (typeDef.getBaseType() == null) {
1482 if (typeDef instanceof EnumTypeDefinition) {
1483 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1484 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1485 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1486 typeBuilder, context);
1487 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1488 typeProvider.putReferencedType(node.getPath(), returnType);
1489 } else if (typeDef instanceof UnionTypeDefinition) {
1490 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1491 node, parentModule);
1492 if (genTOBuilder != null) {
1493 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1495 } else if (typeDef instanceof BitsTypeDefinition) {
1496 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1497 node, parentModule);
1498 returnType = genTOBuilder.build();
1500 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1501 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1502 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1505 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1506 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1507 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1510 final ParameterizedType listType = Types.listTypeFor(returnType);
1511 constructGetter(typeBuilder, listType, node);
1515 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1516 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1517 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1519 addCodegenInformation(returnType, parentModule, typeDef);
1520 returnType.setSchemaPath(typeDef.getPath());
1521 returnType.setModuleName(parentModule.getName());
1523 genTOBuilder.setTypedef(true);
1524 genTOBuilder.setIsUnion(true);
1525 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1529 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1532 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1533 method.setReturnType(returnType);
1534 method.addParameter(Types.STRING, "defaultValue");
1535 method.setAccessModifier(AccessModifier.PUBLIC);
1536 method.setStatic(true);
1538 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1539 if (types == null) {
1540 typeProvider.getAdditionalTypes().put(parentModule,
1541 Sets.newHashSet(unionBuilder.build()));
1543 types.add(unionBuilder.build());
1545 return returnType.build();
1548 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1549 final GeneratedTypeBuilder typeBuilder) {
1550 // Append enclosing path hierarchy without dots
1551 final StringBuilder sb = new StringBuilder();
1552 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1553 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1554 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1555 unionBuilder.setIsUnionBuilder(true);
1556 return unionBuilder;
1559 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1560 final SchemaNode schemaNode) {
1561 return addDefaultInterfaceDefinition(context, schemaNode, null);
1564 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1565 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1566 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1567 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1572 * Instantiates generated type builder with <code>packageName</code> and
1573 * <code>schemaNode</code>.
1575 * The new builder always implements
1576 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1577 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1578 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1580 * If <code>schemaNode</code> is instance of
1581 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1582 * DataNodeContainer} it can also implement nodes which are specified in
1585 * @param packageName
1586 * string with the name of the package to which
1587 * <code>schemaNode</code> belongs.
1589 * schema node for which is created generated type builder
1591 * parent type (can be null)
1592 * @return generated type builder <code>schemaNode</code>
1594 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1595 final Type parent, final ModuleContext context) {
1596 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1597 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1598 if (parent == null) {
1599 it.addImplementsType(DATA_OBJECT);
1601 it.addImplementsType(BindingTypes.childOf(parent));
1603 if (!(schemaNode instanceof GroupingDefinition)) {
1604 it.addImplementsType(augmentable(it));
1607 if (schemaNode instanceof DataNodeContainer) {
1608 groupingsToGenTypes(context, ((DataNodeContainer) schemaNode).getGroupings());
1609 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1616 * Wraps the calling of the same overloaded method.
1618 * @param packageName
1619 * string with the package name to which returning generated type
1622 * schema node which provide data about the schema node name
1623 * @return generated type builder for <code>schemaNode</code>
1625 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1626 final String prefix) {
1627 return addRawInterfaceDefinition(
1628 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1629 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1633 * Returns reference to generated type builder for specified
1634 * <code>schemaNode</code> with <code>packageName</code>.
1636 * Firstly the generated type builder is searched in
1637 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1638 * found it is created and added to <code>genTypeBuilders</code>.
1640 * @param packageName
1641 * string with the package name to which returning generated type
1644 * schema node which provide data about the schema node name
1646 * return type name prefix
1647 * @return generated type builder for <code>schemaNode</code>
1648 * @throws IllegalArgumentException
1650 * <li>if <code>schemaNode</code> is null</li>
1651 * <li>if <code>packageName</code> is null</li>
1652 * <li>if QName of schema node is null</li>
1653 * <li>if schemaNode name is null</li>
1657 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1658 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1659 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1660 final String schemaNodeName = schemaNode.getQName().getLocalName();
1661 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1663 // FIXME: Validation of name conflict
1664 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1665 final Module module = findParentModule(schemaContext, schemaNode);
1666 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1668 addCodegenInformation(newType, module, schemaNode);
1669 newType.setSchemaPath(schemaNode.getPath());
1670 newType.setModuleName(module.getName());
1672 final String packageName = identifier.packageName();
1673 final String simpleName = identifier.simpleName();
1674 if (!genTypeBuilders.containsKey(packageName)) {
1675 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1676 builders.put(simpleName, newType);
1677 genTypeBuilders.put(packageName, builders);
1679 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1680 if (!builders.containsKey(simpleName)) {
1681 builders.put(simpleName, newType);
1688 * Creates the name of the getter method name from <code>localName</code>.
1691 * string with the name of the getter method
1694 * @return string with the name of the getter method for
1695 * <code>methodName</code> in JAVA method format
1697 public static String getterMethodName(final String localName, final Type returnType) {
1698 final StringBuilder method = new StringBuilder();
1699 if (BOOLEAN.equals(returnType)) {
1700 method.append("is");
1702 method.append("get");
1704 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1705 method.append(name);
1706 return method.toString();
1710 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1712 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1713 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1715 * @param interfaceBuilder generated type builder for which the getter method should be created
1716 * @param returnType type which represents the return type of the getter method
1717 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1718 * @param comment string with comment for the getter method
1719 * @param status status from yang file, for deprecated annotation
1720 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1722 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1723 final SchemaNode node) {
1724 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1725 getterMethodName(node.getQName().getLocalName(), returnType));
1726 getMethod.setReturnType(returnType);
1728 if (node.getStatus() == Status.DEPRECATED) {
1729 getMethod.addAnnotation("java.lang", "Deprecated");
1731 if (!returnType.getPackageName().isEmpty()) {
1732 // The return type has a package, so it's not a primitive type
1733 getMethod.addAnnotation("javax.annotation", "Nullable");
1735 addComment(getMethod, node);
1741 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1742 * or to <code>genTOBuilder</code> as property.
1744 * @param basePackageName
1745 * string contains the module package name
1747 * data schema node which should be added as getter method to
1748 * <code>typeBuilder</code> or as a property to
1749 * <code>genTOBuilder</code> if is part of the list key
1750 * @param typeBuilder
1751 * generated type builder for the list schema node
1752 * @param genTOBuilder
1753 * generated TO builder for the list keys
1755 * list of string which contains names of the list keys
1758 * @throws IllegalArgumentException
1760 * <li>if <code>schemaNode</code> equals null</li>
1761 * <li>if <code>typeBuilder</code> equals null</li>
1764 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1765 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1766 final List<String> listKeys) {
1767 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1768 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1770 if (schemaNode instanceof LeafSchemaNode) {
1771 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1772 final String leafName = leaf.getQName().getLocalName();
1773 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1774 if (listKeys.contains(leafName)) {
1776 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1778 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1781 } else if (!schemaNode.isAddedByUses()) {
1782 if (schemaNode instanceof LeafListSchemaNode) {
1783 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1784 } else if (schemaNode instanceof ContainerSchemaNode) {
1785 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1786 } else if (schemaNode instanceof ChoiceSchemaNode) {
1787 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1788 } else if (schemaNode instanceof ListSchemaNode) {
1789 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1794 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1795 final GeneratedTOBuilder genTOBuilder) {
1796 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1798 if (genTOBuilder != null) {
1799 final GeneratedTransferObject genTO = genTOBuilder.build();
1801 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1802 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1803 getMethod.setReturnType(genTO);
1804 getMethod.setComment("Returns Primary Key of Yang List Type");
1805 context.addGeneratedTOBuilder(genTOBuilder);
1810 * Selects the names of the list keys from <code>list</code> and returns
1811 * them as the list of the strings
1814 * of string with names of the list keys
1815 * @return list of string which represents names of the list keys. If the
1816 * <code>list</code> contains no keys then the empty list is
1819 private static List<String> listKeys(final ListSchemaNode list) {
1820 final List<String> listKeys = new ArrayList<>();
1822 final List<QName> keyDefinition = list.getKeyDefinition();
1823 if (keyDefinition != null) {
1824 for (final QName keyDef : keyDefinition) {
1825 listKeys.add(keyDef.getLocalName());
1832 * Generates for the <code>list</code> which contains any list keys special
1833 * generated TO builder.
1835 * @param packageName
1836 * string with package name to which the list belongs
1838 * list schema node which is source of data about the list name
1839 * @return generated TO builder which represents the keys of the
1840 * <code>list</code> or null if <code>list</code> is null or list of
1841 * key definitions is null or empty.
1843 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1844 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1845 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1846 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1847 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1853 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1855 * If more then one generated TO builder is created for enclosing then all
1856 * of the generated TO builders are added to <code>typeBuilder</code> as
1857 * enclosing transfer objects.
1860 * type definition which can be of type <code>UnionType</code> or
1861 * <code>BitsTypeDefinition</code>
1862 * @param typeBuilder
1863 * generated type builder to which is added generated TO created
1864 * from <code>typeDef</code>
1866 * string with name for generated TO builder
1867 * @param parentModule
1869 * @return generated TO builder for <code>typeDef</code>
1871 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1872 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1873 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1874 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1877 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1878 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1879 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1880 for (final GeneratedTOBuilder genTOBuilder : types) {
1881 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1884 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1885 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1886 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1887 resultTOBuilder.addHashIdentity(genPropBuilder);
1888 resultTOBuilder.addToStringProperty(genPropBuilder);
1889 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1890 return resultTOBuilder;
1894 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1895 * also added to <code>typeBuilder</code> as enclosing transfer object.
1897 * If more then one generated TO builder is created for enclosing then all
1898 * of the generated TO builders are added to <code>typeBuilder</code> as
1899 * enclosing transfer objects.
1902 * type definition which can be of type <code>UnionType</code> or
1903 * <code>BitsTypeDefinition</code>
1904 * @param typeBuilder
1905 * generated type builder to which is added generated TO created
1906 * from <code>typeDef</code>
1908 * string with name for generated TO builder
1909 * @param parentModule
1911 * @return generated TO builder for <code>typeDef</code>
1913 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1914 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1915 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1916 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1917 typeDef, parentModule.getName());
1918 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1919 return genTOBuilder;
1923 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1924 final List<GeneratedTOBuilder> genTOBuilders) {
1925 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1926 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1928 return genTOBuilders.get(0);
1932 * Adds the implemented types to type builder.
1934 * The method passes through the list of <i>uses</i> in
1935 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1936 * generated type from {@link ModuleContext#groupings
1937 * allGroupings} which is added as <i>implements type</i> to
1938 * <code>builder</code>
1940 * @param dataNodeContainer
1941 * element which contains the list of used YANG groupings
1943 * builder to which are added implemented types according to
1944 * <code>dataNodeContainer</code>
1945 * @return generated type builder with all implemented types
1947 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1948 final GeneratedTypeBuilder builder) {
1949 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1950 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1951 if (genType == null) {
1952 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1953 + builder.getName());
1956 builder.addImplementsType(genType);
1961 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1962 for (final ModuleContext ctx : genCtx.values()) {
1963 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1964 if (result != null) {
1971 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1972 for (final ModuleContext ctx : genCtx.values()) {
1973 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1974 if (result != null) {
1981 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1982 for (final ModuleContext ctx : genCtx.values()) {
1983 final GeneratedTypeBuilder result = ctx.getCase(path);
1984 if (result != null) {
1991 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
1992 if (status == Status.DEPRECATED) {
1993 builder.addAnnotation("java.lang", "Deprecated");