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.rpcResult;
33 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
34 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
35 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
36 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
37 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
38 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
39 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
41 import com.google.common.base.Splitter;
42 import com.google.common.collect.Iterables;
43 import com.google.common.collect.Sets;
44 import java.util.AbstractMap.SimpleImmutableEntry;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.Comparator;
48 import java.util.HashMap;
49 import java.util.Iterator;
50 import java.util.List;
52 import java.util.Optional;
54 import org.eclipse.jdt.annotation.Nullable;
55 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
56 import org.opendaylight.mdsal.binding.model.api.Constant;
57 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
58 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
59 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
60 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
61 import org.opendaylight.mdsal.binding.model.api.Restrictions;
62 import org.opendaylight.mdsal.binding.model.api.Type;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
67 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
68 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
69 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
72 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
73 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
74 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
75 import org.opendaylight.mdsal.binding.model.util.Types;
76 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
77 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
78 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
79 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
80 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
81 import org.opendaylight.yangtools.yang.common.QName;
82 import org.opendaylight.yangtools.yang.common.QNameModule;
83 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
84 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
90 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
93 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
94 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.Module;
99 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
100 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
101 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
102 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
103 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
105 import org.opendaylight.yangtools.yang.model.api.Status;
106 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
107 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.UsesNode;
109 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
110 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
111 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
112 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
113 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
114 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
115 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
116 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
120 abstract class AbstractTypeGenerator {
121 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
122 private static final Splitter COLON_SPLITTER = Splitter.on(':');
123 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
124 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
125 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
128 * Comparator based on augment target path.
130 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
131 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
132 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
134 while (thisIt.hasNext()) {
135 if (!otherIt.hasNext()) {
139 final int comp = thisIt.next().compareTo(otherIt.next());
145 return otherIt.hasNext() ? -1 : 0;
149 * Constant with the concrete name of identifier.
151 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
154 * Constant with the concrete name of namespace.
156 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
158 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
161 * Outer key represents the package name. Outer value represents map of all
162 * builders in the same package. Inner key represents the schema node name
163 * (in JAVA class/interface name format). Inner value represents instance of
164 * builder for schema node specified in key part.
166 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
169 * Provide methods for converting YANG types to JAVA types.
171 private final AbstractTypeProvider typeProvider;
174 * Holds reference to schema context to resolve data of augmented element
175 * when creating augmentation builder
177 private final SchemaContext schemaContext;
179 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
180 this.schemaContext = requireNonNull(context);
181 this.typeProvider = requireNonNull(typeProvider);
183 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
184 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
185 for (final Module contextModule : contextModules) {
186 contexts.add(moduleToGenTypes(contextModule));
189 contexts.forEach(this::allAugmentsToGenTypes);
192 final Collection<ModuleContext> moduleContexts() {
193 return genCtx.values();
196 final ModuleContext moduleContext(final QNameModule module) {
197 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
200 final AbstractTypeProvider typeProvider() {
204 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
206 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
208 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
209 Set<? extends SchemaNode> nodes);
211 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
213 private ModuleContext moduleToGenTypes(final Module module) {
214 final ModuleContext context = new ModuleContext(module);
215 genCtx.put(module.getQNameModule(), context);
216 allTypeDefinitionsToGenTypes(context);
217 groupingsToGenTypes(context, module.getGroupings());
218 rpcMethodsToGenType(context);
219 allIdentitiesToGenTypes(context);
220 notificationsToGenType(context);
222 if (!module.getChildNodes().isEmpty()) {
223 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
224 context.addModuleNode(moduleType);
225 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
231 * Converts all extended type definitions of module to the list of
232 * <code>Type</code> objects.
235 * module from which is obtained set of type definitions
236 * @throws IllegalArgumentException
238 * <li>if module is null</li>
239 * <li>if name of module is null</li>
241 * @throws IllegalStateException
242 * if set of type definitions from module is null
244 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
245 final Module module = context.module();
246 checkArgument(module.getName() != null, "Module name cannot be NULL.");
247 final DataNodeIterator it = new DataNodeIterator(module);
248 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
249 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
251 for (final TypeDefinition<?> typedef : typeDefinitions) {
252 if (typedef != null) {
253 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
255 context.addTypedefType(typedef.getPath(), type);
256 context.addTypeToSchema(type,typedef);
262 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
263 final DataSchemaNode node) {
264 if (node.isAugmenting() || node.isAddedByUses()) {
267 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
268 annotateDeprecatedIfNecessary(node.getStatus(), genType);
270 final Module module = context.module();
271 genType.setModuleName(module.getName());
272 addCodegenInformation(genType, module, node);
273 genType.setSchemaPath(node.getPath());
274 if (node instanceof DataNodeContainer) {
275 context.addChildNodeType(node, genType);
276 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
277 processUsesAugments((DataNodeContainer) node, context);
282 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
283 final Type baseInterface, final ContainerSchemaNode node) {
284 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
285 if (genType != null) {
286 constructGetter(parent, genType, node);
287 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
288 actionsToGenType(context, genType, node);
292 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
293 final Type baseInterface, final ListSchemaNode node) {
294 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node);
295 if (genType != null) {
296 constructGetter(parent, listTypeFor(genType), node);
298 final List<String> listKeys = listKeys(node);
299 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
300 if (genTOBuilder != null) {
301 final Type identifierMarker = identifier(genType);
302 final Type identifiableMarker = identifiable(genTOBuilder);
303 genTOBuilder.addImplementsType(identifierMarker);
304 genType.addImplementsType(identifiableMarker);
306 actionsToGenType(context, genTOBuilder, node);
309 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
310 if (!schemaNode.isAugmenting()) {
311 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
316 if (genTOBuilder != null) {
317 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
318 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
319 genTOBuilder.setSUID(prop);
322 typeBuildersToGenTypes(context, genType, genTOBuilder);
326 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
327 for (final UsesNode usesNode : node.getUses()) {
328 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
329 usesAugmentationToGenTypes(context, augment, usesNode, node);
330 processUsesAugments(augment, context);
336 * Converts all <b>augmentation</b> of the module to the list
337 * <code>Type</code> objects.
340 * module from which is obtained list of all augmentation objects
341 * to iterate over them
342 * @throws IllegalArgumentException
344 * <li>if the module is null</li>
345 * <li>if the name of module is null</li>
347 * @throws IllegalStateException
348 * if set of augmentations from module is null
350 private void allAugmentsToGenTypes(final ModuleContext context) {
351 final Module module = context.module();
352 checkArgument(module != null, "Module reference cannot be NULL.");
353 checkArgument(module.getName() != null, "Module name cannot be NULL.");
354 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
356 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
357 augmentationToGenTypes(context, augment);
362 * Returns list of <code>AugmentationSchema</code> objects. The objects are
363 * sorted according to the length of their target path from the shortest to
367 * module from which is obtained list of all augmentation objects
368 * @return list of sorted <code>AugmentationSchema</code> objects obtained
369 * from <code>module</code>
370 * @throws IllegalArgumentException
372 * @throws IllegalStateException
373 * if set of module augmentations is null
375 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
376 checkArgument(module != null, "Module reference cannot be NULL.");
377 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
379 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
380 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
381 sortedAugmentations.sort(AUGMENT_COMP);
383 return sortedAugmentations;
387 * Create GeneratedTypeBuilder object from module argument.
390 * Module object from which builder will be created
391 * @return <code>GeneratedTypeBuilder</code> which is internal
392 * representation of the module
393 * @throws IllegalArgumentException
396 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
397 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
398 final Module module = context.module();
399 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
400 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
402 addCodegenInformation(moduleDataTypeBuilder, module);
403 return moduleDataTypeBuilder;
406 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
407 final Type parent, final T parentSchema) {
408 for (final ActionDefinition action : parentSchema.getActions()) {
409 final GeneratedType input;
410 final GeneratedType output;
411 if (action.isAddedByUses()) {
412 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
413 input = context.getChildNode(orig.getInput().getPath()).build();
414 output = context.getChildNode(orig.getOutput().getPath()).build();
416 input = actionContainer(context, RPC_INPUT, action.getInput());
417 output = actionContainer(context, RPC_OUTPUT, action.getOutput());
420 if (!(parentSchema instanceof GroupingDefinition)) {
421 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
422 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
423 // and do not capture an actual instantiation.
424 final QName qname = action.getQName();
425 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
426 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
427 BindingMapping.getClassName(qname)));
428 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
429 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
431 annotateDeprecatedIfNecessary(action.getStatus(), builder);
432 builder.addImplementsType(action(parent, input, output));
434 addCodegenInformation(builder, context.module(), action);
435 context.addChildNodeType(action, builder);
440 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
441 for (UsesNode uses : parent.getUses()) {
442 final GroupingDefinition grp = findUsedGrouping(uses);
443 final Optional<ActionDefinition> found = grp.getActions().stream()
444 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
445 if (found.isPresent()) {
446 final ActionDefinition result = found.get();
447 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
451 return Optional.empty();
454 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
455 final ContainerSchemaNode schema) {
456 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
457 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
458 return genType.build();
462 * Converts all <b>RPCs</b> input and output substatements of the module
463 * to the list of <code>Type</code> objects. In addition are to containers
464 * and lists which belong to input or output also part of returning list.
467 * module from which is obtained set of all rpc objects to
469 * @throws IllegalArgumentException
471 * <li>if the module is null</li>
472 * <li>if the name of module is null</li>
474 * @throws IllegalStateException
475 * if set of rpcs from module is null
477 private void rpcMethodsToGenType(final ModuleContext context) {
478 final Module module = context.module();
479 checkArgument(module.getName() != null, "Module name cannot be NULL.");
480 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
481 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
482 if (rpcDefinitions.isEmpty()) {
486 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
487 interfaceBuilder.addImplementsType(RPC_SERVICE);
489 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
491 for (final RpcDefinition rpc : rpcDefinitions) {
493 final String rpcName = BindingMapping.getClassName(rpc.getQName());
494 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
495 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
497 // Do not refer to annotation class, as it may not be available at runtime
498 method.addAnnotation("javax.annotation", "CheckReturnValue");
499 addComment(method, rpc);
501 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
502 method.setReturnType(listenableFutureTypeFor(
503 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
507 context.addTopLevelNodeType(interfaceBuilder);
510 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
511 final ContainerSchemaNode schema, final Type type) {
512 processUsesAugments(schema, context);
513 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
514 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
516 addImplementedInterfaceFromUses(schema, outType);
517 outType.addImplementsType(type);
518 outType.addImplementsType(augmentable(outType));
519 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
520 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
521 context.addChildNodeType(schema, outType);
522 return outType.build();
526 * Converts all <b>notifications</b> of the module to the list of
527 * <code>Type</code> objects. In addition are to this list added containers
528 * and lists which are part of this notification.
531 * module from which is obtained set of all notification objects
532 * to iterate over them
533 * @throws IllegalArgumentException
535 * <li>if the module equals null</li>
536 * <li>if the name of module equals null</li>
538 * @throws IllegalStateException
539 * if set of notifications from module is null
541 private void notificationsToGenType(final ModuleContext context) {
542 final Module module = context.module();
543 checkArgument(module.getName() != null, "Module name cannot be NULL.");
544 final Set<NotificationDefinition> notifications = module.getNotifications();
545 if (notifications.isEmpty()) {
549 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
550 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
552 for (final NotificationDefinition notification : notifications) {
553 if (notification != null) {
554 processUsesAugments(notification, context);
556 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
557 context.modulePackageName(), notification, DATA_OBJECT, context);
558 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
559 notificationInterface.addImplementsType(NOTIFICATION);
560 context.addChildNodeType(notification, notificationInterface);
562 // Notification object
563 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
564 notification.getChildNodes());
566 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
567 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
568 .setReturnType(Types.primitiveVoidType()), notification);
572 addCodegenInformation(listenerInterface, module, "notifications", notifications);
573 context.addTopLevelNodeType(listenerInterface);
577 * Converts all <b>identities</b> of the module to the list of
578 * <code>Type</code> objects.
581 * module from which is obtained set of all identity objects to
583 * @param schemaContext
584 * schema context only used as input parameter for method
585 * {@link BindingGeneratorImpl#identityToGenType}
588 private void allIdentitiesToGenTypes(final ModuleContext context) {
589 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
591 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
592 for (final IdentitySchemaNode identity : schemaIdentities) {
593 identityToGenType(context, identity);
599 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
600 * created transport object builder. If identity contains base identity then
601 * reference to base identity is added to superior identity as its extend.
602 * If identity doesn't contain base identity then only reference to abstract
603 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
604 * BaseIdentity} is added
608 * @param basePackageName
609 * string contains the module package name
611 * IdentitySchemaNode which contains data about identity
613 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
614 if (identity == null) {
617 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
618 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
619 BindingMapping.getClassName(identity.getQName())));
620 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
621 if (!baseIdentities.isEmpty()) {
622 for (IdentitySchemaNode baseIdentity : baseIdentities) {
623 final QName qname = baseIdentity.getQName();
624 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
625 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
626 newType.addImplementsType(gto);
629 newType.addImplementsType(BASE_IDENTITY);
632 final Module module = context.module();
633 addCodegenInformation(newType, module, identity);
634 newType.setModuleName(module.getName());
635 newType.setSchemaPath(identity.getPath());
637 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
638 identity.getQName().getLocalName());
640 context.addIdentityType(identity.getQName(), newType);
643 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
644 final JavaTypeName yangModuleInfo, final String localName) {
645 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
646 new SimpleImmutableEntry<>(yangModuleInfo, localName));
650 * Converts all <b>groupings</b> of the module to the list of
651 * <code>Type</code> objects. Firstly are groupings sorted according mutual
652 * dependencies. At least dependent (independent) groupings are in the list
653 * saved at first positions. For every grouping the record is added to map
654 * {@link ModuleContext#groupings allGroupings}
659 * collection of groupings from which types will be generated
662 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
663 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
664 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
665 // node of grouping is resolved to the method.
666 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
667 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
668 context.addGroupingType(grouping.getPath(), genType);
669 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
670 groupingsToGenTypes(context, grouping.getGroupings());
671 processUsesAugments(grouping, context);
672 actionsToGenType(context, genType, grouping);
677 * Adds enumeration builder created from <code>enumTypeDef</code> to
678 * <code>typeBuilder</code>.
680 * Each <code>enumTypeDef</code> item is added to builder with its name and
684 * EnumTypeDefinition contains enum data
686 * string contains name which will be assigned to enumeration
689 * GeneratedTypeBuilder to which will be enum builder assigned
691 * Module in which type should be generated
692 * @return enumeration builder which contains data from
693 * <code>enumTypeDef</code>
695 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
696 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
697 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
698 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
699 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
700 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
701 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
708 * Generates type builder for <code>module</code>.
711 * Module which is source of package name for generated type
714 * string which is added to the module class name representation
716 * @return instance of GeneratedTypeBuilder which represents
717 * <code>module</code>.
718 * @throws IllegalArgumentException
719 * if <code>module</code> is null
721 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
722 final Module module = context.module();
723 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
724 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
725 JavaTypeName.create(context.modulePackageName(), moduleName));
727 moduleBuilder.setModuleName(moduleName);
728 addCodegenInformation(moduleBuilder, module);
729 return moduleBuilder;
733 * Converts <code>augSchema</code> to list of <code>Type</code> which
734 * contains generated type for augmentation. In addition there are also
735 * generated types for all containers, list and choices which are child of
736 * <code>augSchema</code> node or a generated types for cases are added if
737 * augmented node is choice.
739 * @param augmentPackageName
740 * string with the name of the package to which the augmentation
743 * AugmentationSchema which is contains data about augmentation
744 * (target path, childs...)
747 * @throws IllegalArgumentException
749 * <li>if <code>augmentPackageName</code> equals null</li>
750 * <li>if <code>augSchema</code> equals null</li>
752 * @throws IllegalStateException
753 * if augment target path is null
755 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
756 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
757 checkState(augSchema.getTargetPath() != null,
758 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
760 processUsesAugments(augSchema, context);
761 final SchemaPath targetPath = augSchema.getTargetPath();
762 SchemaNode targetSchemaNode = null;
764 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
765 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
766 if (targetSchemaNode instanceof DerivableSchemaNode) {
767 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
769 if (targetSchemaNode == null) {
770 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
771 + " in module " + context.module().getName());
774 if (targetSchemaNode == null) {
775 throw new IllegalArgumentException("augment target not found: " + targetPath);
778 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
779 if (targetTypeBuilder == null) {
780 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
782 if (targetTypeBuilder == null) {
783 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
786 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
787 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
788 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
791 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
792 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
796 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
797 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
798 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
799 checkState(augSchema.getTargetPath() != null,
800 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
802 processUsesAugments(augSchema, context);
803 final SchemaPath targetPath = augSchema.getTargetPath();
804 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
805 if (targetSchemaNode == null) {
806 throw new IllegalArgumentException("augment target not found: " + targetPath);
809 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
810 if (targetTypeBuilder == null) {
811 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
813 if (targetTypeBuilder == null) {
814 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
817 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
818 if (usesNodeParent instanceof SchemaNode) {
819 addRawAugmentGenTypeDefinition(context,
820 packageNameForAugmentedGeneratedType(context.modulePackageName(),
821 ((SchemaNode) usesNodeParent).getPath()),
822 targetTypeBuilder.build(), augSchema);
824 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
827 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
828 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
832 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
833 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
835 if (targetGrouping instanceof GroupingDefinition) {
836 return (GroupingDefinition) targetGrouping;
839 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
843 * Convenient method to find node added by uses statement.
847 * @param parentUsesNode
848 * parent of uses node
849 * @return node from its original location in grouping
851 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
852 SchemaNode result = findUsedGrouping(parentUsesNode);
853 for (final QName node : targetPath.getPathFromRoot()) {
854 if (result instanceof DataNodeContainer) {
855 final QName resultNode = node.withModule(result.getQName().getModule());
856 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
857 } else if (result instanceof ChoiceSchemaNode) {
858 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
861 if (result == null) {
865 if (result instanceof DerivableSchemaNode) {
866 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
867 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
868 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
869 result = originalNode.get();
873 if (result instanceof DataSchemaNode) {
874 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
875 if (resultDataSchemaNode.isAddedByUses()) {
876 // The original node is required, but we have only the copy of
877 // the original node.
878 // Maybe this indicates a bug in Yang parser.
879 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
882 return resultDataSchemaNode;
885 throw new IllegalStateException(
886 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
891 * Returns a generated type builder for an augmentation.
893 * The name of the type builder is equal to the name of augmented node with
894 * serial number as suffix.
898 * @param augmentPackageName
899 * string with contains the package name to which the augment
901 * @param basePackageName
902 * string with the package name to which the augmented node
904 * @param targetTypeRef
907 * augmentation schema which contains data about the child nodes
908 * and uses of augment
909 * @return generated type builder for augment
911 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
912 final String augmentPackageName, final Type targetTypeRef,
913 final AugmentationSchemaNode augSchema) {
914 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
915 if (augmentBuilders == null) {
916 augmentBuilders = new HashMap<>();
917 genTypeBuilders.put(augmentPackageName, augmentBuilders);
919 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
922 if (augIdentifier != null) {
923 augTypeName = BindingMapping.getClassName(augIdentifier);
925 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
928 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
929 JavaTypeName.create(augmentPackageName, augTypeName));
931 augTypeBuilder.addImplementsType(DATA_OBJECT);
932 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
933 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
934 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
936 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
937 augmentBuilders.put(augTypeName, augTypeBuilder);
939 if (!augSchema.getChildNodes().isEmpty()) {
940 context.addTypeToAugmentation(augTypeBuilder, augSchema);
943 context.addAugmentType(augTypeBuilder);
944 return augTypeBuilder;
947 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
948 final AugmentationSchemaNode augSchema) {
949 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
954 * @param unknownSchemaNodes
955 * @return nodeParameter of UnknownSchemaNode
957 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
958 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
959 final QName nodeType = unknownSchemaNode.getNodeType();
960 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
961 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
962 return unknownSchemaNode.getNodeParameter();
969 * Returns first unique name for the augment generated type builder. The
970 * generated type builder name for augment consists from name of augmented
971 * node and serial number of its augmentation.
974 * map of builders which were created in the package to which the
975 * augmentation belongs
977 * string with name of augmented node
978 * @return string with unique name for augmentation builder
980 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
982 if (builders != null) {
983 while (builders.containsKey(genTypeName + index)) {
987 return genTypeName + index;
991 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
992 * node for which <code>typeBuilder</code> was created.
994 * The subnodes aren't mapped to the methods if they are part of grouping or
995 * augment (in this case are already part of them).
1000 * generated type builder which represents any node. The subnodes
1001 * of this node are added to the <code>typeBuilder</code> as
1002 * methods. The subnode can be of type leaf, leaf-list, list,
1003 * container, choice.
1006 * @param schemaNodes
1007 * set of data schema nodes which are the children of the node
1008 * for which <code>typeBuilder</code> was created
1009 * @return generated type builder which is the same builder as input
1010 * parameter. The getter methods (representing child nodes) could be
1013 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1014 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1015 if (schemaNodes != null && parent != null) {
1016 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1017 for (final DataSchemaNode schemaNode : schemaNodes) {
1018 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1019 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1027 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1028 * node for which <code>typeBuilder</code> was created.
1032 * @param typeBuilder
1033 * generated type builder which represents any node. The subnodes
1034 * of this node are added to the <code>typeBuilder</code> as
1035 * methods. The subnode can be of type leaf, leaf-list, list,
1036 * container, choice.
1039 * @param schemaNodes
1040 * set of data schema nodes which are the children of the node
1041 * for which <code>typeBuilder</code> was created
1042 * @return generated type builder which is the same object as the input
1043 * parameter <code>typeBuilder</code>. The getter method could be
1046 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1047 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1048 if (schemaNodes != null && typeBuilder != null) {
1049 final Type baseInterface = childOf(typeBuilder);
1050 for (final DataSchemaNode schemaNode : schemaNodes) {
1051 if (!schemaNode.isAugmenting()) {
1052 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1060 * Adds to <code>typeBuilder</code> a method which is derived from
1061 * <code>schemaNode</code>.
1064 * data schema node which is added to <code>typeBuilder</code> as
1066 * @param typeBuilder
1067 * generated type builder to which is <code>schemaNode</code>
1068 * added as a method.
1074 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1075 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1076 if (node != null && typeBuilder != null) {
1077 if (node instanceof LeafSchemaNode) {
1078 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1079 } else if (node instanceof LeafListSchemaNode) {
1080 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1081 } else if (node instanceof ContainerSchemaNode) {
1082 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1083 } else if (node instanceof ListSchemaNode) {
1084 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1085 } else if (node instanceof ChoiceSchemaNode) {
1086 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1088 // TODO: anyxml not yet supported
1089 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1090 typeBuilder.getFullyQualifiedName());
1096 * Converts <code>choiceNode</code> to the list of generated types for
1097 * choice and its cases.
1099 * The package names for choice and for its cases are created as
1100 * concatenation of the module package (<code>basePackageName</code>) and
1101 * names of all parents node.
1105 * @param basePackageName
1106 * string with the module package name
1110 * choice node which is mapped to generated type. Also child
1111 * nodes - cases are mapped to generated types.
1112 * @throws IllegalArgumentException
1114 * <li>if <code>basePackageName</code> is null</li>
1115 * <li>if <code>choiceNode</code> is null</li>
1118 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1119 final ChoiceSchemaNode choiceNode) {
1120 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1122 if (!choiceNode.isAddedByUses()) {
1123 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1124 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1125 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1126 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1127 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1128 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1130 final GeneratedType choiceType = choiceTypeBuilder.build();
1131 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1133 constructGetter(parent, choiceType, choiceNode);
1138 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1140 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1141 * The package names for the builder is created as concatenation of the module package and names of all parents
1142 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1143 * and <i>choice</i> type
1146 * current module context
1147 * @param refChoiceType
1148 * type which represents superior <i>case</i>
1150 * choice case node which is mapped to generated type
1151 * @throws IllegalArgumentException
1153 * <li>if <code>refChoiceType</code> equals null</li>
1154 * <li>if <code>caseNodes</code> equals null</li>
1157 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1158 final ChoiceSchemaNode choiceNode) {
1159 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1160 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1162 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1163 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1164 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1165 caseTypeBuilder.addImplementsType(refChoiceType);
1166 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1167 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1168 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1169 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1170 if (caseChildNodes != null) {
1171 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1173 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1174 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1176 if (parent instanceof AugmentationSchemaNode) {
1177 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1178 final SchemaPath targetPath = augSchema.getTargetPath();
1179 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1180 if (targetSchemaNode instanceof DataSchemaNode
1181 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1182 if (targetSchemaNode instanceof DerivableSchemaNode) {
1183 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1186 if (targetSchemaNode == null) {
1187 throw new IllegalStateException(
1188 "Failed to find target node from grouping for augmentation " + augSchema
1189 + " in module " + context.module().getName());
1192 parent = targetSchemaNode;
1195 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1196 Type childOfType = findChildNodeByPath(parent.getPath());
1197 if (childOfType == null) {
1198 childOfType = findGroupingByPath(parent.getPath());
1200 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1202 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1206 processUsesAugments(caseNode, context);
1211 * Generates list of generated types for all the cases of a choice which are
1212 * added to the choice through the augment.
1216 * @param basePackageName
1217 * string contains name of package to which augment belongs. If
1218 * an augmented choice is from an other package (pcg1) than an
1219 * augmenting choice (pcg2) then case's of the augmenting choice
1220 * will belong to pcg2.
1222 * Type which represents target choice
1224 * node which represents target choice
1225 * @param augmentedNodes
1226 * set of choice case nodes for which is checked if are/aren't
1227 * added to choice through augmentation
1228 * @throws IllegalArgumentException
1230 * <li>if <code>basePackageName</code> is null</li>
1231 * <li>if <code>targetType</code> is null</li>
1232 * <li>if <code>augmentedNodes</code> is null</li>
1235 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1236 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1237 final DataNodeContainer usesNodeParent) {
1238 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1239 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1241 for (final DataSchemaNode caseNode : augmentedNodes) {
1242 if (caseNode != null) {
1243 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1244 caseTypeBuilder.addImplementsType(targetType);
1246 CaseSchemaNode node = null;
1247 final String caseLocalName = caseNode.getQName().getLocalName();
1248 if (caseNode instanceof CaseSchemaNode) {
1249 node = (CaseSchemaNode) caseNode;
1250 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1251 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1252 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1253 if (dataSchemaNode instanceof ChoiceSchemaNode
1254 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1255 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1260 node = findNamedCase(targetNode, caseLocalName);
1262 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1263 if (childNodes != null) {
1264 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1266 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1267 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1272 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1273 final SchemaPath nodePath = targetNode.getPath();
1274 final SchemaPath parentSp = nodePath.getParent();
1275 if (parentSp.getParent() == null) {
1276 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1279 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1280 GeneratedTypeBuilder childOfType = null;
1281 if (parent instanceof CaseSchemaNode) {
1282 childOfType = findCaseByPath(parent.getPath());
1283 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1284 childOfType = findChildNodeByPath(parent.getPath());
1285 } else if (parent instanceof GroupingDefinition) {
1286 childOfType = findGroupingByPath(parent.getPath());
1289 if (childOfType == null) {
1290 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1296 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1297 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1298 return cases.isEmpty() ? null : cases.get(0);
1301 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1302 // New parser with encapsulated type
1303 if (leaf.getPath().equals(type.getPath())) {
1307 // Embedded type definition with new parser. Also takes care of the old parser with bits
1308 if (leaf.getPath().equals(type.getPath().getParent())) {
1315 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1316 final List<PatternConstraint> patternConstraints) {
1317 if (!patternConstraints.isEmpty()) {
1318 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1319 .append(BindingMapping.getPropertyName(leafName));
1320 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1321 typeProvider.resolveRegExpressions(patternConstraints));
1326 * Converts <code>leaf</code> to the getter method which is added to
1327 * <code>typeBuilder</code>.
1329 * @param typeBuilder
1330 * generated type builder to which is added getter method as
1331 * <code>leaf</code> mapping
1333 * leaf schema node which is mapped as getter method which is
1334 * added to <code>typeBuilder</code>
1336 * Module in which type was defined
1337 * @return boolean value
1339 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1341 * <li>true - in other cases</li>
1344 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1345 final ModuleContext context) {
1346 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1350 final Module parentModule = findParentModule(schemaContext, leaf);
1351 Type returnType = null;
1353 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1354 if (isInnerType(leaf, typeDef)) {
1355 if (typeDef instanceof EnumTypeDefinition) {
1356 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1357 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1358 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1359 typeBuilder, context);
1360 if (enumBuilder != null) {
1361 returnType = enumBuilder.toInstance(typeBuilder);
1363 typeProvider.putReferencedType(leaf.getPath(), returnType);
1364 } else if (typeDef instanceof UnionTypeDefinition) {
1365 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1367 if (genTOBuilder != null) {
1368 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1369 // Store the inner type within the union so that we can find the reference for it
1370 context.addInnerTypedefType(typeDef.getPath(), returnType);
1372 } else if (typeDef instanceof BitsTypeDefinition) {
1373 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1375 if (genTOBuilder != null) {
1376 returnType = genTOBuilder.build();
1379 // It is constrained version of already declared type (inner declared type exists,
1380 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1381 // In order to get proper class we need to look up closest derived type
1382 // and apply restrictions from leaf type
1383 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1384 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1386 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1389 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1390 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1391 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1394 if (returnType == null) {
1398 if (typeDef instanceof EnumTypeDefinition) {
1399 typeProvider.putReferencedType(leaf.getPath(), returnType);
1402 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1403 processContextRefExtension(leaf, getter, parentModule);
1407 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1408 // Returns DerivedType in case of new parser.
1409 final TypeDefinition<?> baseType = typeDef.getBaseType();
1410 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1413 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1414 final Module module) {
1415 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1416 final QName nodeType = node.getNodeType();
1417 if ("context-reference".equals(nodeType.getLocalName())) {
1418 final String nodeParam = node.getNodeParameter();
1419 IdentitySchemaNode identity = null;
1420 String basePackageName = null;
1421 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1422 final Iterator<String> iterator = splittedElement.iterator();
1423 final int length = Iterables.size(splittedElement);
1425 identity = findIdentityByName(module.getIdentities(), iterator.next());
1426 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1427 } else if (length == 2) {
1428 final String prefix = iterator.next();
1429 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1430 if (dependentModule == null) {
1431 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1434 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1435 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1437 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1440 if (identity == null) {
1441 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1445 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1446 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1447 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1448 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1453 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1454 for (final IdentitySchemaNode id : identities) {
1455 if (id.getQName().getLocalName().equals(name)) {
1462 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1463 for (final ModuleImport imp : imports) {
1464 if (imp.getPrefix().equals(prefix)) {
1465 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1471 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1472 final boolean isReadOnly) {
1473 if (leaf != null && toBuilder != null) {
1475 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1476 if (typeDef instanceof UnionTypeDefinition) {
1477 // GeneratedType for this type definition should have be already created
1478 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1479 returnType = mc.getTypedefs().get(typeDef.getPath());
1480 if (returnType == null) {
1481 // This may still be an inner type, try to find it
1482 returnType = mc.getInnerType(typeDef.getPath());
1484 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1485 // Annonymous enumeration (already generated, since it is inherited via uses).
1486 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1487 QName qname = originalLeaf.getQName();
1488 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1490 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1492 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1498 * Converts <code>leaf</code> schema node to property of generated TO
1502 * generated TO builder to which is <code>leaf</code> added as
1505 * leaf schema node which is added to <code>toBuilder</code> as
1510 * boolean value which says if leaf property is|isn't read only
1511 * @return boolean value
1513 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1514 * name equals null or if leaf is added by <i>uses</i>.</li>
1515 * <li>true - other cases</li>
1518 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1519 final Type returnType, final boolean isReadOnly) {
1520 if (returnType == null) {
1523 final String leafName = leaf.getQName().getLocalName();
1524 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1525 propBuilder.setReadOnly(isReadOnly);
1526 propBuilder.setReturnType(returnType);
1527 addComment(propBuilder, leaf);
1529 toBuilder.addEqualsIdentity(propBuilder);
1530 toBuilder.addHashIdentity(propBuilder);
1531 toBuilder.addToStringProperty(propBuilder);
1536 * Converts <code>node</code> leaf list schema node to getter method of
1537 * <code>typeBuilder</code>.
1539 * @param typeBuilder
1540 * generated type builder to which is <code>node</code> added as
1543 * leaf list schema node which is added to
1544 * <code>typeBuilder</code> as getter method
1545 * @param module module
1546 * @return boolean value
1548 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1549 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1550 * <li>false - other cases</li>
1553 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1554 final ModuleContext context) {
1555 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1559 final QName nodeName = node.getQName();
1561 final TypeDefinition<?> typeDef = node.getType();
1562 final Module parentModule = findParentModule(schemaContext, node);
1564 Type returnType = null;
1565 if (typeDef.getBaseType() == null) {
1566 if (typeDef instanceof EnumTypeDefinition) {
1567 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1568 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1569 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1570 typeBuilder, context);
1571 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1572 typeProvider.putReferencedType(node.getPath(), returnType);
1573 } else if (typeDef instanceof UnionTypeDefinition) {
1574 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1575 node, parentModule);
1576 if (genTOBuilder != null) {
1577 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1579 } else if (typeDef instanceof BitsTypeDefinition) {
1580 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1581 node, parentModule);
1582 returnType = genTOBuilder.build();
1584 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1585 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1586 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1589 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1590 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1591 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1594 final ParameterizedType listType = listTypeFor(returnType);
1595 constructGetter(typeBuilder, listType, node);
1599 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1600 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1601 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1603 addCodegenInformation(returnType, parentModule, typeDef);
1604 returnType.setSchemaPath(typeDef.getPath());
1605 returnType.setModuleName(parentModule.getName());
1607 genTOBuilder.setTypedef(true);
1608 genTOBuilder.setIsUnion(true);
1609 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1613 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1616 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1617 method.setReturnType(returnType);
1618 method.addParameter(Types.STRING, "defaultValue");
1619 method.setAccessModifier(AccessModifier.PUBLIC);
1620 method.setStatic(true);
1622 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1623 if (types == null) {
1624 typeProvider.getAdditionalTypes().put(parentModule,
1625 Sets.newHashSet(unionBuilder.build()));
1627 types.add(unionBuilder.build());
1629 return returnType.build();
1632 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1633 final GeneratedTypeBuilder typeBuilder) {
1634 // Append enclosing path hierarchy without dots
1635 final StringBuilder sb = new StringBuilder();
1636 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1637 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1638 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1639 unionBuilder.setIsUnionBuilder(true);
1640 return unionBuilder;
1643 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1644 final SchemaNode schemaNode) {
1645 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1648 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1649 final SchemaNode schemaNode, final Type baseInterface) {
1650 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1651 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1656 * Instantiates generated type builder with <code>packageName</code> and
1657 * <code>schemaNode</code>.
1659 * The new builder always implements
1660 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1661 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1662 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1664 * If <code>schemaNode</code> is instance of
1665 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1666 * DataNodeContainer} it can also implement nodes which are specified in
1669 * @param packageName
1670 * string with the name of the package to which
1671 * <code>schemaNode</code> belongs.
1673 * schema node for which is created generated type builder
1675 * parent type (can be null)
1676 * @return generated type builder <code>schemaNode</code>
1678 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1679 final Type baseInterface, final ModuleContext context) {
1680 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1681 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1683 it.addImplementsType(baseInterface);
1684 if (!(schemaNode instanceof GroupingDefinition)) {
1685 it.addImplementsType(augmentable(it));
1687 if (schemaNode instanceof DataNodeContainer) {
1688 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1689 groupingsToGenTypes(context, containerSchema.getGroupings());
1690 addImplementedInterfaceFromUses(containerSchema, it);
1697 * Wraps the calling of the same overloaded method.
1699 * @param packageName
1700 * string with the package name to which returning generated type
1703 * schema node which provide data about the schema node name
1704 * @return generated type builder for <code>schemaNode</code>
1706 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1707 final String prefix) {
1708 return addRawInterfaceDefinition(
1709 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1710 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1714 * Returns reference to generated type builder for specified
1715 * <code>schemaNode</code> with <code>packageName</code>.
1717 * Firstly the generated type builder is searched in
1718 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1719 * found it is created and added to <code>genTypeBuilders</code>.
1721 * @param packageName
1722 * string with the package name to which returning generated type
1725 * schema node which provide data about the schema node name
1727 * return type name prefix
1728 * @return generated type builder for <code>schemaNode</code>
1729 * @throws IllegalArgumentException
1731 * <li>if <code>schemaNode</code> is null</li>
1732 * <li>if <code>packageName</code> is null</li>
1733 * <li>if QName of schema node is null</li>
1734 * <li>if schemaNode name is null</li>
1738 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1739 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1740 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1741 final String schemaNodeName = schemaNode.getQName().getLocalName();
1742 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1744 // FIXME: Validation of name conflict
1745 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1746 final Module module = findParentModule(schemaContext, schemaNode);
1747 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1748 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1750 addCodegenInformation(newType, module, schemaNode);
1751 newType.setSchemaPath(schemaNode.getPath());
1752 newType.setModuleName(module.getName());
1754 final String packageName = identifier.packageName();
1755 final String simpleName = identifier.simpleName();
1756 if (!genTypeBuilders.containsKey(packageName)) {
1757 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1758 builders.put(simpleName, newType);
1759 genTypeBuilders.put(packageName, builders);
1761 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1762 if (!builders.containsKey(simpleName)) {
1763 builders.put(simpleName, newType);
1770 * Creates the name of the getter method name from <code>localName</code>.
1773 * string with the name of the getter method
1776 * @return string with the name of the getter method for
1777 * <code>methodName</code> in JAVA method format
1779 public static String getterMethodName(final String localName, final Type returnType) {
1780 final StringBuilder method = new StringBuilder();
1781 if (BOOLEAN.equals(returnType)) {
1782 method.append("is");
1784 method.append("get");
1786 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1787 method.append(name);
1788 return method.toString();
1792 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1794 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1795 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1797 * @param interfaceBuilder generated type builder for which the getter method should be created
1798 * @param returnType type which represents the return type of the getter method
1799 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1800 * @param comment string with comment for the getter method
1801 * @param status status from yang file, for deprecated annotation
1802 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1804 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1805 final SchemaNode node) {
1806 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1807 getterMethodName(node.getQName().getLocalName(), returnType));
1808 getMethod.setReturnType(returnType);
1810 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1811 if (!returnType.getPackageName().isEmpty()) {
1812 // The return type has a package, so it's not a primitive type
1813 getMethod.addAnnotation("javax.annotation", "Nullable");
1815 addComment(getMethod, node);
1821 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1822 * or to <code>genTOBuilder</code> as property.
1824 * @param basePackageName
1825 * string contains the module package name
1827 * data schema node which should be added as getter method to
1828 * <code>typeBuilder</code> or as a property to
1829 * <code>genTOBuilder</code> if is part of the list key
1830 * @param typeBuilder
1831 * generated type builder for the list schema node
1832 * @param genTOBuilder
1833 * generated TO builder for the list keys
1835 * list of string which contains names of the list keys
1838 * @throws IllegalArgumentException
1840 * <li>if <code>schemaNode</code> equals null</li>
1841 * <li>if <code>typeBuilder</code> equals null</li>
1844 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1845 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1846 final List<String> listKeys) {
1847 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1848 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1850 if (schemaNode instanceof LeafSchemaNode) {
1851 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1852 final String leafName = leaf.getQName().getLocalName();
1853 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1854 if (listKeys.contains(leafName)) {
1856 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1858 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1861 } else if (!schemaNode.isAddedByUses()) {
1862 if (schemaNode instanceof LeafListSchemaNode) {
1863 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1864 } else if (schemaNode instanceof ContainerSchemaNode) {
1865 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1866 (ContainerSchemaNode) schemaNode);
1867 } else if (schemaNode instanceof ChoiceSchemaNode) {
1868 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1869 } else if (schemaNode instanceof ListSchemaNode) {
1870 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1875 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1876 final GeneratedTOBuilder genTOBuilder) {
1877 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1879 if (genTOBuilder != null) {
1880 final GeneratedTransferObject genTO = genTOBuilder.build();
1881 // Add Identifiable.getKey() for items
1882 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1883 .addAnnotation(OVERRIDE_ANNOTATION);
1884 context.addGeneratedTOBuilder(genTOBuilder);
1889 * Selects the names of the list keys from <code>list</code> and returns
1890 * them as the list of the strings
1893 * of string with names of the list keys
1894 * @return list of string which represents names of the list keys. If the
1895 * <code>list</code> contains no keys then the empty list is
1898 private static List<String> listKeys(final ListSchemaNode list) {
1899 final List<String> listKeys = new ArrayList<>();
1901 final List<QName> keyDefinition = list.getKeyDefinition();
1902 if (keyDefinition != null) {
1903 for (final QName keyDef : keyDefinition) {
1904 listKeys.add(keyDef.getLocalName());
1911 * Generates for the <code>list</code> which contains any list keys special
1912 * generated TO builder.
1914 * @param packageName
1915 * string with package name to which the list belongs
1917 * list schema node which is source of data about the list name
1918 * @return generated TO builder which represents the keys of the
1919 * <code>list</code> or null if <code>list</code> is null or list of
1920 * key definitions is null or empty.
1922 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1923 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1924 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1925 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1926 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1932 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1934 * If more then one generated TO builder is created for enclosing then all
1935 * of the generated TO builders are added to <code>typeBuilder</code> as
1936 * enclosing transfer objects.
1939 * type definition which can be of type <code>UnionType</code> or
1940 * <code>BitsTypeDefinition</code>
1941 * @param typeBuilder
1942 * generated type builder to which is added generated TO created
1943 * from <code>typeDef</code>
1945 * string with name for generated TO builder
1946 * @param parentModule
1948 * @return generated TO builder for <code>typeDef</code>
1950 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1951 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1952 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1953 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1956 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1957 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1958 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1959 for (final GeneratedTOBuilder genTOBuilder : types) {
1960 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1963 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1964 return resultTOBuilder;
1968 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1969 * also added to <code>typeBuilder</code> as enclosing transfer object.
1971 * If more then one generated TO builder is created for enclosing then all
1972 * of the generated TO builders are added to <code>typeBuilder</code> as
1973 * enclosing transfer objects.
1976 * type definition which can be of type <code>UnionType</code> or
1977 * <code>BitsTypeDefinition</code>
1978 * @param typeBuilder
1979 * generated type builder to which is added generated TO created
1980 * from <code>typeDef</code>
1982 * string with name for generated TO builder
1983 * @param parentModule
1985 * @return generated TO builder for <code>typeDef</code>
1987 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1988 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1989 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1990 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1991 typeDef, parentModule.getName());
1992 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1993 return genTOBuilder;
1997 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1998 final List<GeneratedTOBuilder> genTOBuilders) {
1999 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2000 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2002 return genTOBuilders.get(0);
2006 * Adds the implemented types to type builder.
2008 * The method passes through the list of <i>uses</i> in
2009 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2010 * generated type from {@link ModuleContext#groupings
2011 * allGroupings} which is added as <i>implements type</i> to
2012 * <code>builder</code>
2014 * @param dataNodeContainer
2015 * element which contains the list of used YANG groupings
2017 * builder to which are added implemented types according to
2018 * <code>dataNodeContainer</code>
2019 * @return generated type builder with all implemented types
2021 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2022 final GeneratedTypeBuilder builder) {
2023 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2024 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2025 if (genType == null) {
2026 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2027 + builder.getName());
2030 builder.addImplementsType(genType);
2035 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2036 for (final ModuleContext ctx : genCtx.values()) {
2037 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2038 if (result != null) {
2045 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2046 for (final ModuleContext ctx : genCtx.values()) {
2047 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2048 if (result != null) {
2055 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2056 for (final ModuleContext ctx : genCtx.values()) {
2057 final GeneratedTypeBuilder result = ctx.getCase(path);
2058 if (result != null) {
2065 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2066 if (status == Status.DEPRECATED) {
2067 builder.addAnnotation(DEPRECATED_ANNOTATION);