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 java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
22 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
23 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
24 import static org.opendaylight.mdsal.binding.model.util.Types.VOID;
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.ArrayDeque;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Comparator;
37 import java.util.Deque;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.List;
42 import java.util.Optional;
44 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
45 import org.opendaylight.mdsal.binding.model.api.Constant;
46 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
47 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
48 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
49 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
50 import org.opendaylight.mdsal.binding.model.api.Restrictions;
51 import org.opendaylight.mdsal.binding.model.api.Type;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
53 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
54 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
55 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
60 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
61 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
62 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
63 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
64 import org.opendaylight.mdsal.binding.model.util.Types;
65 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
66 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
67 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
68 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
69 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
70 import org.opendaylight.yangtools.yang.binding.BindingMapping;
71 import org.opendaylight.yangtools.yang.binding.DataContainer;
72 import org.opendaylight.yangtools.yang.binding.RpcService;
73 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
74 import org.opendaylight.yangtools.yang.common.QName;
75 import org.opendaylight.yangtools.yang.common.QNameModule;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
85 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
86 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
94 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
97 import org.opendaylight.yangtools.yang.model.api.Status;
98 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.UsesNode;
101 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
102 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
103 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
106 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
107 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
108 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
109 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
110 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
114 abstract class AbstractTypeGenerator {
115 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
116 private static final Splitter COLON_SPLITTER = Splitter.on(':');
119 * Comparator based on augment target path.
121 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
122 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
123 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
125 while (thisIt.hasNext()) {
126 if (!otherIt.hasNext()) {
130 final int comp = thisIt.next().compareTo(otherIt.next());
136 return otherIt.hasNext() ? -1 : 0;
140 * Constant with the concrete name of identifier.
142 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
145 * Constant with the concrete name of namespace.
147 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
149 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
152 * Outer key represents the package name. Outer value represents map of all
153 * builders in the same package. Inner key represents the schema node name
154 * (in JAVA class/interface name format). Inner value represents instance of
155 * builder for schema node specified in key part.
157 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
160 * Provide methods for converting YANG types to JAVA types.
162 private final AbstractTypeProvider typeProvider;
165 * Holds reference to schema context to resolve data of augmented element
166 * when creating augmentation builder
168 private final SchemaContext schemaContext;
170 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
171 this.schemaContext = requireNonNull(context);
172 this.typeProvider = requireNonNull(typeProvider);
174 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
175 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
176 for (final Module contextModule : contextModules) {
177 contexts.add(moduleToGenTypes(contextModule));
180 contexts.forEach(this::allAugmentsToGenTypes);
183 final Collection<ModuleContext> moduleContexts() {
184 return genCtx.values();
187 final ModuleContext moduleContext(final QNameModule module) {
188 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
191 final AbstractTypeProvider typeProvider() {
195 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
197 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
199 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
200 Set<? extends SchemaNode> nodes);
202 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
204 private ModuleContext moduleToGenTypes(final Module module) {
205 final ModuleContext context = new ModuleContext(module);
206 genCtx.put(module.getQNameModule(), context);
207 allTypeDefinitionsToGenTypes(context);
208 groupingsToGenTypes(context, module.getGroupings());
209 rpcMethodsToGenType(context);
210 allIdentitiesToGenTypes(context);
211 notificationsToGenType(context);
213 if (!module.getChildNodes().isEmpty()) {
214 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
215 context.addModuleNode(moduleType);
216 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
222 * Converts all extended type definitions of module to the list of
223 * <code>Type</code> objects.
226 * module from which is obtained set of type definitions
227 * @throws IllegalArgumentException
229 * <li>if module is null</li>
230 * <li>if name of module is null</li>
232 * @throws IllegalStateException
233 * if set of type definitions from module is null
235 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
236 final Module module = context.module();
237 checkArgument(module.getName() != null, "Module name cannot be NULL.");
238 final DataNodeIterator it = new DataNodeIterator(module);
239 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
240 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
242 for (final TypeDefinition<?> typedef : typeDefinitions) {
243 if (typedef != null) {
244 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
246 context.addTypedefType(typedef.getPath(), type);
247 context.addTypeToSchema(type,typedef);
253 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final GeneratedTypeBuilder childOf,
254 final DataSchemaNode node) {
255 if (node.isAugmenting() || node.isAddedByUses()) {
258 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
259 annotateDeprecatedIfNecessary(node.getStatus(), genType);
261 final Module module = context.module();
262 genType.setModuleName(module.getName());
263 addCodegenInformation(genType, module, node);
264 genType.setSchemaPath(node.getPath());
265 if (node instanceof DataNodeContainer) {
266 context.addChildNodeType(node, genType);
267 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
268 processUsesAugments((DataNodeContainer) node, context);
273 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
274 final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
275 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
276 if (genType != null) {
277 constructGetter(parent, genType, node);
278 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
282 private void listToGenType(final ModuleContext context,
283 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
284 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
285 if (genType != null) {
286 constructGetter(parent, Types.listTypeFor(genType), node);
288 final List<String> listKeys = listKeys(node);
289 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
290 if (genTOBuilder != null) {
291 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
292 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
293 genTOBuilder.addImplementsType(identifierMarker);
294 genType.addImplementsType(identifiableMarker);
297 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
298 if (!schemaNode.isAugmenting()) {
299 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
304 if (genTOBuilder != null) {
305 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
306 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
307 genTOBuilder.setSUID(prop);
310 typeBuildersToGenTypes(context, genType, genTOBuilder);
314 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
315 for (final UsesNode usesNode : node.getUses()) {
316 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
317 usesAugmentationToGenTypes(context, augment, usesNode, node);
318 processUsesAugments(augment, context);
324 * Converts all <b>augmentation</b> of the module to the list
325 * <code>Type</code> objects.
328 * module from which is obtained list of all augmentation objects
329 * to iterate over them
330 * @throws IllegalArgumentException
332 * <li>if the module is null</li>
333 * <li>if the name of module is null</li>
335 * @throws IllegalStateException
336 * if set of augmentations from module is null
338 private void allAugmentsToGenTypes(final ModuleContext context) {
339 final Module module = context.module();
340 checkArgument(module != null, "Module reference cannot be NULL.");
341 checkArgument(module.getName() != null, "Module name cannot be NULL.");
342 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
344 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
345 augmentationToGenTypes(context, augment);
350 * Returns list of <code>AugmentationSchema</code> objects. The objects are
351 * sorted according to the length of their target path from the shortest to
355 * module from which is obtained list of all augmentation objects
356 * @return list of sorted <code>AugmentationSchema</code> objects obtained
357 * from <code>module</code>
358 * @throws IllegalArgumentException
360 * @throws IllegalStateException
361 * if set of module augmentations is null
363 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
364 checkArgument(module != null, "Module reference cannot be NULL.");
365 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
367 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
368 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
369 sortedAugmentations.sort(AUGMENT_COMP);
371 return sortedAugmentations;
375 * Create GeneratedTypeBuilder object from module argument.
378 * Module object from which builder will be created
379 * @return <code>GeneratedTypeBuilder</code> which is internal
380 * representation of the module
381 * @throws IllegalArgumentException
384 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
385 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
386 final Module module = context.module();
387 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
388 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
390 addCodegenInformation(moduleDataTypeBuilder, module);
391 return moduleDataTypeBuilder;
395 * Converts all <b>RPCs</b> input and output substatements of the module
396 * to the list of <code>Type</code> objects. In addition are to containers
397 * and lists which belong to input or output also part of returning list.
400 * module from which is obtained set of all rpc objects to
402 * @throws IllegalArgumentException
404 * <li>if the module is null</li>
405 * <li>if the name of module is null</li>
407 * @throws IllegalStateException
408 * if set of rpcs from module is null
410 private void rpcMethodsToGenType(final ModuleContext context) {
411 final Module module = context.module();
412 checkArgument(module.getName() != null, "Module name cannot be NULL.");
413 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
414 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
415 if (rpcDefinitions.isEmpty()) {
419 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
420 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
422 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
424 for (final RpcDefinition rpc : rpcDefinitions) {
426 final String rpcName = BindingMapping.getClassName(rpc.getQName());
427 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
428 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
429 final ContainerSchemaNode input = rpc.getInput();
430 final ContainerSchemaNode output = rpc.getOutput();
432 // Do not refer to annotation class, as it may not be available at runtime
433 method.addAnnotation("javax.annotation", "CheckReturnValue");
435 //in case of implicit RPC input (StatementSource.CONTEXT),
436 // stay compatible (no input argument generated)
437 if (input != null && isExplicitStatement(input)) {
438 final Type inTypeInstance = createRpcContainer(context, rpcName, rpc, input);
439 method.addParameter(inTypeInstance, "input");
442 final Type outTypeInstance;
443 //in case of implicit RPC output (StatementSource.CONTEXT),
444 //stay compatible (Future<RpcResult<Void>> return type generated)
445 if (output != null && isExplicitStatement(output)) {
446 outTypeInstance = createRpcContainer(context, rpcName, rpc, output);
448 outTypeInstance = VOID;
451 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
452 addComment(method, rpc);
453 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
457 context.addTopLevelNodeType(interfaceBuilder);
460 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
461 return node instanceof EffectiveStatement
462 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
465 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
466 final ContainerSchemaNode schema) {
467 processUsesAugments(schema, context);
468 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
469 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
471 addImplementedInterfaceFromUses(schema, outType);
472 outType.addImplementsType(DATA_OBJECT);
473 outType.addImplementsType(augmentable(outType));
474 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
475 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
476 context.addChildNodeType(schema, outType);
477 return outType.build();
481 * Converts all <b>notifications</b> of the module to the list of
482 * <code>Type</code> objects. In addition are to this list added containers
483 * and lists which are part of this notification.
486 * module from which is obtained set of all notification objects
487 * to iterate over them
488 * @throws IllegalArgumentException
490 * <li>if the module equals null</li>
491 * <li>if the name of module equals null</li>
493 * @throws IllegalStateException
494 * if set of notifications from module is null
496 private void notificationsToGenType(final ModuleContext context) {
497 final Module module = context.module();
498 checkArgument(module.getName() != null, "Module name cannot be NULL.");
499 final Set<NotificationDefinition> notifications = module.getNotifications();
500 if (notifications.isEmpty()) {
504 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
505 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
507 for (final NotificationDefinition notification : notifications) {
508 if (notification != null) {
509 processUsesAugments(notification, context);
511 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
512 context.modulePackageName(), notification, null, context);
513 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
514 notificationInterface.addImplementsType(NOTIFICATION);
515 context.addChildNodeType(notification, notificationInterface);
517 // Notification object
518 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
519 notification.getChildNodes());
521 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
522 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
523 .setReturnType(Types.VOID), notification);
527 addCodegenInformation(listenerInterface, module, "notifications", notifications);
528 context.addTopLevelNodeType(listenerInterface);
532 * Converts all <b>identities</b> of the module to the list of
533 * <code>Type</code> objects.
536 * module from which is obtained set of all identity objects to
538 * @param schemaContext
539 * schema context only used as input parameter for method
540 * {@link BindingGeneratorImpl#identityToGenType}
543 private void allIdentitiesToGenTypes(final ModuleContext context) {
544 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
546 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
547 for (final IdentitySchemaNode identity : schemaIdentities) {
548 identityToGenType(context, identity);
554 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
555 * created transport object builder. If identity contains base identity then
556 * reference to base identity is added to superior identity as its extend.
557 * If identity doesn't contain base identity then only reference to abstract
558 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
559 * BaseIdentity} is added
563 * @param basePackageName
564 * string contains the module package name
566 * IdentitySchemaNode which contains data about identity
568 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
569 if (identity == null) {
572 final GeneratedTOBuilder newType = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
573 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
574 BindingMapping.getClassName(identity.getQName())));
575 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
576 if (baseIdentities.isEmpty()) {
577 final GeneratedTOBuilder gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(BaseIdentity.class));
578 newType.setExtendsType(gto.build());
580 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
581 final QName qname = baseIdentity.getQName();
582 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
583 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
584 newType.setExtendsType(gto);
586 newType.setAbstract(true);
588 final Module module = context.module();
589 addCodegenInformation(newType, module, identity);
590 newType.setModuleName(module.getName());
591 newType.setSchemaPath(identity.getPath());
593 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, identity.getQName());
595 context.addIdentityType(identity.getQName(), newType);
599 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
601 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
605 * Converts all <b>groupings</b> of the module to the list of
606 * <code>Type</code> objects. Firstly are groupings sorted according mutual
607 * dependencies. At least dependent (independent) groupings are in the list
608 * saved at first positions. For every grouping the record is added to map
609 * {@link ModuleContext#groupings allGroupings}
614 * collection of groupings from which types will be generated
617 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
618 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
619 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
620 // node of grouping is resolved to the method.
621 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
622 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
623 context.addGroupingType(grouping.getPath(), genType);
624 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
625 groupingsToGenTypes(context, grouping.getGroupings());
626 processUsesAugments(grouping, context);
631 * Adds enumeration builder created from <code>enumTypeDef</code> to
632 * <code>typeBuilder</code>.
634 * Each <code>enumTypeDef</code> item is added to builder with its name and
638 * EnumTypeDefinition contains enum data
640 * string contains name which will be assigned to enumeration
643 * GeneratedTypeBuilder to which will be enum builder assigned
645 * Module in which type should be generated
646 * @return enumeration builder which contains data from
647 * <code>enumTypeDef</code>
649 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
650 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
651 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
652 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
653 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
654 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
655 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
662 * Generates type builder for <code>module</code>.
665 * Module which is source of package name for generated type
668 * string which is added to the module class name representation
670 * @return instance of GeneratedTypeBuilder which represents
671 * <code>module</code>.
672 * @throws IllegalArgumentException
673 * if <code>module</code> is null
675 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
676 final Module module = context.module();
677 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
678 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
679 JavaTypeName.create(context.modulePackageName(), moduleName));
681 moduleBuilder.setModuleName(moduleName);
682 addCodegenInformation(moduleBuilder, module);
683 return moduleBuilder;
687 * Converts <code>augSchema</code> to list of <code>Type</code> which
688 * contains generated type for augmentation. In addition there are also
689 * generated types for all containers, list and choices which are child of
690 * <code>augSchema</code> node or a generated types for cases are added if
691 * augmented node is choice.
693 * @param augmentPackageName
694 * string with the name of the package to which the augmentation
697 * AugmentationSchema which is contains data about augmentation
698 * (target path, childs...)
701 * @throws IllegalArgumentException
703 * <li>if <code>augmentPackageName</code> equals null</li>
704 * <li>if <code>augSchema</code> equals null</li>
706 * @throws IllegalStateException
707 * if augment target path is null
709 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
710 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
711 checkState(augSchema.getTargetPath() != null,
712 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
714 processUsesAugments(augSchema, context);
715 final SchemaPath targetPath = augSchema.getTargetPath();
716 SchemaNode targetSchemaNode = null;
718 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
719 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
720 if (targetSchemaNode instanceof DerivableSchemaNode) {
721 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
723 if (targetSchemaNode == null) {
724 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
725 + " in module " + context.module().getName());
728 if (targetSchemaNode == null) {
729 throw new IllegalArgumentException("augment target not found: " + targetPath);
732 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
733 if (targetTypeBuilder == null) {
734 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
736 if (targetTypeBuilder == null) {
737 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
740 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
741 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
742 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
745 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
746 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
750 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
751 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
752 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
753 checkState(augSchema.getTargetPath() != null,
754 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
756 processUsesAugments(augSchema, context);
757 final SchemaPath targetPath = augSchema.getTargetPath();
758 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
759 if (targetSchemaNode == null) {
760 throw new IllegalArgumentException("augment target not found: " + targetPath);
763 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
764 if (targetTypeBuilder == null) {
765 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
767 if (targetTypeBuilder == null) {
768 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
771 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
772 if (usesNodeParent instanceof SchemaNode) {
773 addRawAugmentGenTypeDefinition(context,
774 packageNameForAugmentedGeneratedType(context.modulePackageName(),
775 ((SchemaNode) usesNodeParent).getPath()),
776 targetTypeBuilder.build(), augSchema);
778 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
781 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
782 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
787 * Convenient method to find node added by uses statement.
791 * @param parentUsesNode
792 * parent of uses node
793 * @return node from its original location in grouping
795 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
796 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
798 if (!(targetGrouping instanceof GroupingDefinition)) {
799 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
802 SchemaNode result = targetGrouping;
803 for (final QName node : targetPath.getPathFromRoot()) {
804 if (result instanceof DataNodeContainer) {
805 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
806 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
807 } else if (result instanceof ChoiceSchemaNode) {
808 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
811 if (result == null) {
815 if (result instanceof DerivableSchemaNode) {
816 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
817 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
818 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
819 result = originalNode.get();
823 if (result instanceof DataSchemaNode) {
824 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
825 if (resultDataSchemaNode.isAddedByUses()) {
826 // The original node is required, but we have only the copy of
827 // the original node.
828 // Maybe this indicates a bug in Yang parser.
829 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
832 return resultDataSchemaNode;
835 throw new IllegalStateException(
836 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
841 * Returns a generated type builder for an augmentation.
843 * The name of the type builder is equal to the name of augmented node with
844 * serial number as suffix.
848 * @param augmentPackageName
849 * string with contains the package name to which the augment
851 * @param basePackageName
852 * string with the package name to which the augmented node
854 * @param targetTypeRef
857 * augmentation schema which contains data about the child nodes
858 * and uses of augment
859 * @return generated type builder for augment
861 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
862 final String augmentPackageName, final Type targetTypeRef,
863 final AugmentationSchemaNode augSchema) {
864 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
865 if (augmentBuilders == null) {
866 augmentBuilders = new HashMap<>();
867 genTypeBuilders.put(augmentPackageName, augmentBuilders);
869 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
872 if (augIdentifier != null) {
873 augTypeName = BindingMapping.getClassName(augIdentifier);
875 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
878 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
879 JavaTypeName.create(augmentPackageName, augTypeName));
881 augTypeBuilder.addImplementsType(DATA_OBJECT);
882 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
883 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
884 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
886 augSchemaNodeToMethods(context,augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
887 augmentBuilders.put(augTypeName, augTypeBuilder);
889 if (!augSchema.getChildNodes().isEmpty()) {
890 context.addTypeToAugmentation(augTypeBuilder, augSchema);
893 context.addAugmentType(augTypeBuilder);
894 return augTypeBuilder;
897 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
898 final AugmentationSchemaNode augSchema) {
899 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
904 * @param unknownSchemaNodes
905 * @return nodeParameter of UnknownSchemaNode
907 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
908 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
909 final QName nodeType = unknownSchemaNode.getNodeType();
910 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
911 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
912 return unknownSchemaNode.getNodeParameter();
919 * Returns first unique name for the augment generated type builder. The
920 * generated type builder name for augment consists from name of augmented
921 * node and serial number of its augmentation.
924 * map of builders which were created in the package to which the
925 * augmentation belongs
927 * string with name of augmented node
928 * @return string with unique name for augmentation builder
930 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
932 if (builders != null) {
933 while (builders.containsKey(genTypeName + index)) {
937 return genTypeName + index;
941 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
942 * node for which <code>typeBuilder</code> was created.
944 * The subnodes aren't mapped to the methods if they are part of grouping or
945 * augment (in this case are already part of them).
950 * generated type builder which represents any node. The subnodes
951 * of this node are added to the <code>typeBuilder</code> as
952 * methods. The subnode can be of type leaf, leaf-list, list,
957 * set of data schema nodes which are the children of the node
958 * for which <code>typeBuilder</code> was created
959 * @return generated type builder which is the same builder as input
960 * parameter. The getter methods (representing child nodes) could be
963 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
964 final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
965 if (schemaNodes != null && parent != null) {
966 for (final DataSchemaNode schemaNode : schemaNodes) {
967 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
968 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
976 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
977 * node for which <code>typeBuilder</code> was created.
982 * generated type builder which represents any node. The subnodes
983 * of this node are added to the <code>typeBuilder</code> as
984 * methods. The subnode can be of type leaf, leaf-list, list,
989 * set of data schema nodes which are the children of the node
990 * for which <code>typeBuilder</code> was created
991 * @return generated type builder which is the same object as the input
992 * parameter <code>typeBuilder</code>. The getter method could be
995 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
996 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
997 final Iterable<DataSchemaNode> schemaNodes) {
998 if (schemaNodes != null && typeBuilder != null) {
999 for (final DataSchemaNode schemaNode : schemaNodes) {
1000 if (!schemaNode.isAugmenting()) {
1001 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
1009 * Adds to <code>typeBuilder</code> a method which is derived from
1010 * <code>schemaNode</code>.
1013 * data schema node which is added to <code>typeBuilder</code> as
1015 * @param typeBuilder
1016 * generated type builder to which is <code>schemaNode</code>
1017 * added as a method.
1023 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1024 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf) {
1025 if (node != null && typeBuilder != null) {
1026 if (node instanceof LeafSchemaNode) {
1027 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1028 } else if (node instanceof LeafListSchemaNode) {
1029 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1030 } else if (node instanceof ContainerSchemaNode) {
1031 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1032 } else if (node instanceof ListSchemaNode) {
1033 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1034 } else if (node instanceof ChoiceSchemaNode) {
1035 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1037 // TODO: anyxml not yet supported
1038 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1039 typeBuilder.getFullyQualifiedName());
1045 * Converts <code>choiceNode</code> to the list of generated types for
1046 * choice and its cases.
1048 * The package names for choice and for its cases are created as
1049 * concatenation of the module package (<code>basePackageName</code>) and
1050 * names of all parents node.
1054 * @param basePackageName
1055 * string with the module package name
1059 * choice node which is mapped to generated type. Also child
1060 * nodes - cases are mapped to generated types.
1061 * @throws IllegalArgumentException
1063 * <li>if <code>basePackageName</code> is null</li>
1064 * <li>if <code>choiceNode</code> is null</li>
1067 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1068 final ChoiceSchemaNode choiceNode) {
1069 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1071 if (!choiceNode.isAddedByUses()) {
1072 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1073 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1074 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1075 constructGetter(parent, choiceTypeBuilder, choiceNode);
1076 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1077 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1078 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1079 generateTypesFromChoiceCases(context, choiceTypeBuilder.build(), choiceNode);
1084 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1086 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1087 * The package names for the builder is created as concatenation of the module package and names of all parents
1088 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1089 * and <i>choice</i> type
1092 * current module context
1093 * @param refChoiceType
1094 * type which represents superior <i>case</i>
1096 * choice case node which is mapped to generated type
1097 * @throws IllegalArgumentException
1099 * <li>if <code>refChoiceType</code> equals null</li>
1100 * <li>if <code>caseNodes</code> equals null</li>
1103 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1104 final ChoiceSchemaNode choiceNode) {
1105 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1106 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1108 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1109 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1110 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1111 caseTypeBuilder.addImplementsType(refChoiceType);
1112 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1113 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1114 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1115 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1116 if (caseChildNodes != null) {
1117 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1119 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1120 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1122 if (parent instanceof AugmentationSchemaNode) {
1123 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1124 final SchemaPath targetPath = augSchema.getTargetPath();
1125 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1126 if (targetSchemaNode instanceof DataSchemaNode
1127 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1128 if (targetSchemaNode instanceof DerivableSchemaNode) {
1129 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1132 if (targetSchemaNode == null) {
1133 throw new IllegalStateException(
1134 "Failed to find target node from grouping for augmentation " + augSchema
1135 + " in module " + context.module().getName());
1138 parent = targetSchemaNode;
1141 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1142 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1143 if (childOfType == null) {
1144 childOfType = findGroupingByPath(parent.getPath());
1146 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1148 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1152 processUsesAugments(caseNode, context);
1157 * Generates list of generated types for all the cases of a choice which are
1158 * added to the choice through the augment.
1162 * @param basePackageName
1163 * string contains name of package to which augment belongs. If
1164 * an augmented choice is from an other package (pcg1) than an
1165 * augmenting choice (pcg2) then case's of the augmenting choice
1166 * will belong to pcg2.
1168 * Type which represents target choice
1170 * node which represents target choice
1171 * @param augmentedNodes
1172 * set of choice case nodes for which is checked if are/aren't
1173 * added to choice through augmentation
1174 * @throws IllegalArgumentException
1176 * <li>if <code>basePackageName</code> is null</li>
1177 * <li>if <code>targetType</code> is null</li>
1178 * <li>if <code>augmentedNodes</code> is null</li>
1181 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1182 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1183 final DataNodeContainer usesNodeParent) {
1184 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1185 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1187 for (final DataSchemaNode caseNode : augmentedNodes) {
1188 if (caseNode != null) {
1189 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1190 caseTypeBuilder.addImplementsType(targetType);
1193 final SchemaPath nodeSp = targetNode.getPath();
1194 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1196 GeneratedTypeBuilder childOfType = null;
1197 if (parent instanceof Module) {
1198 childOfType = moduleContext(((Module) parent).getQNameModule()).getModuleNode();
1199 } else if (parent instanceof CaseSchemaNode) {
1200 childOfType = findCaseByPath(parent.getPath());
1201 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1202 childOfType = findChildNodeByPath(parent.getPath());
1203 } else if (parent instanceof GroupingDefinition) {
1204 childOfType = findGroupingByPath(parent.getPath());
1207 if (childOfType == null) {
1208 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1211 CaseSchemaNode node = null;
1212 final String caseLocalName = caseNode.getQName().getLocalName();
1213 if (caseNode instanceof CaseSchemaNode) {
1214 node = (CaseSchemaNode) caseNode;
1215 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1216 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1217 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1218 if (dataSchemaNode instanceof ChoiceSchemaNode
1219 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1220 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1225 node = findNamedCase(targetNode, caseLocalName);
1227 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1228 if (childNodes != null) {
1229 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1231 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1232 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1237 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1238 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1239 return cases.isEmpty() ? null : cases.get(0);
1242 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1243 // New parser with encapsulated type
1244 if (leaf.getPath().equals(type.getPath())) {
1248 // Embedded type definition with new parser. Also takes care of the old parser with bits
1249 if (leaf.getPath().equals(type.getPath().getParent())) {
1256 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1257 final List<PatternConstraint> patternConstraints) {
1258 if (!patternConstraints.isEmpty()) {
1259 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1260 .append(BindingMapping.getPropertyName(leafName));
1261 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1262 typeProvider.resolveRegExpressions(patternConstraints));
1267 * Converts <code>leaf</code> to the getter method which is added to
1268 * <code>typeBuilder</code>.
1270 * @param typeBuilder
1271 * generated type builder to which is added getter method as
1272 * <code>leaf</code> mapping
1274 * leaf schema node which is mapped as getter method which is
1275 * added to <code>typeBuilder</code>
1277 * Module in which type was defined
1278 * @return boolean value
1280 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1282 * <li>true - in other cases</li>
1285 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1286 final ModuleContext context) {
1287 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1291 final Module parentModule = findParentModule(schemaContext, leaf);
1292 Type returnType = null;
1294 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1295 if (isInnerType(leaf, typeDef)) {
1296 if (typeDef instanceof EnumTypeDefinition) {
1297 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1298 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1299 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1300 typeBuilder, context);
1301 if (enumBuilder != null) {
1302 returnType = enumBuilder.toInstance(typeBuilder);
1304 typeProvider.putReferencedType(leaf.getPath(), returnType);
1305 } else if (typeDef instanceof UnionTypeDefinition) {
1306 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1308 if (genTOBuilder != null) {
1309 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1310 // Store the inner type within the union so that we can find the reference for it
1311 context.addInnerTypedefType(typeDef.getPath(), returnType);
1313 } else if (typeDef instanceof BitsTypeDefinition) {
1314 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1316 if (genTOBuilder != null) {
1317 returnType = genTOBuilder.build();
1320 // It is constrained version of already declared type (inner declared type exists,
1321 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1322 // In order to get proper class we need to look up closest derived type
1323 // and apply restrictions from leaf type
1324 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1325 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1327 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1330 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1331 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1332 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1335 if (returnType == null) {
1339 if (typeDef instanceof EnumTypeDefinition) {
1340 typeProvider.putReferencedType(leaf.getPath(), returnType);
1343 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1344 processContextRefExtension(leaf, getter, parentModule);
1348 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1349 // Returns DerivedType in case of new parser.
1350 final TypeDefinition<?> baseType = typeDef.getBaseType();
1351 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1354 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1355 final Module module) {
1356 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1357 final QName nodeType = node.getNodeType();
1358 if ("context-reference".equals(nodeType.getLocalName())) {
1359 final String nodeParam = node.getNodeParameter();
1360 IdentitySchemaNode identity = null;
1361 String basePackageName = null;
1362 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1363 final Iterator<String> iterator = splittedElement.iterator();
1364 final int length = Iterables.size(splittedElement);
1366 identity = findIdentityByName(module.getIdentities(), iterator.next());
1367 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1368 } else if (length == 2) {
1369 final String prefix = iterator.next();
1370 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1371 if (dependentModule == null) {
1372 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1375 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1376 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1378 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1381 if (identity == null) {
1382 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1386 final AnnotationTypeBuilder rc = getter.addAnnotation(JavaTypeName.create(RoutingContext.class));
1387 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1388 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1389 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1394 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1395 for (final IdentitySchemaNode id : identities) {
1396 if (id.getQName().getLocalName().equals(name)) {
1403 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1404 for (final ModuleImport imp : imports) {
1405 if (imp.getPrefix().equals(prefix)) {
1406 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1412 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1413 final boolean isReadOnly) {
1414 if (leaf != null && toBuilder != null) {
1416 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1417 if (typeDef instanceof UnionTypeDefinition) {
1418 // GeneratedType for this type definition should have be already created
1419 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1420 returnType = mc.getTypedefs().get(typeDef.getPath());
1421 if (returnType == null) {
1422 // This may still be an inner type, try to find it
1423 returnType = mc.getInnerType(typeDef.getPath());
1425 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1426 // Annonymous enumeration (already generated, since it is inherited via uses).
1427 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1428 QName qname = originalLeaf.getQName();
1429 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1431 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1433 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1439 * Converts <code>leaf</code> schema node to property of generated TO
1443 * generated TO builder to which is <code>leaf</code> added as
1446 * leaf schema node which is added to <code>toBuilder</code> as
1451 * boolean value which says if leaf property is|isn't read only
1452 * @return boolean value
1454 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1455 * name equals null or if leaf is added by <i>uses</i>.</li>
1456 * <li>true - other cases</li>
1459 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1460 final Type returnType, final boolean isReadOnly) {
1461 if (returnType == null) {
1464 final String leafName = leaf.getQName().getLocalName();
1465 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1466 propBuilder.setReadOnly(isReadOnly);
1467 propBuilder.setReturnType(returnType);
1468 addComment(propBuilder, leaf);
1470 toBuilder.addEqualsIdentity(propBuilder);
1471 toBuilder.addHashIdentity(propBuilder);
1472 toBuilder.addToStringProperty(propBuilder);
1477 * Converts <code>node</code> leaf list schema node to getter method of
1478 * <code>typeBuilder</code>.
1480 * @param typeBuilder
1481 * generated type builder to which is <code>node</code> added as
1484 * leaf list schema node which is added to
1485 * <code>typeBuilder</code> as getter method
1486 * @param module module
1487 * @return boolean value
1489 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1490 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1491 * <li>false - other cases</li>
1494 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1495 final ModuleContext context) {
1496 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1500 final QName nodeName = node.getQName();
1502 final TypeDefinition<?> typeDef = node.getType();
1503 final Module parentModule = findParentModule(schemaContext, node);
1505 Type returnType = null;
1506 if (typeDef.getBaseType() == null) {
1507 if (typeDef instanceof EnumTypeDefinition) {
1508 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1509 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1510 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1511 typeBuilder, context);
1512 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1513 typeProvider.putReferencedType(node.getPath(), returnType);
1514 } else if (typeDef instanceof UnionTypeDefinition) {
1515 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1516 node, parentModule);
1517 if (genTOBuilder != null) {
1518 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1520 } else if (typeDef instanceof BitsTypeDefinition) {
1521 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1522 node, parentModule);
1523 returnType = genTOBuilder.build();
1525 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1526 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1527 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1530 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1531 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1532 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1535 final ParameterizedType listType = Types.listTypeFor(returnType);
1536 constructGetter(typeBuilder, listType, node);
1540 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1541 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1542 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1544 addCodegenInformation(returnType, parentModule, typeDef);
1545 returnType.setSchemaPath(typeDef.getPath());
1546 returnType.setModuleName(parentModule.getName());
1548 genTOBuilder.setTypedef(true);
1549 genTOBuilder.setIsUnion(true);
1550 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1554 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1557 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1558 method.setReturnType(returnType);
1559 method.addParameter(Types.STRING, "defaultValue");
1560 method.setAccessModifier(AccessModifier.PUBLIC);
1561 method.setStatic(true);
1563 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1564 if (types == null) {
1565 typeProvider.getAdditionalTypes().put(parentModule,
1566 Sets.newHashSet(unionBuilder.build()));
1568 types.add(unionBuilder.build());
1570 return returnType.build();
1573 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1574 final GeneratedTypeBuilder typeBuilder) {
1575 final StringBuilder sb = new StringBuilder();
1577 // Append enclosing path hierarchy without dots
1578 // TODO: JavaTypeName could be giving us a Stream<String> or similar, but there is no sense in generalizing
1579 // unless there is another caller.
1580 Optional<JavaTypeName> outerClass = genTOBuilder.getIdentifier().immediatelyEnclosingClass();
1581 if (outerClass.isPresent()) {
1582 final Deque<String> enclosingPath = new ArrayDeque<>();
1584 final JavaTypeName outerName = outerClass.get();
1585 enclosingPath.push(outerName.simpleName());
1586 outerClass = outerName.immediatelyEnclosingClass();
1587 } while (outerClass.isPresent());
1589 while (!enclosingPath.isEmpty()) {
1590 sb.append(enclosingPath.pop());
1594 sb.append(genTOBuilder.getName()).append("Builder");
1595 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1596 JavaTypeName.create(typeBuilder.getPackageName(), sb.toString()));
1597 unionBuilder.setIsUnionBuilder(true);
1598 return unionBuilder;
1601 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1602 final SchemaNode schemaNode) {
1603 return addDefaultInterfaceDefinition(context, schemaNode, null);
1606 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1607 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1608 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1609 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1614 * Instantiates generated type builder with <code>packageName</code> and
1615 * <code>schemaNode</code>.
1617 * The new builder always implements
1618 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1619 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1620 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1622 * If <code>schemaNode</code> is instance of
1623 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1624 * DataNodeContainer} it can also implement nodes which are specified in
1627 * @param packageName
1628 * string with the name of the package to which
1629 * <code>schemaNode</code> belongs.
1631 * schema node for which is created generated type builder
1633 * parent type (can be null)
1634 * @return generated type builder <code>schemaNode</code>
1636 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1637 final Type parent, final ModuleContext context) {
1638 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1639 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1640 if (parent == null) {
1641 it.addImplementsType(DATA_OBJECT);
1643 it.addImplementsType(BindingTypes.childOf(parent));
1645 if (!(schemaNode instanceof GroupingDefinition)) {
1646 it.addImplementsType(augmentable(it));
1649 if (schemaNode instanceof DataNodeContainer) {
1650 groupingsToGenTypes(context, ((DataNodeContainer) schemaNode).getGroupings());
1651 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1658 * Wraps the calling of the same overloaded method.
1660 * @param packageName
1661 * string with the package name to which returning generated type
1664 * schema node which provide data about the schema node name
1665 * @return generated type builder for <code>schemaNode</code>
1667 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1668 final String prefix) {
1669 return addRawInterfaceDefinition(
1670 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1671 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1675 * Returns reference to generated type builder for specified
1676 * <code>schemaNode</code> with <code>packageName</code>.
1678 * Firstly the generated type builder is searched in
1679 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1680 * found it is created and added to <code>genTypeBuilders</code>.
1682 * @param packageName
1683 * string with the package name to which returning generated type
1686 * schema node which provide data about the schema node name
1688 * return type name prefix
1689 * @return generated type builder for <code>schemaNode</code>
1690 * @throws IllegalArgumentException
1692 * <li>if <code>schemaNode</code> is null</li>
1693 * <li>if <code>packageName</code> is null</li>
1694 * <li>if QName of schema node is null</li>
1695 * <li>if schemaNode name is null</li>
1699 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1700 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1701 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1702 final String schemaNodeName = schemaNode.getQName().getLocalName();
1703 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1705 // FIXME: Validation of name conflict
1706 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1707 final Module module = findParentModule(schemaContext, schemaNode);
1708 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1710 addCodegenInformation(newType, module, schemaNode);
1711 newType.setSchemaPath(schemaNode.getPath());
1712 newType.setModuleName(module.getName());
1714 final String packageName = identifier.packageName();
1715 final String simpleName = identifier.simpleName();
1716 if (!genTypeBuilders.containsKey(packageName)) {
1717 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1718 builders.put(simpleName, newType);
1719 genTypeBuilders.put(packageName, builders);
1721 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1722 if (!builders.containsKey(simpleName)) {
1723 builders.put(simpleName, newType);
1730 * Creates the name of the getter method name from <code>localName</code>.
1733 * string with the name of the getter method
1736 * @return string with the name of the getter method for
1737 * <code>methodName</code> in JAVA method format
1739 public static String getterMethodName(final String localName, final Type returnType) {
1740 final StringBuilder method = new StringBuilder();
1741 if (BOOLEAN.equals(returnType)) {
1742 method.append("is");
1744 method.append("get");
1746 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1747 method.append(name);
1748 return method.toString();
1752 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1754 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1755 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1757 * @param interfaceBuilder generated type builder for which the getter method should be created
1758 * @param returnType type which represents the return type of the getter method
1759 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1760 * @param comment string with comment for the getter method
1761 * @param status status from yang file, for deprecated annotation
1762 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1764 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1765 final SchemaNode node) {
1766 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1767 getterMethodName(node.getQName().getLocalName(), returnType));
1768 getMethod.setReturnType(returnType);
1770 if (node.getStatus() == Status.DEPRECATED) {
1771 getMethod.addAnnotation("java.lang", "Deprecated");
1773 addComment(getMethod, node);
1779 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1780 * or to <code>genTOBuilder</code> as property.
1782 * @param basePackageName
1783 * string contains the module package name
1785 * data schema node which should be added as getter method to
1786 * <code>typeBuilder</code> or as a property to
1787 * <code>genTOBuilder</code> if is part of the list key
1788 * @param typeBuilder
1789 * generated type builder for the list schema node
1790 * @param genTOBuilder
1791 * generated TO builder for the list keys
1793 * list of string which contains names of the list keys
1796 * @throws IllegalArgumentException
1798 * <li>if <code>schemaNode</code> equals null</li>
1799 * <li>if <code>typeBuilder</code> equals null</li>
1802 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1803 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1804 final List<String> listKeys) {
1805 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1806 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1808 if (schemaNode instanceof LeafSchemaNode) {
1809 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1810 final String leafName = leaf.getQName().getLocalName();
1811 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1812 if (listKeys.contains(leafName)) {
1814 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1816 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1819 } else if (!schemaNode.isAddedByUses()) {
1820 if (schemaNode instanceof LeafListSchemaNode) {
1821 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1822 } else if (schemaNode instanceof ContainerSchemaNode) {
1823 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1824 } else if (schemaNode instanceof ChoiceSchemaNode) {
1825 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1826 } else if (schemaNode instanceof ListSchemaNode) {
1827 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1832 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1833 final GeneratedTOBuilder genTOBuilder) {
1834 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1836 if (genTOBuilder != null) {
1837 final GeneratedTransferObject genTO = genTOBuilder.build();
1839 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1840 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1841 getMethod.setReturnType(genTO);
1842 getMethod.setComment("Returns Primary Key of Yang List Type");
1843 context.addGeneratedTOBuilder(genTOBuilder);
1848 * Selects the names of the list keys from <code>list</code> and returns
1849 * them as the list of the strings
1852 * of string with names of the list keys
1853 * @return list of string which represents names of the list keys. If the
1854 * <code>list</code> contains no keys then the empty list is
1857 private static List<String> listKeys(final ListSchemaNode list) {
1858 final List<String> listKeys = new ArrayList<>();
1860 final List<QName> keyDefinition = list.getKeyDefinition();
1861 if (keyDefinition != null) {
1862 for (final QName keyDef : keyDefinition) {
1863 listKeys.add(keyDef.getLocalName());
1870 * Generates for the <code>list</code> which contains any list keys special
1871 * generated TO builder.
1873 * @param packageName
1874 * string with package name to which the list belongs
1876 * list schema node which is source of data about the list name
1877 * @return generated TO builder which represents the keys of the
1878 * <code>list</code> or null if <code>list</code> is null or list of
1879 * key definitions is null or empty.
1881 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1882 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1883 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1884 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1885 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1891 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1893 * If more then one generated TO builder is created for enclosing then all
1894 * of the generated TO builders are added to <code>typeBuilder</code> as
1895 * enclosing transfer objects.
1898 * type definition which can be of type <code>UnionType</code> or
1899 * <code>BitsTypeDefinition</code>
1900 * @param typeBuilder
1901 * generated type builder to which is added generated TO created
1902 * from <code>typeDef</code>
1904 * string with name for generated TO builder
1905 * @param parentModule
1907 * @return generated TO builder for <code>typeDef</code>
1909 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1910 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1911 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1912 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1915 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1916 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1917 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1918 for (final GeneratedTOBuilder genTOBuilder : types) {
1919 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1922 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1923 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1924 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1925 resultTOBuilder.addHashIdentity(genPropBuilder);
1926 resultTOBuilder.addToStringProperty(genPropBuilder);
1927 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1928 return resultTOBuilder;
1932 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1933 * also added to <code>typeBuilder</code> as enclosing transfer object.
1935 * If more then one generated TO builder is created for enclosing then all
1936 * of the generated TO builders are added to <code>typeBuilder</code> as
1937 * enclosing transfer objects.
1940 * type definition which can be of type <code>UnionType</code> or
1941 * <code>BitsTypeDefinition</code>
1942 * @param typeBuilder
1943 * generated type builder to which is added generated TO created
1944 * from <code>typeDef</code>
1946 * string with name for generated TO builder
1947 * @param parentModule
1949 * @return generated TO builder for <code>typeDef</code>
1951 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1952 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1953 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1954 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1955 typeDef, parentModule.getName());
1956 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1957 return genTOBuilder;
1961 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1962 final List<GeneratedTOBuilder> genTOBuilders) {
1963 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1964 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1966 return genTOBuilders.get(0);
1970 * Adds the implemented types to type builder.
1972 * The method passes through the list of <i>uses</i> in
1973 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1974 * generated type from {@link ModuleContext#groupings
1975 * allGroupings} which is added as <i>implements type</i> to
1976 * <code>builder</code>
1978 * @param dataNodeContainer
1979 * element which contains the list of used YANG groupings
1981 * builder to which are added implemented types according to
1982 * <code>dataNodeContainer</code>
1983 * @return generated type builder with all implemented types
1985 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1986 final GeneratedTypeBuilder builder) {
1987 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1988 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1989 if (genType == null) {
1990 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1991 + builder.getName());
1994 builder.addImplementsType(genType);
1999 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2000 for (final ModuleContext ctx : genCtx.values()) {
2001 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2002 if (result != null) {
2009 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2010 for (final ModuleContext ctx : genCtx.values()) {
2011 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2012 if (result != null) {
2019 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2020 for (final ModuleContext ctx : genCtx.values()) {
2021 final GeneratedTypeBuilder result = ctx.getCase(path);
2022 if (result != null) {
2029 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2030 if (status == Status.DEPRECATED) {
2031 builder.addAnnotation("java.lang", "Deprecated");