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 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1307 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1308 // Store the inner type within the union so that we can find the reference for it
1309 context.addInnerTypedefType(typeDef.getPath(), returnType);
1310 } else if (typeDef instanceof BitsTypeDefinition) {
1311 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1313 if (genTOBuilder != null) {
1314 returnType = genTOBuilder.build();
1317 // It is constrained version of already declared type (inner declared type exists,
1318 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1319 // In order to get proper class we need to look up closest derived type
1320 // and apply restrictions from leaf type
1321 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1322 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1324 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1327 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1328 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1329 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1332 if (returnType == null) {
1336 if (typeDef instanceof EnumTypeDefinition) {
1337 typeProvider.putReferencedType(leaf.getPath(), returnType);
1340 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1341 processContextRefExtension(leaf, getter, parentModule);
1345 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1346 // Returns DerivedType in case of new parser.
1347 final TypeDefinition<?> baseType = typeDef.getBaseType();
1348 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1351 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1352 final Module module) {
1353 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1354 final QName nodeType = node.getNodeType();
1355 if ("context-reference".equals(nodeType.getLocalName())) {
1356 final String nodeParam = node.getNodeParameter();
1357 IdentitySchemaNode identity = null;
1358 String basePackageName = null;
1359 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1360 final Iterator<String> iterator = splittedElement.iterator();
1361 final int length = Iterables.size(splittedElement);
1363 identity = findIdentityByName(module.getIdentities(), iterator.next());
1364 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1365 } else if (length == 2) {
1366 final String prefix = iterator.next();
1367 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1368 if (dependentModule == null) {
1369 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1372 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1373 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1375 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1378 if (identity == null) {
1379 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1383 final AnnotationTypeBuilder rc = getter.addAnnotation(JavaTypeName.create(RoutingContext.class));
1384 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1385 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1386 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1391 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1392 for (final IdentitySchemaNode id : identities) {
1393 if (id.getQName().getLocalName().equals(name)) {
1400 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1401 for (final ModuleImport imp : imports) {
1402 if (imp.getPrefix().equals(prefix)) {
1403 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1409 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1410 final boolean isReadOnly) {
1411 if (leaf != null && toBuilder != null) {
1413 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1414 if (typeDef instanceof UnionTypeDefinition) {
1415 // GeneratedType for this type definition should have be already created
1416 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1417 returnType = mc.getTypedefs().get(typeDef.getPath());
1418 if (returnType == null) {
1419 // This may still be an inner type, try to find it
1420 returnType = mc.getInnerType(typeDef.getPath());
1422 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1423 // Annonymous enumeration (already generated, since it is inherited via uses).
1424 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1425 QName qname = originalLeaf.getQName();
1426 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1428 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1430 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1436 * Converts <code>leaf</code> schema node to property of generated TO
1440 * generated TO builder to which is <code>leaf</code> added as
1443 * leaf schema node which is added to <code>toBuilder</code> as
1448 * boolean value which says if leaf property is|isn't read only
1449 * @return boolean value
1451 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1452 * name equals null or if leaf is added by <i>uses</i>.</li>
1453 * <li>true - other cases</li>
1456 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1457 final Type returnType, final boolean isReadOnly) {
1458 if (returnType == null) {
1461 final String leafName = leaf.getQName().getLocalName();
1462 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1463 propBuilder.setReadOnly(isReadOnly);
1464 propBuilder.setReturnType(returnType);
1465 addComment(propBuilder, leaf);
1467 toBuilder.addEqualsIdentity(propBuilder);
1468 toBuilder.addHashIdentity(propBuilder);
1469 toBuilder.addToStringProperty(propBuilder);
1474 * Converts <code>node</code> leaf list schema node to getter method of
1475 * <code>typeBuilder</code>.
1477 * @param typeBuilder
1478 * generated type builder to which is <code>node</code> added as
1481 * leaf list schema node which is added to
1482 * <code>typeBuilder</code> as getter method
1483 * @param module module
1484 * @return boolean value
1486 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1487 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1488 * <li>false - other cases</li>
1491 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1492 final ModuleContext context) {
1493 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1497 final QName nodeName = node.getQName();
1499 final TypeDefinition<?> typeDef = node.getType();
1500 final Module parentModule = findParentModule(schemaContext, node);
1502 Type returnType = null;
1503 if (typeDef.getBaseType() == null) {
1504 if (typeDef instanceof EnumTypeDefinition) {
1505 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1506 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1507 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1508 typeBuilder, context);
1509 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1510 typeProvider.putReferencedType(node.getPath(), returnType);
1511 } else if (typeDef instanceof UnionTypeDefinition) {
1512 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1513 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1514 } else if (typeDef instanceof BitsTypeDefinition) {
1515 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1516 node, parentModule);
1517 returnType = genTOBuilder.build();
1519 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1520 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1521 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1524 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1525 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1526 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1529 final ParameterizedType listType = Types.listTypeFor(returnType);
1530 constructGetter(typeBuilder, listType, node);
1534 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1535 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1536 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1537 returnTypeBuilder.setIsUnion(true);
1538 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1539 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1540 returnTypeBuilder.setModuleName(parentModule.getName());
1541 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1543 genTOBuilder.setTypedef(true);
1544 genTOBuilder.setIsUnion(true);
1545 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1547 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1551 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1552 final GeneratedTransferObject returnType, final Module parentModule) {
1553 final StringBuilder sb = new StringBuilder();
1555 // Append enclosing path hierarchy without dots
1556 // TODO: JavaTypeName could be giving us a Stream<String> or similar, but there is no sense in generalizing
1557 // unless there is another caller.
1558 Optional<JavaTypeName> outerClass = genTOBuilder.getIdentifier().immediatelyEnclosingClass();
1559 if (outerClass.isPresent()) {
1560 final Deque<String> enclosingPath = new ArrayDeque<>();
1562 final JavaTypeName outerName = outerClass.get();
1563 enclosingPath.push(outerName.simpleName());
1564 outerClass = outerName.immediatelyEnclosingClass();
1565 } while (outerClass.isPresent());
1567 while (!enclosingPath.isEmpty()) {
1568 sb.append(enclosingPath.pop());
1572 sb.append(genTOBuilder.getName()).append("Builder");
1573 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1574 JavaTypeName.create(typeBuilder.getPackageName(), sb.toString()));
1575 unionBuilder.setIsUnionBuilder(true);
1577 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1578 method.setReturnType(returnType);
1579 method.addParameter(Types.STRING, "defaultValue");
1580 method.setAccessModifier(AccessModifier.PUBLIC);
1581 method.setStatic(true);
1583 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1584 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1585 if (types == null) {
1586 typeProvider.getAdditionalTypes().put(parentModule, Sets.newHashSet(unionBuilderType));
1588 types.add(unionBuilderType);
1592 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1593 final SchemaNode schemaNode) {
1594 return addDefaultInterfaceDefinition(context, schemaNode, null);
1597 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1598 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1599 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1600 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1604 * Instantiates generated type builder with <code>packageName</code> and
1605 * <code>schemaNode</code>.
1607 * The new builder always implements
1608 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1609 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1610 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1612 * If <code>schemaNode</code> is instance of
1613 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1614 * DataNodeContainer} it can also implement nodes which are specified in
1617 * @param packageName
1618 * string with the name of the package to which
1619 * <code>schemaNode</code> belongs.
1621 * schema node for which is created generated type builder
1623 * parent type (can be null)
1624 * @return generated type builder <code>schemaNode</code>
1626 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1627 final Type parent, final ModuleContext context) {
1628 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1629 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1630 if (parent == null) {
1631 it.addImplementsType(DATA_OBJECT);
1633 it.addImplementsType(BindingTypes.childOf(parent));
1635 if (!(schemaNode instanceof GroupingDefinition)) {
1636 it.addImplementsType(augmentable(it));
1639 if (schemaNode instanceof DataNodeContainer) {
1640 groupingsToGenTypes(context, ((DataNodeContainer) schemaNode).getGroupings());
1641 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1648 * Wraps the calling of the same overloaded method.
1650 * @param packageName
1651 * string with the package name to which returning generated type
1654 * schema node which provide data about the schema node name
1655 * @return generated type builder for <code>schemaNode</code>
1657 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1658 final String prefix) {
1659 return addRawInterfaceDefinition(
1660 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1661 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1665 * Returns reference to generated type builder for specified
1666 * <code>schemaNode</code> with <code>packageName</code>.
1668 * Firstly the generated type builder is searched in
1669 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1670 * found it is created and added to <code>genTypeBuilders</code>.
1672 * @param packageName
1673 * string with the package name to which returning generated type
1676 * schema node which provide data about the schema node name
1678 * return type name prefix
1679 * @return generated type builder for <code>schemaNode</code>
1680 * @throws IllegalArgumentException
1682 * <li>if <code>schemaNode</code> is null</li>
1683 * <li>if <code>packageName</code> is null</li>
1684 * <li>if QName of schema node is null</li>
1685 * <li>if schemaNode name is null</li>
1689 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1690 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1691 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1692 final String schemaNodeName = schemaNode.getQName().getLocalName();
1693 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1695 // FIXME: Validation of name conflict
1696 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1697 final Module module = findParentModule(schemaContext, schemaNode);
1698 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1700 addCodegenInformation(newType, module, schemaNode);
1701 newType.setSchemaPath(schemaNode.getPath());
1702 newType.setModuleName(module.getName());
1704 final String packageName = identifier.packageName();
1705 final String simpleName = identifier.simpleName();
1706 if (!genTypeBuilders.containsKey(packageName)) {
1707 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1708 builders.put(simpleName, newType);
1709 genTypeBuilders.put(packageName, builders);
1711 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1712 if (!builders.containsKey(simpleName)) {
1713 builders.put(simpleName, newType);
1720 * Creates the name of the getter method name from <code>localName</code>.
1723 * string with the name of the getter method
1726 * @return string with the name of the getter method for
1727 * <code>methodName</code> in JAVA method format
1729 public static String getterMethodName(final String localName, final Type returnType) {
1730 final StringBuilder method = new StringBuilder();
1731 if (BOOLEAN.equals(returnType)) {
1732 method.append("is");
1734 method.append("get");
1736 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1737 method.append(name);
1738 return method.toString();
1742 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1744 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1745 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1747 * @param interfaceBuilder generated type builder for which the getter method should be created
1748 * @param returnType type which represents the return type of the getter method
1749 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1750 * @param comment string with comment for the getter method
1751 * @param status status from yang file, for deprecated annotation
1752 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1754 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1755 final SchemaNode node) {
1756 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1757 getterMethodName(node.getQName().getLocalName(), returnType));
1758 getMethod.setReturnType(returnType);
1760 if (node.getStatus() == Status.DEPRECATED) {
1761 getMethod.addAnnotation("java.lang", "Deprecated");
1763 addComment(getMethod, node);
1769 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1770 * or to <code>genTOBuilder</code> as property.
1772 * @param basePackageName
1773 * string contains the module package name
1775 * data schema node which should be added as getter method to
1776 * <code>typeBuilder</code> or as a property to
1777 * <code>genTOBuilder</code> if is part of the list key
1778 * @param typeBuilder
1779 * generated type builder for the list schema node
1780 * @param genTOBuilder
1781 * generated TO builder for the list keys
1783 * list of string which contains names of the list keys
1786 * @throws IllegalArgumentException
1788 * <li>if <code>schemaNode</code> equals null</li>
1789 * <li>if <code>typeBuilder</code> equals null</li>
1792 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1793 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1794 final List<String> listKeys) {
1795 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1796 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1798 if (schemaNode instanceof LeafSchemaNode) {
1799 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1800 final String leafName = leaf.getQName().getLocalName();
1801 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1802 if (listKeys.contains(leafName)) {
1804 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1806 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1809 } else if (!schemaNode.isAddedByUses()) {
1810 if (schemaNode instanceof LeafListSchemaNode) {
1811 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1812 } else if (schemaNode instanceof ContainerSchemaNode) {
1813 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1814 } else if (schemaNode instanceof ChoiceSchemaNode) {
1815 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1816 } else if (schemaNode instanceof ListSchemaNode) {
1817 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1822 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1823 final GeneratedTOBuilder genTOBuilder) {
1824 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1826 if (genTOBuilder != null) {
1827 final GeneratedTransferObject genTO = genTOBuilder.build();
1829 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1830 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1831 getMethod.setReturnType(genTO);
1832 getMethod.setComment("Returns Primary Key of Yang List Type");
1833 context.addGeneratedTOBuilder(genTOBuilder);
1838 * Selects the names of the list keys from <code>list</code> and returns
1839 * them as the list of the strings
1842 * of string with names of the list keys
1843 * @return list of string which represents names of the list keys. If the
1844 * <code>list</code> contains no keys then the empty list is
1847 private static List<String> listKeys(final ListSchemaNode list) {
1848 final List<String> listKeys = new ArrayList<>();
1850 final List<QName> keyDefinition = list.getKeyDefinition();
1851 if (keyDefinition != null) {
1852 for (final QName keyDef : keyDefinition) {
1853 listKeys.add(keyDef.getLocalName());
1860 * Generates for the <code>list</code> which contains any list keys special
1861 * generated TO builder.
1863 * @param packageName
1864 * string with package name to which the list belongs
1866 * list schema node which is source of data about the list name
1867 * @return generated TO builder which represents the keys of the
1868 * <code>list</code> or null if <code>list</code> is null or list of
1869 * key definitions is null or empty.
1871 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1872 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1873 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1874 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1875 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1881 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1883 * If more then one generated TO builder is created for enclosing then all
1884 * of the generated TO builders are added to <code>typeBuilder</code> as
1885 * enclosing transfer objects.
1888 * type definition which can be of type <code>UnionType</code> or
1889 * <code>BitsTypeDefinition</code>
1890 * @param typeBuilder
1891 * generated type builder to which is added generated TO created
1892 * from <code>typeDef</code>
1894 * string with name for generated TO builder
1895 * @param parentModule
1897 * @return generated TO builder for <code>typeDef</code>
1899 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1900 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1901 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1902 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1905 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1906 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1907 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1908 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1909 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1911 for (GeneratedTOBuilder builder : types) {
1912 if (builder.isUnion()) {
1913 final GeneratedTransferObject type = builder.build();
1914 createUnionBuilder(builder, typeBuilder, type, parentModule);
1918 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1922 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1923 * also added to <code>typeBuilder</code> as enclosing transfer object.
1925 * If more then one generated TO builder is created for enclosing then all
1926 * of the generated TO builders are added to <code>typeBuilder</code> as
1927 * enclosing transfer objects.
1930 * type definition which can be of type <code>UnionType</code> or
1931 * <code>BitsTypeDefinition</code>
1932 * @param typeBuilder
1933 * generated type builder to which is added generated TO created
1934 * from <code>typeDef</code>
1936 * string with name for generated TO builder
1937 * @param parentModule
1939 * @return generated TO builder for <code>typeDef</code>
1941 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1942 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1943 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1944 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1945 typeDef, parentModule.getName());
1946 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1947 return genTOBuilder;
1952 * Adds the implemented types to type builder.
1954 * The method passes through the list of <i>uses</i> in
1955 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1956 * generated type from {@link ModuleContext#groupings
1957 * allGroupings} which is added as <i>implements type</i> to
1958 * <code>builder</code>
1960 * @param dataNodeContainer
1961 * element which contains the list of used YANG groupings
1963 * builder to which are added implemented types according to
1964 * <code>dataNodeContainer</code>
1965 * @return generated type builder with all implemented types
1967 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1968 final GeneratedTypeBuilder builder) {
1969 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1970 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1971 if (genType == null) {
1972 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1973 + builder.getName());
1976 builder.addImplementsType(genType);
1981 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1982 for (final ModuleContext ctx : genCtx.values()) {
1983 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1984 if (result != null) {
1991 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1992 for (final ModuleContext ctx : genCtx.values()) {
1993 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1994 if (result != null) {
2001 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2002 for (final ModuleContext ctx : genCtx.values()) {
2003 final GeneratedTypeBuilder result = ctx.getCase(path);
2004 if (result != null) {
2011 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2012 if (status == Status.DEPRECATED) {
2013 builder.addAnnotation("java.lang", "Deprecated");