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 String enumerationName = BindingMapping.getClassName(enumName);
653 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
654 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
655 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
656 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
663 * Generates type builder for <code>module</code>.
666 * Module which is source of package name for generated type
669 * string which is added to the module class name representation
671 * @return instance of GeneratedTypeBuilder which represents
672 * <code>module</code>.
673 * @throws IllegalArgumentException
674 * if <code>module</code> is null
676 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
677 final Module module = context.module();
678 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
679 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
680 JavaTypeName.create(context.modulePackageName(), moduleName));
682 moduleBuilder.setModuleName(moduleName);
683 addCodegenInformation(moduleBuilder, module);
684 return moduleBuilder;
688 * Converts <code>augSchema</code> to list of <code>Type</code> which
689 * contains generated type for augmentation. In addition there are also
690 * generated types for all containers, list and choices which are child of
691 * <code>augSchema</code> node or a generated types for cases are added if
692 * augmented node is choice.
694 * @param augmentPackageName
695 * string with the name of the package to which the augmentation
698 * AugmentationSchema which is contains data about augmentation
699 * (target path, childs...)
702 * @throws IllegalArgumentException
704 * <li>if <code>augmentPackageName</code> equals null</li>
705 * <li>if <code>augSchema</code> equals null</li>
707 * @throws IllegalStateException
708 * if augment target path is null
710 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
711 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
712 checkState(augSchema.getTargetPath() != null,
713 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
715 processUsesAugments(augSchema, context);
716 final SchemaPath targetPath = augSchema.getTargetPath();
717 SchemaNode targetSchemaNode = null;
719 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
720 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
721 if (targetSchemaNode instanceof DerivableSchemaNode) {
722 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
724 if (targetSchemaNode == null) {
725 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
726 + " in module " + context.module().getName());
729 if (targetSchemaNode == null) {
730 throw new IllegalArgumentException("augment target not found: " + targetPath);
733 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
734 if (targetTypeBuilder == null) {
735 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
737 if (targetTypeBuilder == null) {
738 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
741 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
742 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
743 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
746 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
747 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
751 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
752 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
753 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
754 checkState(augSchema.getTargetPath() != null,
755 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
757 processUsesAugments(augSchema, context);
758 final SchemaPath targetPath = augSchema.getTargetPath();
759 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
760 if (targetSchemaNode == null) {
761 throw new IllegalArgumentException("augment target not found: " + targetPath);
764 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
765 if (targetTypeBuilder == null) {
766 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
768 if (targetTypeBuilder == null) {
769 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
772 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
773 if (usesNodeParent instanceof SchemaNode) {
774 addRawAugmentGenTypeDefinition(context,
775 packageNameForAugmentedGeneratedType(context.modulePackageName(),
776 ((SchemaNode) usesNodeParent).getPath()),
777 targetTypeBuilder.build(), augSchema);
779 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
782 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
783 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
788 * Convenient method to find node added by uses statement.
792 * @param parentUsesNode
793 * parent of uses node
794 * @return node from its original location in grouping
796 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
797 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
799 if (!(targetGrouping instanceof GroupingDefinition)) {
800 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
803 SchemaNode result = targetGrouping;
804 for (final QName node : targetPath.getPathFromRoot()) {
805 if (result instanceof DataNodeContainer) {
806 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
807 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
808 } else if (result instanceof ChoiceSchemaNode) {
809 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
812 if (result == null) {
816 if (result instanceof DerivableSchemaNode) {
817 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
818 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
819 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
820 result = originalNode.get();
824 if (result instanceof DataSchemaNode) {
825 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
826 if (resultDataSchemaNode.isAddedByUses()) {
827 // The original node is required, but we have only the copy of
828 // the original node.
829 // Maybe this indicates a bug in Yang parser.
830 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
833 return resultDataSchemaNode;
836 throw new IllegalStateException(
837 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
842 * Returns a generated type builder for an augmentation.
844 * The name of the type builder is equal to the name of augmented node with
845 * serial number as suffix.
849 * @param augmentPackageName
850 * string with contains the package name to which the augment
852 * @param basePackageName
853 * string with the package name to which the augmented node
855 * @param targetTypeRef
858 * augmentation schema which contains data about the child nodes
859 * and uses of augment
860 * @return generated type builder for augment
862 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
863 final String augmentPackageName, final Type targetTypeRef,
864 final AugmentationSchemaNode augSchema) {
865 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
866 if (augmentBuilders == null) {
867 augmentBuilders = new HashMap<>();
868 genTypeBuilders.put(augmentPackageName, augmentBuilders);
870 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
873 if (augIdentifier != null) {
874 augTypeName = BindingMapping.getClassName(augIdentifier);
876 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
879 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
880 JavaTypeName.create(augmentPackageName, augTypeName));
882 augTypeBuilder.addImplementsType(DATA_OBJECT);
883 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
884 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
885 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
887 augSchemaNodeToMethods(context,augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
888 augmentBuilders.put(augTypeName, augTypeBuilder);
890 if (!augSchema.getChildNodes().isEmpty()) {
891 context.addTypeToAugmentation(augTypeBuilder, augSchema);
894 context.addAugmentType(augTypeBuilder);
895 return augTypeBuilder;
898 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
899 final AugmentationSchemaNode augSchema) {
900 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
905 * @param unknownSchemaNodes
906 * @return nodeParameter of UnknownSchemaNode
908 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
909 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
910 final QName nodeType = unknownSchemaNode.getNodeType();
911 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
912 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
913 return unknownSchemaNode.getNodeParameter();
920 * Returns first unique name for the augment generated type builder. The
921 * generated type builder name for augment consists from name of augmented
922 * node and serial number of its augmentation.
925 * map of builders which were created in the package to which the
926 * augmentation belongs
928 * string with name of augmented node
929 * @return string with unique name for augmentation builder
931 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
933 if (builders != null) {
934 while (builders.containsKey(genTypeName + index)) {
938 return genTypeName + index;
942 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
943 * node for which <code>typeBuilder</code> was created.
945 * The subnodes aren't mapped to the methods if they are part of grouping or
946 * augment (in this case are already part of them).
951 * generated type builder which represents any node. The subnodes
952 * of this node are added to the <code>typeBuilder</code> as
953 * methods. The subnode can be of type leaf, leaf-list, list,
958 * set of data schema nodes which are the children of the node
959 * for which <code>typeBuilder</code> was created
960 * @return generated type builder which is the same builder as input
961 * parameter. The getter methods (representing child nodes) could be
964 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
965 final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
966 if (schemaNodes != null && parent != null) {
967 for (final DataSchemaNode schemaNode : schemaNodes) {
968 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
969 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
977 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
978 * node for which <code>typeBuilder</code> was created.
983 * generated type builder which represents any node. The subnodes
984 * of this node are added to the <code>typeBuilder</code> as
985 * methods. The subnode can be of type leaf, leaf-list, list,
990 * set of data schema nodes which are the children of the node
991 * for which <code>typeBuilder</code> was created
992 * @return generated type builder which is the same object as the input
993 * parameter <code>typeBuilder</code>. The getter method could be
996 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
997 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
998 final Iterable<DataSchemaNode> schemaNodes) {
999 if (schemaNodes != null && typeBuilder != null) {
1000 for (final DataSchemaNode schemaNode : schemaNodes) {
1001 if (!schemaNode.isAugmenting()) {
1002 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
1010 * Adds to <code>typeBuilder</code> a method which is derived from
1011 * <code>schemaNode</code>.
1014 * data schema node which is added to <code>typeBuilder</code> as
1016 * @param typeBuilder
1017 * generated type builder to which is <code>schemaNode</code>
1018 * added as a method.
1024 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1025 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf) {
1026 if (node != null && typeBuilder != null) {
1027 if (node instanceof LeafSchemaNode) {
1028 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1029 } else if (node instanceof LeafListSchemaNode) {
1030 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1031 } else if (node instanceof ContainerSchemaNode) {
1032 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1033 } else if (node instanceof ListSchemaNode) {
1034 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1035 } else if (node instanceof ChoiceSchemaNode) {
1036 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1038 // TODO: anyxml not yet supported
1039 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1040 typeBuilder.getFullyQualifiedName());
1046 * Converts <code>choiceNode</code> to the list of generated types for
1047 * choice and its cases.
1049 * The package names for choice and for its cases are created as
1050 * concatenation of the module package (<code>basePackageName</code>) and
1051 * names of all parents node.
1055 * @param basePackageName
1056 * string with the module package name
1060 * choice node which is mapped to generated type. Also child
1061 * nodes - cases are mapped to generated types.
1062 * @throws IllegalArgumentException
1064 * <li>if <code>basePackageName</code> is null</li>
1065 * <li>if <code>choiceNode</code> is null</li>
1068 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1069 final ChoiceSchemaNode choiceNode) {
1070 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1072 if (!choiceNode.isAddedByUses()) {
1073 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1074 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1075 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1076 constructGetter(parent, choiceTypeBuilder, choiceNode);
1077 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1078 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1079 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1080 generateTypesFromChoiceCases(context, choiceTypeBuilder.build(), choiceNode);
1085 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1087 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1088 * The package names for the builder is created as concatenation of the module package and names of all parents
1089 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1090 * and <i>choice</i> type
1093 * current module context
1094 * @param refChoiceType
1095 * type which represents superior <i>case</i>
1097 * choice case node which is mapped to generated type
1098 * @throws IllegalArgumentException
1100 * <li>if <code>refChoiceType</code> equals null</li>
1101 * <li>if <code>caseNodes</code> equals null</li>
1104 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1105 final ChoiceSchemaNode choiceNode) {
1106 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1107 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1109 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1110 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1111 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1112 caseTypeBuilder.addImplementsType(refChoiceType);
1113 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1114 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1115 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1116 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1117 if (caseChildNodes != null) {
1118 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1120 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1121 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1123 if (parent instanceof AugmentationSchemaNode) {
1124 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1125 final SchemaPath targetPath = augSchema.getTargetPath();
1126 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1127 if (targetSchemaNode instanceof DataSchemaNode
1128 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1129 if (targetSchemaNode instanceof DerivableSchemaNode) {
1130 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1133 if (targetSchemaNode == null) {
1134 throw new IllegalStateException(
1135 "Failed to find target node from grouping for augmentation " + augSchema
1136 + " in module " + context.module().getName());
1139 parent = targetSchemaNode;
1142 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1143 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1144 if (childOfType == null) {
1145 childOfType = findGroupingByPath(parent.getPath());
1147 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1149 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1153 processUsesAugments(caseNode, context);
1158 * Generates list of generated types for all the cases of a choice which are
1159 * added to the choice through the augment.
1163 * @param basePackageName
1164 * string contains name of package to which augment belongs. If
1165 * an augmented choice is from an other package (pcg1) than an
1166 * augmenting choice (pcg2) then case's of the augmenting choice
1167 * will belong to pcg2.
1169 * Type which represents target choice
1171 * node which represents target choice
1172 * @param augmentedNodes
1173 * set of choice case nodes for which is checked if are/aren't
1174 * added to choice through augmentation
1175 * @throws IllegalArgumentException
1177 * <li>if <code>basePackageName</code> is null</li>
1178 * <li>if <code>targetType</code> is null</li>
1179 * <li>if <code>augmentedNodes</code> is null</li>
1182 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1183 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1184 final DataNodeContainer usesNodeParent) {
1185 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1186 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1188 for (final DataSchemaNode caseNode : augmentedNodes) {
1189 if (caseNode != null) {
1190 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1191 caseTypeBuilder.addImplementsType(targetType);
1194 final SchemaPath nodeSp = targetNode.getPath();
1195 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1197 GeneratedTypeBuilder childOfType = null;
1198 if (parent instanceof Module) {
1199 childOfType = moduleContext(((Module) parent).getQNameModule()).getModuleNode();
1200 } else if (parent instanceof CaseSchemaNode) {
1201 childOfType = findCaseByPath(parent.getPath());
1202 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1203 childOfType = findChildNodeByPath(parent.getPath());
1204 } else if (parent instanceof GroupingDefinition) {
1205 childOfType = findGroupingByPath(parent.getPath());
1208 if (childOfType == null) {
1209 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1212 CaseSchemaNode node = null;
1213 final String caseLocalName = caseNode.getQName().getLocalName();
1214 if (caseNode instanceof CaseSchemaNode) {
1215 node = (CaseSchemaNode) caseNode;
1216 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1217 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1218 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1219 if (dataSchemaNode instanceof ChoiceSchemaNode
1220 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1221 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1226 node = findNamedCase(targetNode, caseLocalName);
1228 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1229 if (childNodes != null) {
1230 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1232 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1233 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1238 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1239 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1240 return cases.isEmpty() ? null : cases.get(0);
1243 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1244 // New parser with encapsulated type
1245 if (leaf.getPath().equals(type.getPath())) {
1249 // Embedded type definition with new parser. Also takes care of the old parser with bits
1250 if (leaf.getPath().equals(type.getPath().getParent())) {
1257 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1258 final List<PatternConstraint> patternConstraints) {
1259 if (!patternConstraints.isEmpty()) {
1260 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1261 .append(BindingMapping.getPropertyName(leafName).toUpperCase());
1262 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1263 typeProvider.resolveRegExpressions(patternConstraints));
1268 * Converts <code>leaf</code> to the getter method which is added to
1269 * <code>typeBuilder</code>.
1271 * @param typeBuilder
1272 * generated type builder to which is added getter method as
1273 * <code>leaf</code> mapping
1275 * leaf schema node which is mapped as getter method which is
1276 * added to <code>typeBuilder</code>
1278 * Module in which type was defined
1279 * @return boolean value
1281 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1283 * <li>true - in other cases</li>
1286 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1287 final ModuleContext context) {
1288 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1292 final Module parentModule = findParentModule(schemaContext, leaf);
1293 Type returnType = null;
1295 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1296 if (isInnerType(leaf, typeDef)) {
1297 if (typeDef instanceof EnumTypeDefinition) {
1298 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1299 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1300 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1301 typeBuilder, context);
1302 if (enumBuilder != null) {
1303 returnType = enumBuilder.toInstance(typeBuilder);
1305 typeProvider.putReferencedType(leaf.getPath(), returnType);
1306 } else if (typeDef instanceof UnionTypeDefinition) {
1307 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1309 if (genTOBuilder != null) {
1310 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1311 // Store the inner type within the union so that we can find the reference for it
1312 context.addInnerTypedefType(typeDef.getPath(), returnType);
1314 } else if (typeDef instanceof BitsTypeDefinition) {
1315 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1317 if (genTOBuilder != null) {
1318 returnType = genTOBuilder.build();
1321 // It is constrained version of already declared type (inner declared type exists,
1322 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1323 // In order to get proper class we need to look up closest derived type
1324 // and apply restrictions from leaf type
1325 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1326 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1328 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1331 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1332 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1333 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1336 if (returnType == null) {
1340 if (typeDef instanceof EnumTypeDefinition) {
1341 typeProvider.putReferencedType(leaf.getPath(), returnType);
1344 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1345 processContextRefExtension(leaf, getter, parentModule);
1349 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1350 // Returns DerivedType in case of new parser.
1351 final TypeDefinition<?> baseType = typeDef.getBaseType();
1352 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1355 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1356 final Module module) {
1357 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1358 final QName nodeType = node.getNodeType();
1359 if ("context-reference".equals(nodeType.getLocalName())) {
1360 final String nodeParam = node.getNodeParameter();
1361 IdentitySchemaNode identity = null;
1362 String basePackageName = null;
1363 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1364 final Iterator<String> iterator = splittedElement.iterator();
1365 final int length = Iterables.size(splittedElement);
1367 identity = findIdentityByName(module.getIdentities(), iterator.next());
1368 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1369 } else if (length == 2) {
1370 final String prefix = iterator.next();
1371 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1372 if (dependentModule == null) {
1373 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1376 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1377 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1379 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1382 if (identity == null) {
1383 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1387 final AnnotationTypeBuilder rc = getter.addAnnotation(JavaTypeName.create(RoutingContext.class));
1388 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1389 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1390 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1395 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1396 for (final IdentitySchemaNode id : identities) {
1397 if (id.getQName().getLocalName().equals(name)) {
1404 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1405 for (final ModuleImport imp : imports) {
1406 if (imp.getPrefix().equals(prefix)) {
1407 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1413 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1414 final boolean isReadOnly) {
1415 if (leaf != null && toBuilder != null) {
1417 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1418 if (typeDef instanceof UnionTypeDefinition) {
1419 // GeneratedType for this type definition should have be already created
1420 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1421 returnType = mc.getTypedefs().get(typeDef.getPath());
1422 if (returnType == null) {
1423 // This may still be an inner type, try to find it
1424 returnType = mc.getInnerType(typeDef.getPath());
1426 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1427 // Annonymous enumeration (already generated, since it is inherited via uses).
1428 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1429 QName qname = originalLeaf.getQName();
1430 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1432 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1434 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1440 * Converts <code>leaf</code> schema node to property of generated TO
1444 * generated TO builder to which is <code>leaf</code> added as
1447 * leaf schema node which is added to <code>toBuilder</code> as
1452 * boolean value which says if leaf property is|isn't read only
1453 * @return boolean value
1455 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1456 * name equals null or if leaf is added by <i>uses</i>.</li>
1457 * <li>true - other cases</li>
1460 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1461 final Type returnType, final boolean isReadOnly) {
1462 if (returnType == null) {
1465 final String leafName = leaf.getQName().getLocalName();
1466 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1467 propBuilder.setReadOnly(isReadOnly);
1468 propBuilder.setReturnType(returnType);
1469 addComment(propBuilder, leaf);
1471 toBuilder.addEqualsIdentity(propBuilder);
1472 toBuilder.addHashIdentity(propBuilder);
1473 toBuilder.addToStringProperty(propBuilder);
1478 * Converts <code>node</code> leaf list schema node to getter method of
1479 * <code>typeBuilder</code>.
1481 * @param typeBuilder
1482 * generated type builder to which is <code>node</code> added as
1485 * leaf list schema node which is added to
1486 * <code>typeBuilder</code> as getter method
1487 * @param module module
1488 * @return boolean value
1490 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1491 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1492 * <li>false - other cases</li>
1495 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1496 final ModuleContext context) {
1497 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1501 final QName nodeName = node.getQName();
1503 final TypeDefinition<?> typeDef = node.getType();
1504 final Module parentModule = findParentModule(schemaContext, node);
1506 Type returnType = null;
1507 if (typeDef.getBaseType() == null) {
1508 if (typeDef instanceof EnumTypeDefinition) {
1509 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1510 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1511 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1512 typeBuilder, context);
1513 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1514 typeProvider.putReferencedType(node.getPath(), returnType);
1515 } else if (typeDef instanceof UnionTypeDefinition) {
1516 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1517 node, parentModule);
1518 if (genTOBuilder != null) {
1519 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1521 } else if (typeDef instanceof BitsTypeDefinition) {
1522 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1523 node, parentModule);
1524 returnType = genTOBuilder.build();
1526 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1527 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1528 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1531 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1532 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1533 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1536 final ParameterizedType listType = Types.listTypeFor(returnType);
1537 constructGetter(typeBuilder, listType, node);
1541 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1542 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1543 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1545 addCodegenInformation(returnType, parentModule, typeDef);
1546 returnType.setSchemaPath(typeDef.getPath());
1547 returnType.setModuleName(parentModule.getName());
1549 genTOBuilder.setTypedef(true);
1550 genTOBuilder.setIsUnion(true);
1551 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1555 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1558 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1559 method.setReturnType(returnType);
1560 method.addParameter(Types.STRING, "defaultValue");
1561 method.setAccessModifier(AccessModifier.PUBLIC);
1562 method.setStatic(true);
1564 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1565 if (types == null) {
1566 typeProvider.getAdditionalTypes().put(parentModule,
1567 Sets.newHashSet(unionBuilder.build()));
1569 types.add(unionBuilder.build());
1571 return returnType.build();
1574 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1575 final GeneratedTypeBuilder typeBuilder) {
1576 final StringBuilder sb = new StringBuilder();
1578 // Append enclosing path hierarchy without dots
1579 // TODO: JavaTypeName could be giving us a Stream<String> or similar, but there is no sense in generalizing
1580 // unless there is another caller.
1581 Optional<JavaTypeName> outerClass = genTOBuilder.getIdentifier().immediatelyEnclosingClass();
1582 if (outerClass.isPresent()) {
1583 final Deque<String> enclosingPath = new ArrayDeque<>();
1585 final JavaTypeName outerName = outerClass.get();
1586 enclosingPath.push(outerName.simpleName());
1587 outerClass = outerName.immediatelyEnclosingClass();
1588 } while (outerClass.isPresent());
1590 while (!enclosingPath.isEmpty()) {
1591 sb.append(enclosingPath.pop());
1595 sb.append(genTOBuilder.getName()).append("Builder");
1596 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1597 JavaTypeName.create(typeBuilder.getPackageName(), sb.toString()));
1598 unionBuilder.setIsUnionBuilder(true);
1599 return unionBuilder;
1602 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1603 final SchemaNode schemaNode) {
1604 return addDefaultInterfaceDefinition(context, schemaNode, null);
1607 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1608 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1609 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1610 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1615 * Instantiates generated type builder with <code>packageName</code> and
1616 * <code>schemaNode</code>.
1618 * The new builder always implements
1619 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1620 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1621 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1623 * If <code>schemaNode</code> is instance of
1624 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1625 * DataNodeContainer} it can also implement nodes which are specified in
1628 * @param packageName
1629 * string with the name of the package to which
1630 * <code>schemaNode</code> belongs.
1632 * schema node for which is created generated type builder
1634 * parent type (can be null)
1635 * @return generated type builder <code>schemaNode</code>
1637 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1638 final Type parent, final ModuleContext context) {
1639 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1640 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1641 if (parent == null) {
1642 it.addImplementsType(DATA_OBJECT);
1644 it.addImplementsType(BindingTypes.childOf(parent));
1646 if (!(schemaNode instanceof GroupingDefinition)) {
1647 it.addImplementsType(augmentable(it));
1650 if (schemaNode instanceof DataNodeContainer) {
1651 groupingsToGenTypes(context, ((DataNodeContainer) schemaNode).getGroupings());
1652 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1659 * Wraps the calling of the same overloaded method.
1661 * @param packageName
1662 * string with the package name to which returning generated type
1665 * schema node which provide data about the schema node name
1666 * @return generated type builder for <code>schemaNode</code>
1668 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1669 final String prefix) {
1670 return addRawInterfaceDefinition(
1671 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1672 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1676 * Returns reference to generated type builder for specified
1677 * <code>schemaNode</code> with <code>packageName</code>.
1679 * Firstly the generated type builder is searched in
1680 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1681 * found it is created and added to <code>genTypeBuilders</code>.
1683 * @param packageName
1684 * string with the package name to which returning generated type
1687 * schema node which provide data about the schema node name
1689 * return type name prefix
1690 * @return generated type builder for <code>schemaNode</code>
1691 * @throws IllegalArgumentException
1693 * <li>if <code>schemaNode</code> is null</li>
1694 * <li>if <code>packageName</code> is null</li>
1695 * <li>if QName of schema node is null</li>
1696 * <li>if schemaNode name is null</li>
1700 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1701 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1702 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1703 final String schemaNodeName = schemaNode.getQName().getLocalName();
1704 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1706 // FIXME: Validation of name conflict
1707 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1708 final Module module = findParentModule(schemaContext, schemaNode);
1709 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1711 addCodegenInformation(newType, module, schemaNode);
1712 newType.setSchemaPath(schemaNode.getPath());
1713 newType.setModuleName(module.getName());
1715 final String packageName = identifier.packageName();
1716 final String simpleName = identifier.simpleName();
1717 if (!genTypeBuilders.containsKey(packageName)) {
1718 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1719 builders.put(simpleName, newType);
1720 genTypeBuilders.put(packageName, builders);
1722 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1723 if (!builders.containsKey(simpleName)) {
1724 builders.put(simpleName, newType);
1731 * Creates the name of the getter method name from <code>localName</code>.
1734 * string with the name of the getter method
1737 * @return string with the name of the getter method for
1738 * <code>methodName</code> in JAVA method format
1740 public static String getterMethodName(final String localName, final Type returnType) {
1741 final StringBuilder method = new StringBuilder();
1742 if (BOOLEAN.equals(returnType)) {
1743 method.append("is");
1745 method.append("get");
1747 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1748 method.append(name);
1749 return method.toString();
1753 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1755 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1756 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1758 * @param interfaceBuilder generated type builder for which the getter method should be created
1759 * @param returnType type which represents the return type of the getter method
1760 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1761 * @param comment string with comment for the getter method
1762 * @param status status from yang file, for deprecated annotation
1763 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1765 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1766 final SchemaNode node) {
1767 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1768 getterMethodName(node.getQName().getLocalName(), returnType));
1769 getMethod.setReturnType(returnType);
1771 if (node.getStatus() == Status.DEPRECATED) {
1772 getMethod.addAnnotation("java.lang", "Deprecated");
1774 addComment(getMethod, node);
1780 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1781 * or to <code>genTOBuilder</code> as property.
1783 * @param basePackageName
1784 * string contains the module package name
1786 * data schema node which should be added as getter method to
1787 * <code>typeBuilder</code> or as a property to
1788 * <code>genTOBuilder</code> if is part of the list key
1789 * @param typeBuilder
1790 * generated type builder for the list schema node
1791 * @param genTOBuilder
1792 * generated TO builder for the list keys
1794 * list of string which contains names of the list keys
1797 * @throws IllegalArgumentException
1799 * <li>if <code>schemaNode</code> equals null</li>
1800 * <li>if <code>typeBuilder</code> equals null</li>
1803 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1804 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1805 final List<String> listKeys) {
1806 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1807 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1809 if (schemaNode instanceof LeafSchemaNode) {
1810 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1811 final String leafName = leaf.getQName().getLocalName();
1812 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1813 if (listKeys.contains(leafName)) {
1815 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1817 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1820 } else if (!schemaNode.isAddedByUses()) {
1821 if (schemaNode instanceof LeafListSchemaNode) {
1822 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1823 } else if (schemaNode instanceof ContainerSchemaNode) {
1824 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1825 } else if (schemaNode instanceof ChoiceSchemaNode) {
1826 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1827 } else if (schemaNode instanceof ListSchemaNode) {
1828 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1833 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1834 final GeneratedTOBuilder genTOBuilder) {
1835 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1837 if (genTOBuilder != null) {
1838 final GeneratedTransferObject genTO = genTOBuilder.build();
1840 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1841 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1842 getMethod.setReturnType(genTO);
1843 getMethod.setComment("Returns Primary Key of Yang List Type");
1844 context.addGeneratedTOBuilder(genTOBuilder);
1849 * Selects the names of the list keys from <code>list</code> and returns
1850 * them as the list of the strings
1853 * of string with names of the list keys
1854 * @return list of string which represents names of the list keys. If the
1855 * <code>list</code> contains no keys then the empty list is
1858 private static List<String> listKeys(final ListSchemaNode list) {
1859 final List<String> listKeys = new ArrayList<>();
1861 final List<QName> keyDefinition = list.getKeyDefinition();
1862 if (keyDefinition != null) {
1863 for (final QName keyDef : keyDefinition) {
1864 listKeys.add(keyDef.getLocalName());
1871 * Generates for the <code>list</code> which contains any list keys special
1872 * generated TO builder.
1874 * @param packageName
1875 * string with package name to which the list belongs
1877 * list schema node which is source of data about the list name
1878 * @return generated TO builder which represents the keys of the
1879 * <code>list</code> or null if <code>list</code> is null or list of
1880 * key definitions is null or empty.
1882 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1883 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1884 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1885 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1886 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1892 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1894 * If more then one generated TO builder is created for enclosing then all
1895 * of the generated TO builders are added to <code>typeBuilder</code> as
1896 * enclosing transfer objects.
1899 * type definition which can be of type <code>UnionType</code> or
1900 * <code>BitsTypeDefinition</code>
1901 * @param typeBuilder
1902 * generated type builder to which is added generated TO created
1903 * from <code>typeDef</code>
1905 * string with name for generated TO builder
1906 * @param parentModule
1908 * @return generated TO builder for <code>typeDef</code>
1910 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1911 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1912 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1913 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1916 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1917 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1918 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1919 for (final GeneratedTOBuilder genTOBuilder : types) {
1920 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1923 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1924 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1925 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1926 resultTOBuilder.addHashIdentity(genPropBuilder);
1927 resultTOBuilder.addToStringProperty(genPropBuilder);
1928 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1929 return resultTOBuilder;
1933 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1934 * also added to <code>typeBuilder</code> as enclosing transfer object.
1936 * If more then one generated TO builder is created for enclosing then all
1937 * of the generated TO builders are added to <code>typeBuilder</code> as
1938 * enclosing transfer objects.
1941 * type definition which can be of type <code>UnionType</code> or
1942 * <code>BitsTypeDefinition</code>
1943 * @param typeBuilder
1944 * generated type builder to which is added generated TO created
1945 * from <code>typeDef</code>
1947 * string with name for generated TO builder
1948 * @param parentModule
1950 * @return generated TO builder for <code>typeDef</code>
1952 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1953 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1954 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1955 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1956 typeDef, parentModule.getName());
1957 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1958 return genTOBuilder;
1962 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1963 final List<GeneratedTOBuilder> genTOBuilders) {
1964 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1965 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1967 return genTOBuilders.get(0);
1971 * Adds the implemented types to type builder.
1973 * The method passes through the list of <i>uses</i> in
1974 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1975 * generated type from {@link ModuleContext#groupings
1976 * allGroupings} which is added as <i>implements type</i> to
1977 * <code>builder</code>
1979 * @param dataNodeContainer
1980 * element which contains the list of used YANG groupings
1982 * builder to which are added implemented types according to
1983 * <code>dataNodeContainer</code>
1984 * @return generated type builder with all implemented types
1986 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1987 final GeneratedTypeBuilder builder) {
1988 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1989 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1990 if (genType == null) {
1991 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1992 + builder.getName());
1995 builder.addImplementsType(genType);
2000 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2001 for (final ModuleContext ctx : genCtx.values()) {
2002 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2003 if (result != null) {
2010 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2011 for (final ModuleContext ctx : genCtx.values()) {
2012 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2013 if (result != null) {
2020 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2021 for (final ModuleContext ctx : genCtx.values()) {
2022 final GeneratedTypeBuilder result = ctx.getCase(path);
2023 if (result != null) {
2030 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2031 if (status == Status.DEPRECATED) {
2032 builder.addAnnotation("java.lang", "Deprecated");