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.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
34 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
35 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
36 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
38 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
39 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
40 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
42 import com.google.common.base.Splitter;
43 import com.google.common.collect.Iterables;
44 import com.google.common.collect.Sets;
45 import java.util.AbstractMap.SimpleImmutableEntry;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Optional;
55 import org.eclipse.jdt.annotation.Nullable;
56 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
57 import org.opendaylight.mdsal.binding.model.api.Constant;
58 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
60 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
61 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
62 import org.opendaylight.mdsal.binding.model.api.Restrictions;
63 import org.opendaylight.mdsal.binding.model.api.Type;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
73 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
74 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
75 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
76 import org.opendaylight.mdsal.binding.model.util.Types;
77 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
78 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
79 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
80 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
81 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.common.QNameModule;
84 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
85 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
94 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
95 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
101 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
102 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
103 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
104 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
106 import org.opendaylight.yangtools.yang.model.api.Status;
107 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
108 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.UsesNode;
110 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
111 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
112 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
113 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
114 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
115 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
116 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
117 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
121 abstract class AbstractTypeGenerator {
122 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
123 private static final Splitter COLON_SPLITTER = Splitter.on(':');
124 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
125 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
126 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
129 * Comparator based on augment target path.
131 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
132 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
133 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
135 while (thisIt.hasNext()) {
136 if (!otherIt.hasNext()) {
140 final int comp = thisIt.next().compareTo(otherIt.next());
146 return otherIt.hasNext() ? -1 : 0;
150 * Constant with the concrete name of identifier.
152 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
155 * Constant with the concrete name of namespace.
157 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
159 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
162 * Outer key represents the package name. Outer value represents map of all
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder for schema node specified in key part.
167 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
170 * Provide methods for converting YANG types to JAVA types.
172 private final AbstractTypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element
176 * when creating augmentation builder
178 private final SchemaContext schemaContext;
181 * Holds renamed elements.
183 private final Map<SchemaNode, JavaTypeName> renames;
185 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
186 final Map<SchemaNode, JavaTypeName> renames) {
187 this.schemaContext = requireNonNull(context);
188 this.typeProvider = requireNonNull(typeProvider);
189 this.renames = requireNonNull(renames);
191 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
192 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
193 for (final Module contextModule : contextModules) {
194 contexts.add(moduleToGenTypes(contextModule));
197 contexts.forEach(this::allAugmentsToGenTypes);
200 final Collection<ModuleContext> moduleContexts() {
201 return genCtx.values();
204 final ModuleContext moduleContext(final QNameModule module) {
205 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
208 final AbstractTypeProvider typeProvider() {
212 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
214 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
216 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
217 Set<? extends SchemaNode> nodes);
219 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
221 private ModuleContext moduleToGenTypes(final Module module) {
222 final ModuleContext context = new ModuleContext(module);
223 genCtx.put(module.getQNameModule(), context);
224 allTypeDefinitionsToGenTypes(context);
225 groupingsToGenTypes(context, module.getGroupings());
226 rpcMethodsToGenType(context);
227 allIdentitiesToGenTypes(context);
228 notificationsToGenType(context);
230 if (!module.getChildNodes().isEmpty()) {
231 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
232 context.addModuleNode(moduleType);
233 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
239 * Converts all extended type definitions of module to the list of
240 * <code>Type</code> objects.
243 * module from which is obtained set of type definitions
244 * @throws IllegalArgumentException
246 * <li>if module is null</li>
247 * <li>if name of module is null</li>
249 * @throws IllegalStateException
250 * if set of type definitions from module is null
252 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
253 final Module module = context.module();
254 checkArgument(module.getName() != null, "Module name cannot be NULL.");
255 final DataNodeIterator it = new DataNodeIterator(module);
256 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
257 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
259 for (final TypeDefinition<?> typedef : typeDefinitions) {
260 if (typedef != null) {
261 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
263 context.addTypedefType(typedef, type);
264 context.addTypeToSchema(type,typedef);
270 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
271 final DataSchemaNode node) {
272 if (node.isAugmenting() || node.isAddedByUses()) {
275 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
276 annotateDeprecatedIfNecessary(node.getStatus(), genType);
278 final Module module = context.module();
279 genType.setModuleName(module.getName());
280 addCodegenInformation(genType, module, node);
281 genType.setSchemaPath(node.getPath());
282 if (node instanceof DataNodeContainer) {
283 context.addChildNodeType(node, genType);
284 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
285 processUsesAugments((DataNodeContainer) node, context);
290 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
291 final Type baseInterface, final ContainerSchemaNode node) {
292 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
293 if (genType != null) {
294 constructGetter(parent, genType, node);
295 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
296 actionsToGenType(context, genType, node, null);
300 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
301 final Type baseInterface, final ListSchemaNode node) {
302 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
303 if (genType != null) {
304 constructGetter(parent, listTypeFor(genType), node);
306 final List<String> listKeys = listKeys(node);
307 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
308 if (genTOBuilder != null) {
309 final Type identifierMarker = identifier(genType);
310 final Type identifiableMarker = identifiable(genTOBuilder);
311 genTOBuilder.addImplementsType(identifierMarker);
312 genType.addImplementsType(identifiableMarker);
315 actionsToGenType(context, genType, node, genTOBuilder);
317 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
318 if (!schemaNode.isAugmenting()) {
319 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
324 if (genTOBuilder != null) {
325 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
326 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
327 genTOBuilder.setSUID(prop);
330 typeBuildersToGenTypes(context, genType, genTOBuilder);
334 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
335 for (final UsesNode usesNode : node.getUses()) {
336 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
337 usesAugmentationToGenTypes(context, augment, usesNode, node);
338 processUsesAugments(augment, context);
344 * Converts all <b>augmentation</b> of the module to the list
345 * <code>Type</code> objects.
348 * module from which is obtained list of all augmentation objects
349 * to iterate over them
350 * @throws IllegalArgumentException
352 * <li>if the module is null</li>
353 * <li>if the name of module is null</li>
355 * @throws IllegalStateException
356 * if set of augmentations from module is null
358 private void allAugmentsToGenTypes(final ModuleContext context) {
359 final Module module = context.module();
360 checkArgument(module != null, "Module reference cannot be NULL.");
361 checkArgument(module.getName() != null, "Module name cannot be NULL.");
362 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
364 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
365 augmentationToGenTypes(context, augment);
370 * Returns list of <code>AugmentationSchema</code> objects. The objects are
371 * sorted according to the length of their target path from the shortest to
375 * module from which is obtained list of all augmentation objects
376 * @return list of sorted <code>AugmentationSchema</code> objects obtained
377 * from <code>module</code>
378 * @throws IllegalArgumentException
380 * @throws IllegalStateException
381 * if set of module augmentations is null
383 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
384 checkArgument(module != null, "Module reference cannot be NULL.");
385 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
387 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
388 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
389 sortedAugmentations.sort(AUGMENT_COMP);
391 return sortedAugmentations;
395 * Create GeneratedTypeBuilder object from module argument.
398 * Module object from which builder will be created
399 * @return <code>GeneratedTypeBuilder</code> which is internal
400 * representation of the module
401 * @throws IllegalArgumentException
404 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
405 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
406 final Module module = context.module();
407 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
408 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
410 addCodegenInformation(moduleDataTypeBuilder, module);
411 return moduleDataTypeBuilder;
414 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
415 final Type parent, final T parentSchema, final Type keyType) {
416 for (final ActionDefinition action : parentSchema.getActions()) {
417 final GeneratedType input;
418 final GeneratedType output;
419 if (action.isAddedByUses()) {
420 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
421 input = context.getChildNode(orig.getInput().getPath()).build();
422 output = context.getChildNode(orig.getOutput().getPath()).build();
424 input = actionContainer(context, RPC_INPUT, action.getInput());
425 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
428 if (!(parentSchema instanceof GroupingDefinition)) {
429 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
430 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
431 // and do not capture an actual instantiation.
432 final QName qname = action.getQName();
433 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
434 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
435 BindingMapping.getClassName(qname)));
436 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
437 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
439 annotateDeprecatedIfNecessary(action.getStatus(), builder);
440 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
441 : action(parent, input, output));
443 addCodegenInformation(builder, context.module(), action);
444 context.addChildNodeType(action, builder);
449 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
450 for (UsesNode uses : parent.getUses()) {
451 final GroupingDefinition grp = findUsedGrouping(uses);
452 final Optional<ActionDefinition> found = grp.getActions().stream()
453 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
454 if (found.isPresent()) {
455 final ActionDefinition result = found.get();
456 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
460 return Optional.empty();
463 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
464 final ContainerSchemaNode schema) {
465 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
466 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
467 return genType.build();
471 * Converts all <b>RPCs</b> input and output substatements of the module
472 * to the list of <code>Type</code> objects. In addition are to containers
473 * and lists which belong to input or output also part of returning list.
476 * module from which is obtained set of all rpc objects to
478 * @throws IllegalArgumentException
480 * <li>if the module is null</li>
481 * <li>if the name of module is null</li>
483 * @throws IllegalStateException
484 * if set of rpcs from module is null
486 private void rpcMethodsToGenType(final ModuleContext context) {
487 final Module module = context.module();
488 checkArgument(module.getName() != null, "Module name cannot be NULL.");
489 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
490 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
491 if (rpcDefinitions.isEmpty()) {
495 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
496 interfaceBuilder.addImplementsType(RPC_SERVICE);
498 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
500 for (final RpcDefinition rpc : rpcDefinitions) {
502 final String rpcName = BindingMapping.getClassName(rpc.getQName());
503 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
504 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
506 // Do not refer to annotation class, as it may not be available at runtime
507 method.addAnnotation("javax.annotation", "CheckReturnValue");
508 addComment(method, rpc);
510 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
511 method.setReturnType(listenableFutureTypeFor(
512 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
516 context.addTopLevelNodeType(interfaceBuilder);
519 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
520 final ContainerSchemaNode schema, final Type type) {
521 processUsesAugments(schema, context);
522 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
523 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
525 addImplementedInterfaceFromUses(schema, outType);
526 outType.addImplementsType(type);
527 outType.addImplementsType(augmentable(outType));
528 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
529 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
530 context.addChildNodeType(schema, outType);
531 return outType.build();
535 * Converts all <b>notifications</b> of the module to the list of
536 * <code>Type</code> objects. In addition are to this list added containers
537 * and lists which are part of this notification.
540 * module from which is obtained set of all notification objects
541 * to iterate over them
542 * @throws IllegalArgumentException
544 * <li>if the module equals null</li>
545 * <li>if the name of module equals null</li>
547 * @throws IllegalStateException
548 * if set of notifications from module is null
550 private void notificationsToGenType(final ModuleContext context) {
551 final Module module = context.module();
552 checkArgument(module.getName() != null, "Module name cannot be NULL.");
553 final Set<NotificationDefinition> notifications = module.getNotifications();
554 if (notifications.isEmpty()) {
558 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
559 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
561 for (final NotificationDefinition notification : notifications) {
562 if (notification != null) {
563 processUsesAugments(notification, context);
565 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
566 context.modulePackageName(), notification, DATA_OBJECT, context);
567 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
568 notificationInterface.addImplementsType(NOTIFICATION);
569 context.addChildNodeType(notification, notificationInterface);
571 // Notification object
572 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
573 notification.getChildNodes());
575 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
576 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
577 .setReturnType(Types.primitiveVoidType()), notification);
581 addCodegenInformation(listenerInterface, module, "notifications", notifications);
582 context.addTopLevelNodeType(listenerInterface);
586 * Converts all <b>identities</b> of the module to the list of
587 * <code>Type</code> objects.
590 * module from which is obtained set of all identity objects to
592 * @param schemaContext
593 * schema context only used as input parameter for method
594 * {@link BindingGeneratorImpl#identityToGenType}
597 private void allIdentitiesToGenTypes(final ModuleContext context) {
598 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
600 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
601 for (final IdentitySchemaNode identity : schemaIdentities) {
602 identityToGenType(context, identity);
608 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
609 * created transport object builder. If identity contains base identity then
610 * reference to base identity is added to superior identity as its extend.
611 * If identity doesn't contain base identity then only reference to abstract
612 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
613 * BaseIdentity} is added
617 * @param basePackageName
618 * string contains the module package name
620 * IdentitySchemaNode which contains data about identity
622 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
623 if (identity == null) {
627 JavaTypeName name = renames.get(identity);
629 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
630 BindingMapping.getClassName(identity.getQName()));
633 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
634 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
635 if (!baseIdentities.isEmpty()) {
636 for (IdentitySchemaNode baseIdentity : baseIdentities) {
637 JavaTypeName base = renames.get(baseIdentity);
639 final QName qname = baseIdentity.getQName();
640 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
641 BindingMapping.getClassName(qname));
644 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
645 newType.addImplementsType(gto);
648 newType.addImplementsType(BASE_IDENTITY);
651 final Module module = context.module();
652 addCodegenInformation(newType, module, identity);
653 newType.setModuleName(module.getName());
654 newType.setSchemaPath(identity.getPath());
656 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
657 identity.getQName().getLocalName());
659 context.addIdentityType(identity, newType);
662 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
663 final JavaTypeName yangModuleInfo, final String localName) {
664 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
665 new SimpleImmutableEntry<>(yangModuleInfo, localName));
669 * Converts all <b>groupings</b> of the module to the list of
670 * <code>Type</code> objects. Firstly are groupings sorted according mutual
671 * dependencies. At least dependent (independent) groupings are in the list
672 * saved at first positions. For every grouping the record is added to map
673 * {@link ModuleContext#groupings allGroupings}
678 * collection of groupings from which types will be generated
681 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
682 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
683 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
684 // node of grouping is resolved to the method.
685 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
686 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
687 context.addGroupingType(grouping, genType);
688 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
689 groupingsToGenTypes(context, grouping.getGroupings());
690 processUsesAugments(grouping, context);
691 actionsToGenType(context, genType, grouping, null);
696 * Adds enumeration builder created from <code>enumTypeDef</code> to
697 * <code>typeBuilder</code>.
699 * Each <code>enumTypeDef</code> item is added to builder with its name and
703 * EnumTypeDefinition contains enum data
705 * string contains name which will be assigned to enumeration
708 * GeneratedTypeBuilder to which will be enum builder assigned
710 * Module in which type should be generated
711 * @return enumeration builder which contains data from
712 * <code>enumTypeDef</code>
714 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
715 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
716 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
717 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
718 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
719 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
720 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
727 * Generates type builder for <code>module</code>.
730 * Module which is source of package name for generated type
733 * string which is added to the module class name representation
735 * @return instance of GeneratedTypeBuilder which represents
736 * <code>module</code>.
737 * @throws IllegalArgumentException
738 * if <code>module</code> is null
740 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
741 final Module module = context.module();
742 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
743 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
744 JavaTypeName.create(context.modulePackageName(), moduleName));
746 moduleBuilder.setModuleName(moduleName);
747 addCodegenInformation(moduleBuilder, module);
748 return moduleBuilder;
752 * Converts <code>augSchema</code> to list of <code>Type</code> which
753 * contains generated type for augmentation. In addition there are also
754 * generated types for all containers, list and choices which are child of
755 * <code>augSchema</code> node or a generated types for cases are added if
756 * augmented node is choice.
758 * @param augmentPackageName
759 * string with the name of the package to which the augmentation
762 * AugmentationSchema which is contains data about augmentation
763 * (target path, childs...)
766 * @throws IllegalArgumentException
768 * <li>if <code>augmentPackageName</code> equals null</li>
769 * <li>if <code>augSchema</code> equals null</li>
771 * @throws IllegalStateException
772 * if augment target path is null
774 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
775 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
776 checkState(augSchema.getTargetPath() != null,
777 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
779 processUsesAugments(augSchema, context);
780 final SchemaPath targetPath = augSchema.getTargetPath();
781 SchemaNode targetSchemaNode = null;
783 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
784 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
785 if (targetSchemaNode instanceof DerivableSchemaNode) {
786 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
788 if (targetSchemaNode == null) {
789 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
790 + " in module " + context.module().getName());
793 if (targetSchemaNode == null) {
794 throw new IllegalArgumentException("augment target not found: " + targetPath);
797 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
798 if (targetTypeBuilder == null) {
799 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
801 if (targetTypeBuilder == null) {
802 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
805 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
806 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
807 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
810 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
811 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
815 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
816 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
817 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
818 checkState(augSchema.getTargetPath() != null,
819 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
821 processUsesAugments(augSchema, context);
822 final SchemaPath targetPath = augSchema.getTargetPath();
823 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
824 if (targetSchemaNode == null) {
825 throw new IllegalArgumentException("augment target not found: " + targetPath);
828 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
829 if (targetTypeBuilder == null) {
830 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
832 if (targetTypeBuilder == null) {
833 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
836 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
837 if (usesNodeParent instanceof SchemaNode) {
838 addRawAugmentGenTypeDefinition(context,
839 packageNameForAugmentedGeneratedType(context.modulePackageName(),
840 ((SchemaNode) usesNodeParent).getPath()),
841 targetTypeBuilder.build(), augSchema);
843 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
846 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
847 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
851 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
852 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
854 if (targetGrouping instanceof GroupingDefinition) {
855 return (GroupingDefinition) targetGrouping;
858 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
862 * Convenient method to find node added by uses statement.
866 * @param parentUsesNode
867 * parent of uses node
868 * @return node from its original location in grouping
870 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
871 SchemaNode result = findUsedGrouping(parentUsesNode);
872 for (final QName node : targetPath.getPathFromRoot()) {
873 if (result instanceof DataNodeContainer) {
874 final QName resultNode = node.withModule(result.getQName().getModule());
875 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
876 } else if (result instanceof ChoiceSchemaNode) {
877 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
880 if (result == null) {
884 if (result instanceof DerivableSchemaNode) {
885 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
886 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
887 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
888 result = originalNode.get();
892 if (result instanceof DataSchemaNode) {
893 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
894 if (resultDataSchemaNode.isAddedByUses()) {
895 // The original node is required, but we have only the copy of
896 // the original node.
897 // Maybe this indicates a bug in Yang parser.
898 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
901 return resultDataSchemaNode;
904 throw new IllegalStateException(
905 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
910 * Returns a generated type builder for an augmentation.
912 * The name of the type builder is equal to the name of augmented node with
913 * serial number as suffix.
917 * @param augmentPackageName
918 * string with contains the package name to which the augment
920 * @param basePackageName
921 * string with the package name to which the augmented node
923 * @param targetTypeRef
926 * augmentation schema which contains data about the child nodes
927 * and uses of augment
928 * @return generated type builder for augment
930 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
931 final String augmentPackageName, final Type targetTypeRef,
932 final AugmentationSchemaNode augSchema) {
933 Map<String, GeneratedTypeBuilder> augmentBuilders =
934 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
935 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
938 if (augIdentifier != null) {
939 augTypeName = BindingMapping.getClassName(augIdentifier);
941 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
944 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
945 JavaTypeName.create(augmentPackageName, augTypeName));
947 augTypeBuilder.addImplementsType(DATA_OBJECT);
948 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
949 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
950 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
952 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
953 augmentBuilders.put(augTypeName, augTypeBuilder);
955 if (!augSchema.getChildNodes().isEmpty()) {
956 context.addTypeToAugmentation(augTypeBuilder, augSchema);
959 context.addAugmentType(augTypeBuilder);
960 return augTypeBuilder;
963 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
964 final AugmentationSchemaNode augSchema) {
965 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
970 * @param unknownSchemaNodes
971 * @return nodeParameter of UnknownSchemaNode
973 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
974 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
975 final QName nodeType = unknownSchemaNode.getNodeType();
976 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
977 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
978 return unknownSchemaNode.getNodeParameter();
985 * Returns first unique name for the augment generated type builder. The
986 * generated type builder name for augment consists from name of augmented
987 * node and serial number of its augmentation.
990 * map of builders which were created in the package to which the
991 * augmentation belongs
993 * string with name of augmented node
994 * @return string with unique name for augmentation builder
996 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
998 if (builders != null) {
999 while (builders.containsKey(genTypeName + index)) {
1003 return genTypeName + index;
1007 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1008 * node for which <code>typeBuilder</code> was created.
1010 * The subnodes aren't mapped to the methods if they are part of grouping or
1011 * augment (in this case are already part of them).
1016 * generated type builder which represents any node. The subnodes
1017 * of this node are added to the <code>typeBuilder</code> as
1018 * methods. The subnode can be of type leaf, leaf-list, list,
1019 * container, choice.
1022 * @param schemaNodes
1023 * set of data schema nodes which are the children of the node
1024 * for which <code>typeBuilder</code> was created
1025 * @return generated type builder which is the same builder as input
1026 * parameter. The getter methods (representing child nodes) could be
1029 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1030 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1031 if (schemaNodes != null && parent != null) {
1032 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1033 for (final DataSchemaNode schemaNode : schemaNodes) {
1034 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1035 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1043 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1044 * node for which <code>typeBuilder</code> was created.
1048 * @param typeBuilder
1049 * generated type builder which represents any node. The subnodes
1050 * of this node are added to the <code>typeBuilder</code> as
1051 * methods. The subnode can be of type leaf, leaf-list, list,
1052 * container, choice.
1055 * @param schemaNodes
1056 * set of data schema nodes which are the children of the node
1057 * for which <code>typeBuilder</code> was created
1058 * @return generated type builder which is the same object as the input
1059 * parameter <code>typeBuilder</code>. The getter method could be
1062 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1063 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1064 if (schemaNodes != null && typeBuilder != null) {
1065 final Type baseInterface = childOf(typeBuilder);
1066 for (final DataSchemaNode schemaNode : schemaNodes) {
1067 if (!schemaNode.isAugmenting()) {
1068 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1076 * Adds to <code>typeBuilder</code> a method which is derived from
1077 * <code>schemaNode</code>.
1080 * data schema node which is added to <code>typeBuilder</code> as
1082 * @param typeBuilder
1083 * generated type builder to which is <code>schemaNode</code>
1084 * added as a method.
1090 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1091 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1092 if (node != null && typeBuilder != null) {
1093 if (node instanceof LeafSchemaNode) {
1094 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1095 } else if (node instanceof LeafListSchemaNode) {
1096 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1097 } else if (node instanceof ContainerSchemaNode) {
1098 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1099 } else if (node instanceof ListSchemaNode) {
1100 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1101 } else if (node instanceof ChoiceSchemaNode) {
1102 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1104 // TODO: anyxml not yet supported
1105 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1106 typeBuilder.getFullyQualifiedName());
1112 * Converts <code>choiceNode</code> to the list of generated types for
1113 * choice and its cases.
1115 * The package names for choice and for its cases are created as
1116 * concatenation of the module package (<code>basePackageName</code>) and
1117 * names of all parents node.
1121 * @param basePackageName
1122 * string with the module package name
1126 * choice node which is mapped to generated type. Also child
1127 * nodes - cases are mapped to generated types.
1128 * @throws IllegalArgumentException
1130 * <li>if <code>basePackageName</code> is null</li>
1131 * <li>if <code>choiceNode</code> is null</li>
1134 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1135 final ChoiceSchemaNode choiceNode) {
1136 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1138 if (!choiceNode.isAddedByUses()) {
1139 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1140 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1141 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1142 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1143 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1144 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1146 final GeneratedType choiceType = choiceTypeBuilder.build();
1147 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1149 constructGetter(parent, choiceType, choiceNode);
1154 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1156 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1157 * The package names for the builder is created as concatenation of the module package and names of all parents
1158 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1159 * and <i>choice</i> type
1162 * current module context
1163 * @param refChoiceType
1164 * type which represents superior <i>case</i>
1166 * choice case node which is mapped to generated type
1167 * @throws IllegalArgumentException
1169 * <li>if <code>refChoiceType</code> equals null</li>
1170 * <li>if <code>caseNodes</code> equals null</li>
1173 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1174 final ChoiceSchemaNode choiceNode) {
1175 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1176 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1178 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1179 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1180 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1181 caseTypeBuilder.addImplementsType(refChoiceType);
1182 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1183 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1184 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1185 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1186 if (caseChildNodes != null) {
1187 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1189 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1190 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1192 if (parent instanceof AugmentationSchemaNode) {
1193 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1194 final SchemaPath targetPath = augSchema.getTargetPath();
1195 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1196 if (targetSchemaNode instanceof DataSchemaNode
1197 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1198 if (targetSchemaNode instanceof DerivableSchemaNode) {
1199 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1202 if (targetSchemaNode == null) {
1203 throw new IllegalStateException(
1204 "Failed to find target node from grouping for augmentation " + augSchema
1205 + " in module " + context.module().getName());
1208 parent = targetSchemaNode;
1211 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1212 Type childOfType = findChildNodeByPath(parent.getPath());
1213 if (childOfType == null) {
1214 childOfType = findGroupingByPath(parent.getPath());
1216 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1218 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1222 processUsesAugments(caseNode, context);
1227 * Generates list of generated types for all the cases of a choice which are
1228 * added to the choice through the augment.
1232 * @param basePackageName
1233 * string contains name of package to which augment belongs. If
1234 * an augmented choice is from an other package (pcg1) than an
1235 * augmenting choice (pcg2) then case's of the augmenting choice
1236 * will belong to pcg2.
1238 * Type which represents target choice
1240 * node which represents target choice
1241 * @param augmentedNodes
1242 * set of choice case nodes for which is checked if are/aren't
1243 * added to choice through augmentation
1244 * @throws IllegalArgumentException
1246 * <li>if <code>basePackageName</code> is null</li>
1247 * <li>if <code>targetType</code> is null</li>
1248 * <li>if <code>augmentedNodes</code> is null</li>
1251 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1252 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1253 final DataNodeContainer usesNodeParent) {
1254 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1255 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1257 for (final DataSchemaNode caseNode : augmentedNodes) {
1258 if (caseNode != null) {
1259 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1260 caseTypeBuilder.addImplementsType(targetType);
1262 CaseSchemaNode node = null;
1263 final String caseLocalName = caseNode.getQName().getLocalName();
1264 if (caseNode instanceof CaseSchemaNode) {
1265 node = (CaseSchemaNode) caseNode;
1266 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1267 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1268 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1269 if (dataSchemaNode instanceof ChoiceSchemaNode
1270 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1271 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1276 node = findNamedCase(targetNode, caseLocalName);
1278 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1279 if (childNodes != null) {
1280 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1282 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1283 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1288 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1289 final SchemaPath nodePath = targetNode.getPath();
1290 final SchemaPath parentSp = nodePath.getParent();
1291 if (parentSp.getParent() == null) {
1292 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1295 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1296 GeneratedTypeBuilder childOfType = null;
1297 if (parent instanceof CaseSchemaNode) {
1298 childOfType = findCaseByPath(parent.getPath());
1299 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1300 childOfType = findChildNodeByPath(parent.getPath());
1301 } else if (parent instanceof GroupingDefinition) {
1302 childOfType = findGroupingByPath(parent.getPath());
1305 if (childOfType == null) {
1306 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1312 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1313 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1314 return cases.isEmpty() ? null : cases.get(0);
1317 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1318 // New parser with encapsulated type
1319 if (leaf.getPath().equals(type.getPath())) {
1323 // Embedded type definition with new parser. Also takes care of the old parser with bits
1324 if (leaf.getPath().equals(type.getPath().getParent())) {
1331 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1332 final List<PatternConstraint> patternConstraints) {
1333 if (!patternConstraints.isEmpty()) {
1334 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1335 .append(BindingMapping.getPropertyName(leafName));
1336 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1337 typeProvider.resolveRegExpressions(patternConstraints));
1342 * Converts <code>leaf</code> to the getter method which is added to
1343 * <code>typeBuilder</code>.
1345 * @param typeBuilder
1346 * generated type builder to which is added getter method as
1347 * <code>leaf</code> mapping
1349 * leaf schema node which is mapped as getter method which is
1350 * added to <code>typeBuilder</code>
1352 * Module in which type was defined
1353 * @return boolean value
1355 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1357 * <li>true - in other cases</li>
1360 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1361 final ModuleContext context) {
1362 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1366 final Module parentModule = findParentModule(schemaContext, leaf);
1367 Type returnType = null;
1369 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1370 if (isInnerType(leaf, typeDef)) {
1371 if (typeDef instanceof EnumTypeDefinition) {
1372 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1373 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1374 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1375 typeBuilder, context);
1376 if (enumBuilder != null) {
1377 returnType = enumBuilder.toInstance(typeBuilder);
1379 typeProvider.putReferencedType(leaf.getPath(), returnType);
1380 } else if (typeDef instanceof UnionTypeDefinition) {
1381 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1383 if (genTOBuilder != null) {
1384 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1385 // Store the inner type within the union so that we can find the reference for it
1386 context.addInnerTypedefType(typeDef.getPath(), returnType);
1388 } else if (typeDef instanceof BitsTypeDefinition) {
1389 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1391 if (genTOBuilder != null) {
1392 returnType = genTOBuilder.build();
1395 // It is constrained version of already declared type (inner declared type exists,
1396 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1397 // In order to get proper class we need to look up closest derived type
1398 // and apply restrictions from leaf type
1399 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1400 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1402 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1405 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1406 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1407 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1410 if (returnType == null) {
1414 if (typeDef instanceof EnumTypeDefinition) {
1415 typeProvider.putReferencedType(leaf.getPath(), returnType);
1418 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1419 processContextRefExtension(leaf, getter, parentModule);
1423 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1424 // Returns DerivedType in case of new parser.
1425 final TypeDefinition<?> baseType = typeDef.getBaseType();
1426 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1429 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1430 final Module module) {
1431 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1432 final QName nodeType = node.getNodeType();
1433 if ("context-reference".equals(nodeType.getLocalName())) {
1434 final String nodeParam = node.getNodeParameter();
1435 IdentitySchemaNode identity = null;
1436 String basePackageName = null;
1437 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1438 final Iterator<String> iterator = splittedElement.iterator();
1439 final int length = Iterables.size(splittedElement);
1441 identity = findIdentityByName(module.getIdentities(), iterator.next());
1442 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1443 } else if (length == 2) {
1444 final String prefix = iterator.next();
1445 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1446 if (dependentModule == null) {
1447 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1450 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1451 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1453 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1456 if (identity == null) {
1457 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1461 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1462 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1463 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1464 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1469 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1470 for (final IdentitySchemaNode id : identities) {
1471 if (id.getQName().getLocalName().equals(name)) {
1478 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1479 for (final ModuleImport imp : imports) {
1480 if (imp.getPrefix().equals(prefix)) {
1481 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1487 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1488 final boolean isReadOnly) {
1489 if (leaf != null && toBuilder != null) {
1491 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1492 if (typeDef instanceof UnionTypeDefinition) {
1493 // GeneratedType for this type definition should have be already created
1494 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1495 returnType = mc.getTypedefs().get(typeDef.getPath());
1496 if (returnType == null) {
1497 // This may still be an inner type, try to find it
1498 returnType = mc.getInnerType(typeDef.getPath());
1500 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1501 // Annonymous enumeration (already generated, since it is inherited via uses).
1502 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1503 QName qname = originalLeaf.getQName();
1504 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1506 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1508 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1514 * Converts <code>leaf</code> schema node to property of generated TO
1518 * generated TO builder to which is <code>leaf</code> added as
1521 * leaf schema node which is added to <code>toBuilder</code> as
1526 * boolean value which says if leaf property is|isn't read only
1527 * @return boolean value
1529 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1530 * name equals null or if leaf is added by <i>uses</i>.</li>
1531 * <li>true - other cases</li>
1534 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1535 final Type returnType, final boolean isReadOnly) {
1536 if (returnType == null) {
1539 final String leafName = leaf.getQName().getLocalName();
1540 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1541 propBuilder.setReadOnly(isReadOnly);
1542 propBuilder.setReturnType(returnType);
1543 addComment(propBuilder, leaf);
1545 toBuilder.addEqualsIdentity(propBuilder);
1546 toBuilder.addHashIdentity(propBuilder);
1547 toBuilder.addToStringProperty(propBuilder);
1552 * Converts <code>node</code> leaf list schema node to getter method of
1553 * <code>typeBuilder</code>.
1555 * @param typeBuilder
1556 * generated type builder to which is <code>node</code> added as
1559 * leaf list schema node which is added to
1560 * <code>typeBuilder</code> as getter method
1561 * @param module module
1562 * @return boolean value
1564 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1565 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1566 * <li>false - other cases</li>
1569 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1570 final ModuleContext context) {
1571 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1575 final QName nodeName = node.getQName();
1577 final TypeDefinition<?> typeDef = node.getType();
1578 final Module parentModule = findParentModule(schemaContext, node);
1580 Type returnType = null;
1581 if (typeDef.getBaseType() == null) {
1582 if (typeDef instanceof EnumTypeDefinition) {
1583 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1584 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1585 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1586 typeBuilder, context);
1587 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1588 typeProvider.putReferencedType(node.getPath(), returnType);
1589 } else if (typeDef instanceof UnionTypeDefinition) {
1590 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1591 node, parentModule);
1592 if (genTOBuilder != null) {
1593 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1595 } else if (typeDef instanceof BitsTypeDefinition) {
1596 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1597 node, parentModule);
1598 returnType = genTOBuilder.build();
1600 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1601 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1602 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1605 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1606 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1607 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1610 final ParameterizedType listType = listTypeFor(returnType);
1611 constructGetter(typeBuilder, listType, node);
1615 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1616 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1617 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1619 addCodegenInformation(returnType, parentModule, typeDef);
1620 returnType.setSchemaPath(typeDef.getPath());
1621 returnType.setModuleName(parentModule.getName());
1623 genTOBuilder.setTypedef(true);
1624 genTOBuilder.setIsUnion(true);
1625 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1629 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1632 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1633 method.setReturnType(returnType);
1634 method.addParameter(Types.STRING, "defaultValue");
1635 method.setAccessModifier(AccessModifier.PUBLIC);
1636 method.setStatic(true);
1638 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1639 if (types == null) {
1640 typeProvider.getAdditionalTypes().put(parentModule,
1641 Sets.newHashSet(unionBuilder.build()));
1643 types.add(unionBuilder.build());
1645 return returnType.build();
1648 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1649 final GeneratedTypeBuilder typeBuilder) {
1650 // Append enclosing path hierarchy without dots
1651 final StringBuilder sb = new StringBuilder();
1652 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1653 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1654 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1655 unionBuilder.setIsUnionBuilder(true);
1656 return unionBuilder;
1659 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1660 final SchemaNode schemaNode) {
1661 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1664 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1665 final SchemaNode schemaNode, final Type baseInterface) {
1666 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1667 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1672 * Instantiates generated type builder with <code>packageName</code> and
1673 * <code>schemaNode</code>.
1675 * The new builder always implements
1676 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1677 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1678 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1680 * If <code>schemaNode</code> is instance of
1681 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1682 * DataNodeContainer} it can also implement nodes which are specified in
1685 * @param packageName
1686 * string with the name of the package to which
1687 * <code>schemaNode</code> belongs.
1689 * schema node for which is created generated type builder
1691 * parent type (can be null)
1692 * @return generated type builder <code>schemaNode</code>
1694 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1695 final Type baseInterface, final ModuleContext context) {
1696 JavaTypeName name = renames.get(schemaNode);
1698 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1701 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1703 it.addImplementsType(baseInterface);
1704 if (!(schemaNode instanceof GroupingDefinition)) {
1705 it.addImplementsType(augmentable(it));
1707 if (schemaNode instanceof DataNodeContainer) {
1708 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1709 groupingsToGenTypes(context, containerSchema.getGroupings());
1710 addImplementedInterfaceFromUses(containerSchema, it);
1717 * Wraps the calling of the same overloaded method.
1719 * @param packageName
1720 * string with the package name to which returning generated type
1723 * schema node which provide data about the schema node name
1724 * @return generated type builder for <code>schemaNode</code>
1726 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1727 final String prefix) {
1728 return addRawInterfaceDefinition(
1729 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1730 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1734 * Returns reference to generated type builder for specified
1735 * <code>schemaNode</code> with <code>packageName</code>.
1737 * Firstly the generated type builder is searched in
1738 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1739 * found it is created and added to <code>genTypeBuilders</code>.
1741 * @param packageName
1742 * string with the package name to which returning generated type
1745 * schema node which provide data about the schema node name
1747 * return type name prefix
1748 * @return generated type builder for <code>schemaNode</code>
1749 * @throws IllegalArgumentException
1751 * <li>if <code>schemaNode</code> is null</li>
1752 * <li>if <code>packageName</code> is null</li>
1753 * <li>if QName of schema node is null</li>
1754 * <li>if schemaNode name is null</li>
1758 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1759 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1760 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1761 final String schemaNodeName = schemaNode.getQName().getLocalName();
1762 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1764 // FIXME: Validation of name conflict
1765 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1766 final Module module = findParentModule(schemaContext, schemaNode);
1767 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1768 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1770 addCodegenInformation(newType, module, schemaNode);
1771 newType.setSchemaPath(schemaNode.getPath());
1772 newType.setModuleName(module.getName());
1774 final String packageName = identifier.packageName();
1775 final String simpleName = identifier.simpleName();
1776 if (!genTypeBuilders.containsKey(packageName)) {
1777 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1778 builders.put(simpleName, newType);
1779 genTypeBuilders.put(packageName, builders);
1781 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1782 if (!builders.containsKey(simpleName)) {
1783 builders.put(simpleName, newType);
1790 * Creates the name of the getter method name from <code>localName</code>.
1793 * string with the name of the getter method
1796 * @return string with the name of the getter method for
1797 * <code>methodName</code> in JAVA method format
1799 public static String getterMethodName(final String localName, final Type returnType) {
1800 final StringBuilder method = new StringBuilder();
1801 if (BOOLEAN.equals(returnType)) {
1802 method.append("is");
1804 method.append("get");
1806 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1807 method.append(name);
1808 return method.toString();
1812 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1814 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1815 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1817 * @param interfaceBuilder generated type builder for which the getter method should be created
1818 * @param returnType type which represents the return type of the getter method
1819 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1820 * @param comment string with comment for the getter method
1821 * @param status status from yang file, for deprecated annotation
1822 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1824 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1825 final SchemaNode node) {
1826 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1827 getterMethodName(node.getQName().getLocalName(), returnType));
1828 getMethod.setReturnType(returnType);
1830 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1831 if (!returnType.getPackageName().isEmpty()) {
1832 // The return type has a package, so it's not a primitive type
1833 getMethod.addAnnotation("javax.annotation", "Nullable");
1835 addComment(getMethod, node);
1841 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1842 * or to <code>genTOBuilder</code> as property.
1844 * @param basePackageName
1845 * string contains the module package name
1847 * data schema node which should be added as getter method to
1848 * <code>typeBuilder</code> or as a property to
1849 * <code>genTOBuilder</code> if is part of the list key
1850 * @param typeBuilder
1851 * generated type builder for the list schema node
1852 * @param genTOBuilder
1853 * generated TO builder for the list keys
1855 * list of string which contains names of the list keys
1858 * @throws IllegalArgumentException
1860 * <li>if <code>schemaNode</code> equals null</li>
1861 * <li>if <code>typeBuilder</code> equals null</li>
1864 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1865 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1866 final List<String> listKeys) {
1867 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1868 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1870 if (schemaNode instanceof LeafSchemaNode) {
1871 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1872 final String leafName = leaf.getQName().getLocalName();
1873 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1874 if (listKeys.contains(leafName)) {
1876 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1878 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1881 } else if (!schemaNode.isAddedByUses()) {
1882 if (schemaNode instanceof LeafListSchemaNode) {
1883 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1884 } else if (schemaNode instanceof ContainerSchemaNode) {
1885 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1886 (ContainerSchemaNode) schemaNode);
1887 } else if (schemaNode instanceof ChoiceSchemaNode) {
1888 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1889 } else if (schemaNode instanceof ListSchemaNode) {
1890 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1895 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1896 final GeneratedTOBuilder genTOBuilder) {
1897 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1899 if (genTOBuilder != null) {
1900 final GeneratedTransferObject genTO = genTOBuilder.build();
1901 // Add Identifiable.getKey() for items
1902 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1903 .addAnnotation(OVERRIDE_ANNOTATION);
1904 context.addGeneratedTOBuilder(genTOBuilder);
1909 * Selects the names of the list keys from <code>list</code> and returns
1910 * them as the list of the strings
1913 * of string with names of the list keys
1914 * @return list of string which represents names of the list keys. If the
1915 * <code>list</code> contains no keys then the empty list is
1918 private static List<String> listKeys(final ListSchemaNode list) {
1919 final List<String> listKeys = new ArrayList<>();
1921 final List<QName> keyDefinition = list.getKeyDefinition();
1922 if (keyDefinition != null) {
1923 for (final QName keyDef : keyDefinition) {
1924 listKeys.add(keyDef.getLocalName());
1931 * Generates for the <code>list</code> which contains any list keys special
1932 * generated TO builder.
1934 * @param packageName
1935 * string with package name to which the list belongs
1937 * list schema node which is source of data about the list name
1938 * @return generated TO builder which represents the keys of the
1939 * <code>list</code> or null if <code>list</code> is null or list of
1940 * key definitions is null or empty.
1942 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1943 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1944 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1945 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1946 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1952 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1954 * If more then one generated TO builder is created for enclosing then all
1955 * of the generated TO builders are added to <code>typeBuilder</code> as
1956 * enclosing transfer objects.
1959 * type definition which can be of type <code>UnionType</code> or
1960 * <code>BitsTypeDefinition</code>
1961 * @param typeBuilder
1962 * generated type builder to which is added generated TO created
1963 * from <code>typeDef</code>
1965 * string with name for generated TO builder
1966 * @param parentModule
1968 * @return generated TO builder for <code>typeDef</code>
1970 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1971 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1972 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1973 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1976 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1977 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1978 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1979 for (final GeneratedTOBuilder genTOBuilder : types) {
1980 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1983 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1984 return resultTOBuilder;
1988 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1989 * also added to <code>typeBuilder</code> as enclosing transfer object.
1991 * If more then one generated TO builder is created for enclosing then all
1992 * of the generated TO builders are added to <code>typeBuilder</code> as
1993 * enclosing transfer objects.
1996 * type definition which can be of type <code>UnionType</code> or
1997 * <code>BitsTypeDefinition</code>
1998 * @param typeBuilder
1999 * generated type builder to which is added generated TO created
2000 * from <code>typeDef</code>
2002 * string with name for generated TO builder
2003 * @param parentModule
2005 * @return generated TO builder for <code>typeDef</code>
2007 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
2008 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2009 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
2010 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
2011 typeDef, parentModule.getName());
2012 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2013 return genTOBuilder;
2017 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
2018 final List<GeneratedTOBuilder> genTOBuilders) {
2019 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2020 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2022 return genTOBuilders.get(0);
2026 * Adds the implemented types to type builder.
2028 * The method passes through the list of <i>uses</i> in
2029 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2030 * generated type from {@link ModuleContext#groupings
2031 * allGroupings} which is added as <i>implements type</i> to
2032 * <code>builder</code>
2034 * @param dataNodeContainer
2035 * element which contains the list of used YANG groupings
2037 * builder to which are added implemented types according to
2038 * <code>dataNodeContainer</code>
2039 * @return generated type builder with all implemented types
2041 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2042 final GeneratedTypeBuilder builder) {
2043 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2044 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2045 if (genType == null) {
2046 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2047 + builder.getName());
2050 builder.addImplementsType(genType);
2055 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2056 for (final ModuleContext ctx : genCtx.values()) {
2057 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2058 if (result != null) {
2065 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2066 for (final ModuleContext ctx : genCtx.values()) {
2067 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2068 if (result != null) {
2075 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2076 for (final ModuleContext ctx : genCtx.values()) {
2077 final GeneratedTypeBuilder result = ctx.getCase(path);
2078 if (result != null) {
2085 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2086 if (status == Status.DEPRECATED) {
2087 builder.addAnnotation(DEPRECATED_ANNOTATION);