2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
23 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
24 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
25 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.base.Splitter;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Sets;
33 import java.util.AbstractMap.SimpleImmutableEntry;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Comparator;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
41 import java.util.Optional;
43 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
44 import org.opendaylight.mdsal.binding.model.api.Constant;
45 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
46 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
47 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
48 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
49 import org.opendaylight.mdsal.binding.model.api.Restrictions;
50 import org.opendaylight.mdsal.binding.model.api.Type;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
53 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
54 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
55 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
59 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
60 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
61 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
62 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
63 import org.opendaylight.mdsal.binding.model.util.Types;
64 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
65 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
66 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
67 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
68 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
69 import org.opendaylight.yangtools.yang.binding.BindingMapping;
70 import org.opendaylight.yangtools.yang.binding.DataContainer;
71 import org.opendaylight.yangtools.yang.binding.RpcService;
72 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.QNameModule;
75 import org.opendaylight.yangtools.yang.common.RpcResult;
76 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
81 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
84 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
85 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
91 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
92 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
96 import org.opendaylight.yangtools.yang.model.api.Status;
97 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.UsesNode;
100 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
103 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
105 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
106 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
107 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
111 abstract class AbstractTypeGenerator {
112 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
113 private static final Splitter COLON_SPLITTER = Splitter.on(':');
116 * Comparator based on augment target path.
118 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
119 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
120 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
122 while (thisIt.hasNext()) {
123 if (!otherIt.hasNext()) {
127 final int comp = thisIt.next().compareTo(otherIt.next());
133 return otherIt.hasNext() ? -1 : 0;
137 * Constant with the concrete name of identifier.
139 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
142 * Constant with the concrete name of namespace.
144 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
146 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
149 * Outer key represents the package name. Outer value represents map of all
150 * builders in the same package. Inner key represents the schema node name
151 * (in JAVA class/interface name format). Inner value represents instance of
152 * builder for schema node specified in key part.
154 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
157 * Provide methods for converting YANG types to JAVA types.
159 private final AbstractTypeProvider typeProvider;
162 * Holds reference to schema context to resolve data of augmented element
163 * when creating augmentation builder
165 private final SchemaContext schemaContext;
167 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
168 this.schemaContext = requireNonNull(context);
169 this.typeProvider = requireNonNull(typeProvider);
171 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
172 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
173 for (final Module contextModule : contextModules) {
174 contexts.add(moduleToGenTypes(contextModule));
177 contexts.forEach(this::allAugmentsToGenTypes);
180 final Collection<ModuleContext> moduleContexts() {
181 return genCtx.values();
184 final ModuleContext moduleContext(final QNameModule module) {
185 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
188 final AbstractTypeProvider typeProvider() {
192 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
194 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
196 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
197 Set<? extends SchemaNode> nodes);
199 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
201 private ModuleContext moduleToGenTypes(final Module module) {
202 final ModuleContext context = new ModuleContext(module);
203 genCtx.put(module.getQNameModule(), context);
204 allTypeDefinitionsToGenTypes(context);
205 groupingsToGenTypes(context, module.getGroupings());
206 rpcMethodsToGenType(context);
207 allIdentitiesToGenTypes(context);
208 notificationsToGenType(context);
210 if (!module.getChildNodes().isEmpty()) {
211 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
212 context.addModuleNode(moduleType);
213 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
219 * Converts all extended type definitions of module to the list of
220 * <code>Type</code> objects.
223 * module from which is obtained set of type definitions
224 * @throws IllegalArgumentException
226 * <li>if module is null</li>
227 * <li>if name of module is null</li>
229 * @throws IllegalStateException
230 * if set of type definitions from module is null
232 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
233 final Module module = context.module();
234 checkArgument(module.getName() != null, "Module name cannot be NULL.");
235 final DataNodeIterator it = new DataNodeIterator(module);
236 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
237 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
239 for (final TypeDefinition<?> typedef : typeDefinitions) {
240 if (typedef != null) {
241 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
243 context.addTypedefType(typedef.getPath(), type);
244 context.addTypeToSchema(type,typedef);
250 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final GeneratedTypeBuilder childOf,
251 final DataSchemaNode node) {
252 if (node.isAugmenting() || node.isAddedByUses()) {
255 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
256 annotateDeprecatedIfNecessary(node.getStatus(), genType);
258 final Module module = context.module();
259 genType.setModuleName(module.getName());
260 addCodegenInformation(genType, module, node);
261 genType.setSchemaPath(node.getPath());
262 if (node instanceof DataNodeContainer) {
263 context.addChildNodeType(node, genType);
264 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
265 processUsesAugments((DataNodeContainer) node, context);
270 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
271 final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
272 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
273 if (genType != null) {
274 constructGetter(parent, genType, node);
275 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
279 private void listToGenType(final ModuleContext context,
280 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
281 final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
282 if (genType != null) {
283 constructGetter(parent, Types.listTypeFor(genType), node);
285 final List<String> listKeys = listKeys(node);
286 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
287 if (genTOBuilder != null) {
288 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
289 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
290 genTOBuilder.addImplementsType(identifierMarker);
291 genType.addImplementsType(identifiableMarker);
294 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
295 if (!schemaNode.isAugmenting()) {
296 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
301 if (genTOBuilder != null) {
302 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
303 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
304 genTOBuilder.setSUID(prop);
307 typeBuildersToGenTypes(context, genType, genTOBuilder);
311 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
312 for (final UsesNode usesNode : node.getUses()) {
313 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
314 usesAugmentationToGenTypes(context, augment, usesNode, node);
315 processUsesAugments(augment, context);
321 * Converts all <b>augmentation</b> of the module to the list
322 * <code>Type</code> objects.
325 * module from which is obtained list of all augmentation objects
326 * to iterate over them
327 * @throws IllegalArgumentException
329 * <li>if the module is null</li>
330 * <li>if the name of module is null</li>
332 * @throws IllegalStateException
333 * if set of augmentations from module is null
335 private void allAugmentsToGenTypes(final ModuleContext context) {
336 final Module module = context.module();
337 checkArgument(module != null, "Module reference cannot be NULL.");
338 checkArgument(module.getName() != null, "Module name cannot be NULL.");
339 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
341 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
342 augmentationToGenTypes(context, augment);
347 * Returns list of <code>AugmentationSchema</code> objects. The objects are
348 * sorted according to the length of their target path from the shortest to
352 * module from which is obtained list of all augmentation objects
353 * @return list of sorted <code>AugmentationSchema</code> objects obtained
354 * from <code>module</code>
355 * @throws IllegalArgumentException
357 * @throws IllegalStateException
358 * if set of module augmentations is null
360 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
361 checkArgument(module != null, "Module reference cannot be NULL.");
362 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
364 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
365 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
366 sortedAugmentations.sort(AUGMENT_COMP);
368 return sortedAugmentations;
372 * Create GeneratedTypeBuilder object from module argument.
375 * Module object from which builder will be created
376 * @return <code>GeneratedTypeBuilder</code> which is internal
377 * representation of the module
378 * @throws IllegalArgumentException
381 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
382 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
383 final Module module = context.module();
384 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
385 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
387 addCodegenInformation(moduleDataTypeBuilder, module);
388 return moduleDataTypeBuilder;
392 * Converts all <b>RPCs</b> input and output substatements of the module
393 * to the list of <code>Type</code> objects. In addition are to containers
394 * and lists which belong to input or output also part of returning list.
397 * module from which is obtained set of all rpc objects to
399 * @throws IllegalArgumentException
401 * <li>if the module is null</li>
402 * <li>if the name of module is null</li>
404 * @throws IllegalStateException
405 * if set of rpcs from module is null
407 private void rpcMethodsToGenType(final ModuleContext context) {
408 final Module module = context.module();
409 checkArgument(module.getName() != null, "Module name cannot be NULL.");
410 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
411 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
412 if (rpcDefinitions.isEmpty()) {
416 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
417 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
419 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
421 for (final RpcDefinition rpc : rpcDefinitions) {
423 final String rpcName = BindingMapping.getClassName(rpc.getQName());
424 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
425 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
427 // Do not refer to annotation class, as it may not be available at runtime
428 method.addAnnotation("javax.annotation", "CheckReturnValue");
429 addComment(method, rpc);
431 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
432 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
433 Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class),
434 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
438 context.addTopLevelNodeType(interfaceBuilder);
441 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
442 final ContainerSchemaNode schema) {
443 processUsesAugments(schema, context);
444 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
445 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
447 addImplementedInterfaceFromUses(schema, outType);
448 outType.addImplementsType(DATA_OBJECT);
449 outType.addImplementsType(augmentable(outType));
450 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
451 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
452 context.addChildNodeType(schema, outType);
453 return outType.build();
457 * Converts all <b>notifications</b> of the module to the list of
458 * <code>Type</code> objects. In addition are to this list added containers
459 * and lists which are part of this notification.
462 * module from which is obtained set of all notification objects
463 * to iterate over them
464 * @throws IllegalArgumentException
466 * <li>if the module equals null</li>
467 * <li>if the name of module equals null</li>
469 * @throws IllegalStateException
470 * if set of notifications from module is null
472 private void notificationsToGenType(final ModuleContext context) {
473 final Module module = context.module();
474 checkArgument(module.getName() != null, "Module name cannot be NULL.");
475 final Set<NotificationDefinition> notifications = module.getNotifications();
476 if (notifications.isEmpty()) {
480 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
481 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
483 for (final NotificationDefinition notification : notifications) {
484 if (notification != null) {
485 processUsesAugments(notification, context);
487 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
488 context.modulePackageName(), notification, null, context);
489 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
490 notificationInterface.addImplementsType(NOTIFICATION);
491 context.addChildNodeType(notification, notificationInterface);
493 // Notification object
494 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
495 notification.getChildNodes());
497 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
498 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
499 .setReturnType(Types.primitiveVoidType()), notification);
503 addCodegenInformation(listenerInterface, module, "notifications", notifications);
504 context.addTopLevelNodeType(listenerInterface);
508 * Converts all <b>identities</b> of the module to the list of
509 * <code>Type</code> objects.
512 * module from which is obtained set of all identity objects to
514 * @param schemaContext
515 * schema context only used as input parameter for method
516 * {@link BindingGeneratorImpl#identityToGenType}
519 private void allIdentitiesToGenTypes(final ModuleContext context) {
520 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
522 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
523 for (final IdentitySchemaNode identity : schemaIdentities) {
524 identityToGenType(context, identity);
530 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
531 * created transport object builder. If identity contains base identity then
532 * reference to base identity is added to superior identity as its extend.
533 * If identity doesn't contain base identity then only reference to abstract
534 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
535 * BaseIdentity} is added
539 * @param basePackageName
540 * string contains the module package name
542 * IdentitySchemaNode which contains data about identity
544 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
545 if (identity == null) {
548 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
549 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
550 BindingMapping.getClassName(identity.getQName())));
551 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
552 if (baseIdentities.isEmpty()) {
553 final GeneratedTOBuilder gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(BaseIdentity.class));
554 newType.addImplementsType(gto.build());
556 for (IdentitySchemaNode baseIdentity : baseIdentities) {
557 final QName qname = baseIdentity.getQName();
558 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
559 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
560 newType.addImplementsType(gto);
564 final Module module = context.module();
565 addCodegenInformation(newType, module, identity);
566 newType.setModuleName(module.getName());
567 newType.setSchemaPath(identity.getPath());
569 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
570 identity.getQName().getLocalName());
572 context.addIdentityType(identity.getQName(), newType);
575 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
576 final JavaTypeName yangModuleInfo, final String localName) {
577 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
578 new SimpleImmutableEntry<>(yangModuleInfo, localName));
582 * Converts all <b>groupings</b> of the module to the list of
583 * <code>Type</code> objects. Firstly are groupings sorted according mutual
584 * dependencies. At least dependent (independent) groupings are in the list
585 * saved at first positions. For every grouping the record is added to map
586 * {@link ModuleContext#groupings allGroupings}
591 * collection of groupings from which types will be generated
594 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
595 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
596 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
597 // node of grouping is resolved to the method.
598 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
599 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
600 context.addGroupingType(grouping.getPath(), genType);
601 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
602 groupingsToGenTypes(context, grouping.getGroupings());
603 processUsesAugments(grouping, context);
608 * Adds enumeration builder created from <code>enumTypeDef</code> to
609 * <code>typeBuilder</code>.
611 * Each <code>enumTypeDef</code> item is added to builder with its name and
615 * EnumTypeDefinition contains enum data
617 * string contains name which will be assigned to enumeration
620 * GeneratedTypeBuilder to which will be enum builder assigned
622 * Module in which type should be generated
623 * @return enumeration builder which contains data from
624 * <code>enumTypeDef</code>
626 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
627 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
628 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
629 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
630 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
631 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
632 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
639 * Generates type builder for <code>module</code>.
642 * Module which is source of package name for generated type
645 * string which is added to the module class name representation
647 * @return instance of GeneratedTypeBuilder which represents
648 * <code>module</code>.
649 * @throws IllegalArgumentException
650 * if <code>module</code> is null
652 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
653 final Module module = context.module();
654 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
655 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
656 JavaTypeName.create(context.modulePackageName(), moduleName));
658 moduleBuilder.setModuleName(moduleName);
659 addCodegenInformation(moduleBuilder, module);
660 return moduleBuilder;
664 * Converts <code>augSchema</code> to list of <code>Type</code> which
665 * contains generated type for augmentation. In addition there are also
666 * generated types for all containers, list and choices which are child of
667 * <code>augSchema</code> node or a generated types for cases are added if
668 * augmented node is choice.
670 * @param augmentPackageName
671 * string with the name of the package to which the augmentation
674 * AugmentationSchema which is contains data about augmentation
675 * (target path, childs...)
678 * @throws IllegalArgumentException
680 * <li>if <code>augmentPackageName</code> equals null</li>
681 * <li>if <code>augSchema</code> equals null</li>
683 * @throws IllegalStateException
684 * if augment target path is null
686 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
687 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
688 checkState(augSchema.getTargetPath() != null,
689 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
691 processUsesAugments(augSchema, context);
692 final SchemaPath targetPath = augSchema.getTargetPath();
693 SchemaNode targetSchemaNode = null;
695 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
696 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
697 if (targetSchemaNode instanceof DerivableSchemaNode) {
698 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
700 if (targetSchemaNode == null) {
701 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
702 + " in module " + context.module().getName());
705 if (targetSchemaNode == null) {
706 throw new IllegalArgumentException("augment target not found: " + targetPath);
709 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
710 if (targetTypeBuilder == null) {
711 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
713 if (targetTypeBuilder == null) {
714 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
717 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
718 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
719 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
722 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
723 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
727 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
728 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
729 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
730 checkState(augSchema.getTargetPath() != null,
731 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
733 processUsesAugments(augSchema, context);
734 final SchemaPath targetPath = augSchema.getTargetPath();
735 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
736 if (targetSchemaNode == null) {
737 throw new IllegalArgumentException("augment target not found: " + targetPath);
740 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
741 if (targetTypeBuilder == null) {
742 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
744 if (targetTypeBuilder == null) {
745 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
748 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
749 if (usesNodeParent instanceof SchemaNode) {
750 addRawAugmentGenTypeDefinition(context,
751 packageNameForAugmentedGeneratedType(context.modulePackageName(),
752 ((SchemaNode) usesNodeParent).getPath()),
753 targetTypeBuilder.build(), augSchema);
755 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
758 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
759 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
764 * Convenient method to find node added by uses statement.
768 * @param parentUsesNode
769 * parent of uses node
770 * @return node from its original location in grouping
772 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
773 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
775 if (!(targetGrouping instanceof GroupingDefinition)) {
776 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
779 SchemaNode result = targetGrouping;
780 for (final QName node : targetPath.getPathFromRoot()) {
781 if (result instanceof DataNodeContainer) {
782 final QName resultNode = node.withModule(result.getQName().getModule());
783 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
784 } else if (result instanceof ChoiceSchemaNode) {
785 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
788 if (result == null) {
792 if (result instanceof DerivableSchemaNode) {
793 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
794 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
795 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
796 result = originalNode.get();
800 if (result instanceof DataSchemaNode) {
801 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
802 if (resultDataSchemaNode.isAddedByUses()) {
803 // The original node is required, but we have only the copy of
804 // the original node.
805 // Maybe this indicates a bug in Yang parser.
806 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
809 return resultDataSchemaNode;
812 throw new IllegalStateException(
813 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
818 * Returns a generated type builder for an augmentation.
820 * The name of the type builder is equal to the name of augmented node with
821 * serial number as suffix.
825 * @param augmentPackageName
826 * string with contains the package name to which the augment
828 * @param basePackageName
829 * string with the package name to which the augmented node
831 * @param targetTypeRef
834 * augmentation schema which contains data about the child nodes
835 * and uses of augment
836 * @return generated type builder for augment
838 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
839 final String augmentPackageName, final Type targetTypeRef,
840 final AugmentationSchemaNode augSchema) {
841 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
842 if (augmentBuilders == null) {
843 augmentBuilders = new HashMap<>();
844 genTypeBuilders.put(augmentPackageName, augmentBuilders);
846 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
849 if (augIdentifier != null) {
850 augTypeName = BindingMapping.getClassName(augIdentifier);
852 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
855 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
856 JavaTypeName.create(augmentPackageName, augTypeName));
858 augTypeBuilder.addImplementsType(DATA_OBJECT);
859 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
860 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
861 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
863 augSchemaNodeToMethods(context,augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
864 augmentBuilders.put(augTypeName, augTypeBuilder);
866 if (!augSchema.getChildNodes().isEmpty()) {
867 context.addTypeToAugmentation(augTypeBuilder, augSchema);
870 context.addAugmentType(augTypeBuilder);
871 return augTypeBuilder;
874 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
875 final AugmentationSchemaNode augSchema) {
876 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
881 * @param unknownSchemaNodes
882 * @return nodeParameter of UnknownSchemaNode
884 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
885 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
886 final QName nodeType = unknownSchemaNode.getNodeType();
887 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
888 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
889 return unknownSchemaNode.getNodeParameter();
896 * Returns first unique name for the augment generated type builder. The
897 * generated type builder name for augment consists from name of augmented
898 * node and serial number of its augmentation.
901 * map of builders which were created in the package to which the
902 * augmentation belongs
904 * string with name of augmented node
905 * @return string with unique name for augmentation builder
907 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
909 if (builders != null) {
910 while (builders.containsKey(genTypeName + index)) {
914 return genTypeName + index;
918 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
919 * node for which <code>typeBuilder</code> was created.
921 * The subnodes aren't mapped to the methods if they are part of grouping or
922 * augment (in this case are already part of them).
927 * generated type builder which represents any node. The subnodes
928 * of this node are added to the <code>typeBuilder</code> as
929 * methods. The subnode can be of type leaf, leaf-list, list,
934 * set of data schema nodes which are the children of the node
935 * for which <code>typeBuilder</code> was created
936 * @return generated type builder which is the same builder as input
937 * parameter. The getter methods (representing child nodes) could be
940 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
941 final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
942 if (schemaNodes != null && parent != null) {
943 for (final DataSchemaNode schemaNode : schemaNodes) {
944 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
945 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
953 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
954 * node for which <code>typeBuilder</code> was created.
959 * generated type builder which represents any node. The subnodes
960 * of this node are added to the <code>typeBuilder</code> as
961 * methods. The subnode can be of type leaf, leaf-list, list,
966 * set of data schema nodes which are the children of the node
967 * for which <code>typeBuilder</code> was created
968 * @return generated type builder which is the same object as the input
969 * parameter <code>typeBuilder</code>. The getter method could be
972 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
973 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
974 final Iterable<DataSchemaNode> schemaNodes) {
975 if (schemaNodes != null && typeBuilder != null) {
976 for (final DataSchemaNode schemaNode : schemaNodes) {
977 if (!schemaNode.isAugmenting()) {
978 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
986 * Adds to <code>typeBuilder</code> a method which is derived from
987 * <code>schemaNode</code>.
990 * data schema node which is added to <code>typeBuilder</code> as
993 * generated type builder to which is <code>schemaNode</code>
1000 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1001 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf) {
1002 if (node != null && typeBuilder != null) {
1003 if (node instanceof LeafSchemaNode) {
1004 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1005 } else if (node instanceof LeafListSchemaNode) {
1006 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1007 } else if (node instanceof ContainerSchemaNode) {
1008 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1009 } else if (node instanceof ListSchemaNode) {
1010 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1011 } else if (node instanceof ChoiceSchemaNode) {
1012 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1014 // TODO: anyxml not yet supported
1015 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1016 typeBuilder.getFullyQualifiedName());
1022 * Converts <code>choiceNode</code> to the list of generated types for
1023 * choice and its cases.
1025 * The package names for choice and for its cases are created as
1026 * concatenation of the module package (<code>basePackageName</code>) and
1027 * names of all parents node.
1031 * @param basePackageName
1032 * string with the module package name
1036 * choice node which is mapped to generated type. Also child
1037 * nodes - cases are mapped to generated types.
1038 * @throws IllegalArgumentException
1040 * <li>if <code>basePackageName</code> is null</li>
1041 * <li>if <code>choiceNode</code> is null</li>
1044 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1045 final ChoiceSchemaNode choiceNode) {
1046 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1048 if (!choiceNode.isAddedByUses()) {
1049 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1050 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1051 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1052 constructGetter(parent, choiceTypeBuilder, choiceNode);
1053 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1054 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1055 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1056 generateTypesFromChoiceCases(context, choiceTypeBuilder.build(), choiceNode);
1061 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1063 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1064 * The package names for the builder is created as concatenation of the module package and names of all parents
1065 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1066 * and <i>choice</i> type
1069 * current module context
1070 * @param refChoiceType
1071 * type which represents superior <i>case</i>
1073 * choice case node which is mapped to generated type
1074 * @throws IllegalArgumentException
1076 * <li>if <code>refChoiceType</code> equals null</li>
1077 * <li>if <code>caseNodes</code> equals null</li>
1080 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1081 final ChoiceSchemaNode choiceNode) {
1082 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1083 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1085 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1086 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1087 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1088 caseTypeBuilder.addImplementsType(refChoiceType);
1089 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1090 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1091 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1092 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1093 if (caseChildNodes != null) {
1094 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1096 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1097 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1099 if (parent instanceof AugmentationSchemaNode) {
1100 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1101 final SchemaPath targetPath = augSchema.getTargetPath();
1102 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1103 if (targetSchemaNode instanceof DataSchemaNode
1104 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1105 if (targetSchemaNode instanceof DerivableSchemaNode) {
1106 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1109 if (targetSchemaNode == null) {
1110 throw new IllegalStateException(
1111 "Failed to find target node from grouping for augmentation " + augSchema
1112 + " in module " + context.module().getName());
1115 parent = targetSchemaNode;
1118 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1119 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1120 if (childOfType == null) {
1121 childOfType = findGroupingByPath(parent.getPath());
1123 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1125 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1129 processUsesAugments(caseNode, context);
1134 * Generates list of generated types for all the cases of a choice which are
1135 * added to the choice through the augment.
1139 * @param basePackageName
1140 * string contains name of package to which augment belongs. If
1141 * an augmented choice is from an other package (pcg1) than an
1142 * augmenting choice (pcg2) then case's of the augmenting choice
1143 * will belong to pcg2.
1145 * Type which represents target choice
1147 * node which represents target choice
1148 * @param augmentedNodes
1149 * set of choice case nodes for which is checked if are/aren't
1150 * added to choice through augmentation
1151 * @throws IllegalArgumentException
1153 * <li>if <code>basePackageName</code> is null</li>
1154 * <li>if <code>targetType</code> is null</li>
1155 * <li>if <code>augmentedNodes</code> is null</li>
1158 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1159 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1160 final DataNodeContainer usesNodeParent) {
1161 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1162 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1164 for (final DataSchemaNode caseNode : augmentedNodes) {
1165 if (caseNode != null) {
1166 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1167 caseTypeBuilder.addImplementsType(targetType);
1170 final SchemaPath nodeSp = targetNode.getPath();
1171 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1173 GeneratedTypeBuilder childOfType = null;
1174 if (parent instanceof Module) {
1175 childOfType = moduleContext(((Module) parent).getQNameModule()).getModuleNode();
1176 } else if (parent instanceof CaseSchemaNode) {
1177 childOfType = findCaseByPath(parent.getPath());
1178 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1179 childOfType = findChildNodeByPath(parent.getPath());
1180 } else if (parent instanceof GroupingDefinition) {
1181 childOfType = findGroupingByPath(parent.getPath());
1184 if (childOfType == null) {
1185 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1188 CaseSchemaNode node = null;
1189 final String caseLocalName = caseNode.getQName().getLocalName();
1190 if (caseNode instanceof CaseSchemaNode) {
1191 node = (CaseSchemaNode) caseNode;
1192 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1193 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1194 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1195 if (dataSchemaNode instanceof ChoiceSchemaNode
1196 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1197 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1202 node = findNamedCase(targetNode, caseLocalName);
1204 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1205 if (childNodes != null) {
1206 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1208 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1209 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1214 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1215 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1216 return cases.isEmpty() ? null : cases.get(0);
1219 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1220 // New parser with encapsulated type
1221 if (leaf.getPath().equals(type.getPath())) {
1225 // Embedded type definition with new parser. Also takes care of the old parser with bits
1226 if (leaf.getPath().equals(type.getPath().getParent())) {
1233 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1234 final List<PatternConstraint> patternConstraints) {
1235 if (!patternConstraints.isEmpty()) {
1236 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1237 .append(BindingMapping.getPropertyName(leafName));
1238 typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1239 typeProvider.resolveRegExpressions(patternConstraints));
1244 * Converts <code>leaf</code> to the getter method which is added to
1245 * <code>typeBuilder</code>.
1247 * @param typeBuilder
1248 * generated type builder to which is added getter method as
1249 * <code>leaf</code> mapping
1251 * leaf schema node which is mapped as getter method which is
1252 * added to <code>typeBuilder</code>
1254 * Module in which type was defined
1255 * @return boolean value
1257 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1259 * <li>true - in other cases</li>
1262 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1263 final ModuleContext context) {
1264 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1268 final Module parentModule = findParentModule(schemaContext, leaf);
1269 Type returnType = null;
1271 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1272 if (isInnerType(leaf, typeDef)) {
1273 if (typeDef instanceof EnumTypeDefinition) {
1274 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1275 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1276 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1277 typeBuilder, context);
1278 if (enumBuilder != null) {
1279 returnType = enumBuilder.toInstance(typeBuilder);
1281 typeProvider.putReferencedType(leaf.getPath(), returnType);
1282 } else if (typeDef instanceof UnionTypeDefinition) {
1283 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1285 if (genTOBuilder != null) {
1286 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1287 // Store the inner type within the union so that we can find the reference for it
1288 context.addInnerTypedefType(typeDef.getPath(), returnType);
1290 } else if (typeDef instanceof BitsTypeDefinition) {
1291 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1293 if (genTOBuilder != null) {
1294 returnType = genTOBuilder.build();
1297 // It is constrained version of already declared type (inner declared type exists,
1298 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1299 // In order to get proper class we need to look up closest derived type
1300 // and apply restrictions from leaf type
1301 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1302 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1304 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1307 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1308 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1309 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1312 if (returnType == null) {
1316 if (typeDef instanceof EnumTypeDefinition) {
1317 typeProvider.putReferencedType(leaf.getPath(), returnType);
1320 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1321 processContextRefExtension(leaf, getter, parentModule);
1325 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1326 // Returns DerivedType in case of new parser.
1327 final TypeDefinition<?> baseType = typeDef.getBaseType();
1328 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1331 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1332 final Module module) {
1333 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1334 final QName nodeType = node.getNodeType();
1335 if ("context-reference".equals(nodeType.getLocalName())) {
1336 final String nodeParam = node.getNodeParameter();
1337 IdentitySchemaNode identity = null;
1338 String basePackageName = null;
1339 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1340 final Iterator<String> iterator = splittedElement.iterator();
1341 final int length = Iterables.size(splittedElement);
1343 identity = findIdentityByName(module.getIdentities(), iterator.next());
1344 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1345 } else if (length == 2) {
1346 final String prefix = iterator.next();
1347 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1348 if (dependentModule == null) {
1349 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1352 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1353 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1355 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1358 if (identity == null) {
1359 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1363 final AnnotationTypeBuilder rc = getter.addAnnotation(JavaTypeName.create(RoutingContext.class));
1364 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1365 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1366 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1371 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1372 for (final IdentitySchemaNode id : identities) {
1373 if (id.getQName().getLocalName().equals(name)) {
1380 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1381 for (final ModuleImport imp : imports) {
1382 if (imp.getPrefix().equals(prefix)) {
1383 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1389 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1390 final boolean isReadOnly) {
1391 if (leaf != null && toBuilder != null) {
1393 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1394 if (typeDef instanceof UnionTypeDefinition) {
1395 // GeneratedType for this type definition should have be already created
1396 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1397 returnType = mc.getTypedefs().get(typeDef.getPath());
1398 if (returnType == null) {
1399 // This may still be an inner type, try to find it
1400 returnType = mc.getInnerType(typeDef.getPath());
1402 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1403 // Annonymous enumeration (already generated, since it is inherited via uses).
1404 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1405 QName qname = originalLeaf.getQName();
1406 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1408 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1410 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1416 * Converts <code>leaf</code> schema node to property of generated TO
1420 * generated TO builder to which is <code>leaf</code> added as
1423 * leaf schema node which is added to <code>toBuilder</code> as
1428 * boolean value which says if leaf property is|isn't read only
1429 * @return boolean value
1431 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1432 * name equals null or if leaf is added by <i>uses</i>.</li>
1433 * <li>true - other cases</li>
1436 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1437 final Type returnType, final boolean isReadOnly) {
1438 if (returnType == null) {
1441 final String leafName = leaf.getQName().getLocalName();
1442 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1443 propBuilder.setReadOnly(isReadOnly);
1444 propBuilder.setReturnType(returnType);
1445 addComment(propBuilder, leaf);
1447 toBuilder.addEqualsIdentity(propBuilder);
1448 toBuilder.addHashIdentity(propBuilder);
1449 toBuilder.addToStringProperty(propBuilder);
1454 * Converts <code>node</code> leaf list schema node to getter method of
1455 * <code>typeBuilder</code>.
1457 * @param typeBuilder
1458 * generated type builder to which is <code>node</code> added as
1461 * leaf list schema node which is added to
1462 * <code>typeBuilder</code> as getter method
1463 * @param module module
1464 * @return boolean value
1466 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1467 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1468 * <li>false - other cases</li>
1471 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1472 final ModuleContext context) {
1473 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1477 final QName nodeName = node.getQName();
1479 final TypeDefinition<?> typeDef = node.getType();
1480 final Module parentModule = findParentModule(schemaContext, node);
1482 Type returnType = null;
1483 if (typeDef.getBaseType() == null) {
1484 if (typeDef instanceof EnumTypeDefinition) {
1485 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1486 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1487 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1488 typeBuilder, context);
1489 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1490 typeProvider.putReferencedType(node.getPath(), returnType);
1491 } else if (typeDef instanceof UnionTypeDefinition) {
1492 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1493 node, parentModule);
1494 if (genTOBuilder != null) {
1495 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1497 } else if (typeDef instanceof BitsTypeDefinition) {
1498 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1499 node, parentModule);
1500 returnType = genTOBuilder.build();
1502 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1503 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1504 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1507 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1508 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1509 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1512 final ParameterizedType listType = Types.listTypeFor(returnType);
1513 constructGetter(typeBuilder, listType, node);
1517 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1518 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1519 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1521 addCodegenInformation(returnType, parentModule, typeDef);
1522 returnType.setSchemaPath(typeDef.getPath());
1523 returnType.setModuleName(parentModule.getName());
1525 genTOBuilder.setTypedef(true);
1526 genTOBuilder.setIsUnion(true);
1527 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1531 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1534 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1535 method.setReturnType(returnType);
1536 method.addParameter(Types.STRING, "defaultValue");
1537 method.setAccessModifier(AccessModifier.PUBLIC);
1538 method.setStatic(true);
1540 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1541 if (types == null) {
1542 typeProvider.getAdditionalTypes().put(parentModule,
1543 Sets.newHashSet(unionBuilder.build()));
1545 types.add(unionBuilder.build());
1547 return returnType.build();
1550 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1551 final GeneratedTypeBuilder typeBuilder) {
1552 // Append enclosing path hierarchy without dots
1553 final StringBuilder sb = new StringBuilder();
1554 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1555 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1556 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1557 unionBuilder.setIsUnionBuilder(true);
1558 return unionBuilder;
1561 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1562 final SchemaNode schemaNode) {
1563 return addDefaultInterfaceDefinition(context, schemaNode, null);
1566 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1567 final SchemaNode schemaNode, final GeneratedTypeBuilder childOf) {
1568 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1569 return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1574 * Instantiates generated type builder with <code>packageName</code> and
1575 * <code>schemaNode</code>.
1577 * The new builder always implements
1578 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1579 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1580 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1582 * If <code>schemaNode</code> is instance of
1583 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1584 * DataNodeContainer} it can also implement nodes which are specified in
1587 * @param packageName
1588 * string with the name of the package to which
1589 * <code>schemaNode</code> belongs.
1591 * schema node for which is created generated type builder
1593 * parent type (can be null)
1594 * @return generated type builder <code>schemaNode</code>
1596 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1597 final Type parent, final ModuleContext context) {
1598 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1599 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1600 if (parent == null) {
1601 it.addImplementsType(DATA_OBJECT);
1603 it.addImplementsType(BindingTypes.childOf(parent));
1605 if (!(schemaNode instanceof GroupingDefinition)) {
1606 it.addImplementsType(augmentable(it));
1609 if (schemaNode instanceof DataNodeContainer) {
1610 groupingsToGenTypes(context, ((DataNodeContainer) schemaNode).getGroupings());
1611 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1618 * Wraps the calling of the same overloaded method.
1620 * @param packageName
1621 * string with the package name to which returning generated type
1624 * schema node which provide data about the schema node name
1625 * @return generated type builder for <code>schemaNode</code>
1627 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1628 final String prefix) {
1629 return addRawInterfaceDefinition(
1630 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1631 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1635 * Returns reference to generated type builder for specified
1636 * <code>schemaNode</code> with <code>packageName</code>.
1638 * Firstly the generated type builder is searched in
1639 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1640 * found it is created and added to <code>genTypeBuilders</code>.
1642 * @param packageName
1643 * string with the package name to which returning generated type
1646 * schema node which provide data about the schema node name
1648 * return type name prefix
1649 * @return generated type builder for <code>schemaNode</code>
1650 * @throws IllegalArgumentException
1652 * <li>if <code>schemaNode</code> is null</li>
1653 * <li>if <code>packageName</code> is null</li>
1654 * <li>if QName of schema node is null</li>
1655 * <li>if schemaNode name is null</li>
1659 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1660 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1661 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1662 final String schemaNodeName = schemaNode.getQName().getLocalName();
1663 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1665 // FIXME: Validation of name conflict
1666 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1667 final Module module = findParentModule(schemaContext, schemaNode);
1668 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1669 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1671 addCodegenInformation(newType, module, schemaNode);
1672 newType.setSchemaPath(schemaNode.getPath());
1673 newType.setModuleName(module.getName());
1675 final String packageName = identifier.packageName();
1676 final String simpleName = identifier.simpleName();
1677 if (!genTypeBuilders.containsKey(packageName)) {
1678 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1679 builders.put(simpleName, newType);
1680 genTypeBuilders.put(packageName, builders);
1682 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1683 if (!builders.containsKey(simpleName)) {
1684 builders.put(simpleName, newType);
1691 * Creates the name of the getter method name from <code>localName</code>.
1694 * string with the name of the getter method
1697 * @return string with the name of the getter method for
1698 * <code>methodName</code> in JAVA method format
1700 public static String getterMethodName(final String localName, final Type returnType) {
1701 final StringBuilder method = new StringBuilder();
1702 if (BOOLEAN.equals(returnType)) {
1703 method.append("is");
1705 method.append("get");
1707 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1708 method.append(name);
1709 return method.toString();
1713 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1715 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1716 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1718 * @param interfaceBuilder generated type builder for which the getter method should be created
1719 * @param returnType type which represents the return type of the getter method
1720 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1721 * @param comment string with comment for the getter method
1722 * @param status status from yang file, for deprecated annotation
1723 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1725 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1726 final SchemaNode node) {
1727 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1728 getterMethodName(node.getQName().getLocalName(), returnType));
1729 getMethod.setReturnType(returnType);
1731 if (node.getStatus() == Status.DEPRECATED) {
1732 getMethod.addAnnotation("java.lang", "Deprecated");
1734 if (!returnType.getPackageName().isEmpty()) {
1735 // The return type has a package, so it's not a primitive type
1736 getMethod.addAnnotation("javax.annotation", "Nullable");
1738 addComment(getMethod, node);
1744 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1745 * or to <code>genTOBuilder</code> as property.
1747 * @param basePackageName
1748 * string contains the module package name
1750 * data schema node which should be added as getter method to
1751 * <code>typeBuilder</code> or as a property to
1752 * <code>genTOBuilder</code> if is part of the list key
1753 * @param typeBuilder
1754 * generated type builder for the list schema node
1755 * @param genTOBuilder
1756 * generated TO builder for the list keys
1758 * list of string which contains names of the list keys
1761 * @throws IllegalArgumentException
1763 * <li>if <code>schemaNode</code> equals null</li>
1764 * <li>if <code>typeBuilder</code> equals null</li>
1767 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1768 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1769 final List<String> listKeys) {
1770 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1771 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1773 if (schemaNode instanceof LeafSchemaNode) {
1774 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1775 final String leafName = leaf.getQName().getLocalName();
1776 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1777 if (listKeys.contains(leafName)) {
1779 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1781 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1784 } else if (!schemaNode.isAddedByUses()) {
1785 if (schemaNode instanceof LeafListSchemaNode) {
1786 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1787 } else if (schemaNode instanceof ContainerSchemaNode) {
1788 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1789 } else if (schemaNode instanceof ChoiceSchemaNode) {
1790 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1791 } else if (schemaNode instanceof ListSchemaNode) {
1792 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1797 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1798 final GeneratedTOBuilder genTOBuilder) {
1799 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1801 if (genTOBuilder != null) {
1802 final GeneratedTransferObject genTO = genTOBuilder.build();
1804 // Fake the 'getKey()' for items, this is equivalent to constructGetter()
1805 final MethodSignatureBuilder getMethod = typeBuilder.addMethod(getterMethodName("key", genTO));
1806 getMethod.setReturnType(genTO);
1807 getMethod.setComment("Returns Primary Key of Yang List Type");
1808 context.addGeneratedTOBuilder(genTOBuilder);
1813 * Selects the names of the list keys from <code>list</code> and returns
1814 * them as the list of the strings
1817 * of string with names of the list keys
1818 * @return list of string which represents names of the list keys. If the
1819 * <code>list</code> contains no keys then the empty list is
1822 private static List<String> listKeys(final ListSchemaNode list) {
1823 final List<String> listKeys = new ArrayList<>();
1825 final List<QName> keyDefinition = list.getKeyDefinition();
1826 if (keyDefinition != null) {
1827 for (final QName keyDef : keyDefinition) {
1828 listKeys.add(keyDef.getLocalName());
1835 * Generates for the <code>list</code> which contains any list keys special
1836 * generated TO builder.
1838 * @param packageName
1839 * string with package name to which the list belongs
1841 * list schema node which is source of data about the list name
1842 * @return generated TO builder which represents the keys of the
1843 * <code>list</code> or null if <code>list</code> is null or list of
1844 * key definitions is null or empty.
1846 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1847 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1848 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1849 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1850 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1856 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1858 * If more then one generated TO builder is created for enclosing then all
1859 * of the generated TO builders are added to <code>typeBuilder</code> as
1860 * enclosing transfer objects.
1863 * type definition which can be of type <code>UnionType</code> or
1864 * <code>BitsTypeDefinition</code>
1865 * @param typeBuilder
1866 * generated type builder to which is added generated TO created
1867 * from <code>typeDef</code>
1869 * string with name for generated TO builder
1870 * @param parentModule
1872 * @return generated TO builder for <code>typeDef</code>
1874 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1875 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1876 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1877 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1880 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1881 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1882 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1883 for (final GeneratedTOBuilder genTOBuilder : types) {
1884 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1887 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1888 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1889 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1890 resultTOBuilder.addHashIdentity(genPropBuilder);
1891 resultTOBuilder.addToStringProperty(genPropBuilder);
1892 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1893 return resultTOBuilder;
1897 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1898 * also added to <code>typeBuilder</code> as enclosing transfer object.
1900 * If more then one generated TO builder is created for enclosing then all
1901 * of the generated TO builders are added to <code>typeBuilder</code> as
1902 * enclosing transfer objects.
1905 * type definition which can be of type <code>UnionType</code> or
1906 * <code>BitsTypeDefinition</code>
1907 * @param typeBuilder
1908 * generated type builder to which is added generated TO created
1909 * from <code>typeDef</code>
1911 * string with name for generated TO builder
1912 * @param parentModule
1914 * @return generated TO builder for <code>typeDef</code>
1916 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1917 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1918 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1919 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1920 typeDef, parentModule.getName());
1921 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1922 return genTOBuilder;
1926 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1927 final List<GeneratedTOBuilder> genTOBuilders) {
1928 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1929 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1931 return genTOBuilders.get(0);
1935 * Adds the implemented types to type builder.
1937 * The method passes through the list of <i>uses</i> in
1938 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1939 * generated type from {@link ModuleContext#groupings
1940 * allGroupings} which is added as <i>implements type</i> to
1941 * <code>builder</code>
1943 * @param dataNodeContainer
1944 * element which contains the list of used YANG groupings
1946 * builder to which are added implemented types according to
1947 * <code>dataNodeContainer</code>
1948 * @return generated type builder with all implemented types
1950 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1951 final GeneratedTypeBuilder builder) {
1952 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1953 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1954 if (genType == null) {
1955 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1956 + builder.getName());
1959 builder.addImplementsType(genType);
1964 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1965 for (final ModuleContext ctx : genCtx.values()) {
1966 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1967 if (result != null) {
1974 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1975 for (final ModuleContext ctx : genCtx.values()) {
1976 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1977 if (result != null) {
1984 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1985 for (final ModuleContext ctx : genCtx.values()) {
1986 final GeneratedTypeBuilder result = ctx.getCase(path);
1987 if (result != null) {
1994 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
1995 if (status == Status.DEPRECATED) {
1996 builder.addAnnotation("java.lang", "Deprecated");