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.yang.types.AbstractTypeProvider;
78 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
79 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
80 import org.opendaylight.yangtools.yang.binding.BindingMapping;
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)));
429 annotateDeprecatedIfNecessary(action.getStatus(), builder);
430 builder.addImplementsType(action(parent, input, output));
432 addCodegenInformation(builder, context.module(), action);
433 context.addChildNodeType(action, builder);
438 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
439 for (UsesNode uses : parent.getUses()) {
440 final GroupingDefinition grp = findUsedGrouping(uses);
441 final Optional<ActionDefinition> found = grp.getActions().stream()
442 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
443 if (found.isPresent()) {
444 final ActionDefinition result = found.get();
445 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
449 return Optional.empty();
452 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
453 final ContainerSchemaNode schema) {
454 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema);
455 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes());
456 return genType.build();
460 * Converts all <b>RPCs</b> input and output substatements of the module
461 * to the list of <code>Type</code> objects. In addition are to containers
462 * and lists which belong to input or output also part of returning list.
465 * module from which is obtained set of all rpc objects to
467 * @throws IllegalArgumentException
469 * <li>if the module is null</li>
470 * <li>if the name of module is null</li>
472 * @throws IllegalStateException
473 * if set of rpcs from module is null
475 private void rpcMethodsToGenType(final ModuleContext context) {
476 final Module module = context.module();
477 checkArgument(module.getName() != null, "Module name cannot be NULL.");
478 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
479 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
480 if (rpcDefinitions.isEmpty()) {
484 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
485 interfaceBuilder.addImplementsType(RPC_SERVICE);
487 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
489 for (final RpcDefinition rpc : rpcDefinitions) {
491 final String rpcName = BindingMapping.getClassName(rpc.getQName());
492 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
493 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
495 // Do not refer to annotation class, as it may not be available at runtime
496 method.addAnnotation("javax.annotation", "CheckReturnValue");
497 addComment(method, rpc);
499 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
500 method.setReturnType(listenableFutureTypeFor(
501 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
505 context.addTopLevelNodeType(interfaceBuilder);
508 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
509 final ContainerSchemaNode schema) {
510 processUsesAugments(schema, context);
511 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
512 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
514 addImplementedInterfaceFromUses(schema, outType);
515 outType.addImplementsType(DATA_OBJECT);
516 outType.addImplementsType(augmentable(outType));
517 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
518 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
519 context.addChildNodeType(schema, outType);
520 return outType.build();
524 * Converts all <b>notifications</b> of the module to the list of
525 * <code>Type</code> objects. In addition are to this list added containers
526 * and lists which are part of this notification.
529 * module from which is obtained set of all notification objects
530 * to iterate over them
531 * @throws IllegalArgumentException
533 * <li>if the module equals null</li>
534 * <li>if the name of module equals null</li>
536 * @throws IllegalStateException
537 * if set of notifications from module is null
539 private void notificationsToGenType(final ModuleContext context) {
540 final Module module = context.module();
541 checkArgument(module.getName() != null, "Module name cannot be NULL.");
542 final Set<NotificationDefinition> notifications = module.getNotifications();
543 if (notifications.isEmpty()) {
547 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
548 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
550 for (final NotificationDefinition notification : notifications) {
551 if (notification != null) {
552 processUsesAugments(notification, context);
554 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
555 context.modulePackageName(), notification, DATA_OBJECT, context);
556 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
557 notificationInterface.addImplementsType(NOTIFICATION);
558 context.addChildNodeType(notification, notificationInterface);
560 // Notification object
561 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
562 notification.getChildNodes());
564 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
565 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
566 .setReturnType(Types.primitiveVoidType()), notification);
570 addCodegenInformation(listenerInterface, module, "notifications", notifications);
571 context.addTopLevelNodeType(listenerInterface);
575 * Converts all <b>identities</b> of the module to the list of
576 * <code>Type</code> objects.
579 * module from which is obtained set of all identity objects to
581 * @param schemaContext
582 * schema context only used as input parameter for method
583 * {@link BindingGeneratorImpl#identityToGenType}
586 private void allIdentitiesToGenTypes(final ModuleContext context) {
587 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
589 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
590 for (final IdentitySchemaNode identity : schemaIdentities) {
591 identityToGenType(context, identity);
597 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
598 * created transport object builder. If identity contains base identity then
599 * reference to base identity is added to superior identity as its extend.
600 * If identity doesn't contain base identity then only reference to abstract
601 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
602 * BaseIdentity} is added
606 * @param basePackageName
607 * string contains the module package name
609 * IdentitySchemaNode which contains data about identity
611 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
612 if (identity == null) {
615 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
616 packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
617 BindingMapping.getClassName(identity.getQName())));
618 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
619 if (!baseIdentities.isEmpty()) {
620 for (IdentitySchemaNode baseIdentity : baseIdentities) {
621 final QName qname = baseIdentity.getQName();
622 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
623 BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
624 newType.addImplementsType(gto);
627 newType.addImplementsType(BASE_IDENTITY);
630 final Module module = context.module();
631 addCodegenInformation(newType, module, identity);
632 newType.setModuleName(module.getName());
633 newType.setSchemaPath(identity.getPath());
635 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
636 identity.getQName().getLocalName());
638 context.addIdentityType(identity.getQName(), newType);
641 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
642 final JavaTypeName yangModuleInfo, final String localName) {
643 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
644 new SimpleImmutableEntry<>(yangModuleInfo, localName));
648 * Converts all <b>groupings</b> of the module to the list of
649 * <code>Type</code> objects. Firstly are groupings sorted according mutual
650 * dependencies. At least dependent (independent) groupings are in the list
651 * saved at first positions. For every grouping the record is added to map
652 * {@link ModuleContext#groupings allGroupings}
657 * collection of groupings from which types will be generated
660 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
661 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
662 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
663 // node of grouping is resolved to the method.
664 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
665 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
666 context.addGroupingType(grouping.getPath(), genType);
667 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
668 groupingsToGenTypes(context, grouping.getGroupings());
669 processUsesAugments(grouping, context);
670 actionsToGenType(context, genType, grouping);
675 * Adds enumeration builder created from <code>enumTypeDef</code> to
676 * <code>typeBuilder</code>.
678 * Each <code>enumTypeDef</code> item is added to builder with its name and
682 * EnumTypeDefinition contains enum data
684 * string contains name which will be assigned to enumeration
687 * GeneratedTypeBuilder to which will be enum builder assigned
689 * Module in which type should be generated
690 * @return enumeration builder which contains data from
691 * <code>enumTypeDef</code>
693 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
694 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
695 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
696 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
697 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
698 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
699 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
706 * Generates type builder for <code>module</code>.
709 * Module which is source of package name for generated type
712 * string which is added to the module class name representation
714 * @return instance of GeneratedTypeBuilder which represents
715 * <code>module</code>.
716 * @throws IllegalArgumentException
717 * if <code>module</code> is null
719 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
720 final Module module = context.module();
721 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
722 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
723 JavaTypeName.create(context.modulePackageName(), moduleName));
725 moduleBuilder.setModuleName(moduleName);
726 addCodegenInformation(moduleBuilder, module);
727 return moduleBuilder;
731 * Converts <code>augSchema</code> to list of <code>Type</code> which
732 * contains generated type for augmentation. In addition there are also
733 * generated types for all containers, list and choices which are child of
734 * <code>augSchema</code> node or a generated types for cases are added if
735 * augmented node is choice.
737 * @param augmentPackageName
738 * string with the name of the package to which the augmentation
741 * AugmentationSchema which is contains data about augmentation
742 * (target path, childs...)
745 * @throws IllegalArgumentException
747 * <li>if <code>augmentPackageName</code> equals null</li>
748 * <li>if <code>augSchema</code> equals null</li>
750 * @throws IllegalStateException
751 * if augment target path is null
753 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
754 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
755 checkState(augSchema.getTargetPath() != null,
756 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
758 processUsesAugments(augSchema, context);
759 final SchemaPath targetPath = augSchema.getTargetPath();
760 SchemaNode targetSchemaNode = null;
762 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
763 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
764 if (targetSchemaNode instanceof DerivableSchemaNode) {
765 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
767 if (targetSchemaNode == null) {
768 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
769 + " in module " + context.module().getName());
772 if (targetSchemaNode == null) {
773 throw new IllegalArgumentException("augment target not found: " + targetPath);
776 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
777 if (targetTypeBuilder == null) {
778 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
780 if (targetTypeBuilder == null) {
781 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
784 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
785 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
786 addRawAugmentGenTypeDefinition(context, targetType, augSchema);
789 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
790 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
794 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
795 final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
796 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
797 checkState(augSchema.getTargetPath() != null,
798 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
800 processUsesAugments(augSchema, context);
801 final SchemaPath targetPath = augSchema.getTargetPath();
802 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
803 if (targetSchemaNode == null) {
804 throw new IllegalArgumentException("augment target not found: " + targetPath);
807 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
808 if (targetTypeBuilder == null) {
809 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
811 if (targetTypeBuilder == null) {
812 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
815 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
816 if (usesNodeParent instanceof SchemaNode) {
817 addRawAugmentGenTypeDefinition(context,
818 packageNameForAugmentedGeneratedType(context.modulePackageName(),
819 ((SchemaNode) usesNodeParent).getPath()),
820 targetTypeBuilder.build(), augSchema);
822 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
825 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
826 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
830 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
831 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
833 if (targetGrouping instanceof GroupingDefinition) {
834 return (GroupingDefinition) targetGrouping;
837 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
841 * Convenient method to find node added by uses statement.
845 * @param parentUsesNode
846 * parent of uses node
847 * @return node from its original location in grouping
849 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
850 SchemaNode result = findUsedGrouping(parentUsesNode);
851 for (final QName node : targetPath.getPathFromRoot()) {
852 if (result instanceof DataNodeContainer) {
853 final QName resultNode = node.withModule(result.getQName().getModule());
854 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
855 } else if (result instanceof ChoiceSchemaNode) {
856 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
859 if (result == null) {
863 if (result instanceof DerivableSchemaNode) {
864 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
865 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
866 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
867 result = originalNode.get();
871 if (result instanceof DataSchemaNode) {
872 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
873 if (resultDataSchemaNode.isAddedByUses()) {
874 // The original node is required, but we have only the copy of
875 // the original node.
876 // Maybe this indicates a bug in Yang parser.
877 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
880 return resultDataSchemaNode;
883 throw new IllegalStateException(
884 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
889 * Returns a generated type builder for an augmentation.
891 * The name of the type builder is equal to the name of augmented node with
892 * serial number as suffix.
896 * @param augmentPackageName
897 * string with contains the package name to which the augment
899 * @param basePackageName
900 * string with the package name to which the augmented node
902 * @param targetTypeRef
905 * augmentation schema which contains data about the child nodes
906 * and uses of augment
907 * @return generated type builder for augment
909 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
910 final String augmentPackageName, final Type targetTypeRef,
911 final AugmentationSchemaNode augSchema) {
912 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
913 if (augmentBuilders == null) {
914 augmentBuilders = new HashMap<>();
915 genTypeBuilders.put(augmentPackageName, augmentBuilders);
917 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
920 if (augIdentifier != null) {
921 augTypeName = BindingMapping.getClassName(augIdentifier);
923 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
926 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
927 JavaTypeName.create(augmentPackageName, augTypeName));
929 augTypeBuilder.addImplementsType(DATA_OBJECT);
930 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
931 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
932 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
934 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
935 augmentBuilders.put(augTypeName, augTypeBuilder);
937 if (!augSchema.getChildNodes().isEmpty()) {
938 context.addTypeToAugmentation(augTypeBuilder, augSchema);
941 context.addAugmentType(augTypeBuilder);
942 return augTypeBuilder;
945 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
946 final AugmentationSchemaNode augSchema) {
947 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
952 * @param unknownSchemaNodes
953 * @return nodeParameter of UnknownSchemaNode
955 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
956 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
957 final QName nodeType = unknownSchemaNode.getNodeType();
958 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
959 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
960 return unknownSchemaNode.getNodeParameter();
967 * Returns first unique name for the augment generated type builder. The
968 * generated type builder name for augment consists from name of augmented
969 * node and serial number of its augmentation.
972 * map of builders which were created in the package to which the
973 * augmentation belongs
975 * string with name of augmented node
976 * @return string with unique name for augmentation builder
978 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
980 if (builders != null) {
981 while (builders.containsKey(genTypeName + index)) {
985 return genTypeName + index;
989 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
990 * node for which <code>typeBuilder</code> was created.
992 * The subnodes aren't mapped to the methods if they are part of grouping or
993 * augment (in this case are already part of them).
998 * generated type builder which represents any node. The subnodes
999 * of this node are added to the <code>typeBuilder</code> as
1000 * methods. The subnode can be of type leaf, leaf-list, list,
1001 * container, choice.
1004 * @param schemaNodes
1005 * set of data schema nodes which are the children of the node
1006 * for which <code>typeBuilder</code> was created
1007 * @return generated type builder which is the same builder as input
1008 * parameter. The getter methods (representing child nodes) could be
1011 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1012 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1013 if (schemaNodes != null && parent != null) {
1014 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1015 for (final DataSchemaNode schemaNode : schemaNodes) {
1016 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1017 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1025 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1026 * node for which <code>typeBuilder</code> was created.
1030 * @param typeBuilder
1031 * generated type builder which represents any node. The subnodes
1032 * of this node are added to the <code>typeBuilder</code> as
1033 * methods. The subnode can be of type leaf, leaf-list, list,
1034 * container, choice.
1037 * @param schemaNodes
1038 * set of data schema nodes which are the children of the node
1039 * for which <code>typeBuilder</code> was created
1040 * @return generated type builder which is the same object as the input
1041 * parameter <code>typeBuilder</code>. The getter method could be
1044 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1045 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1046 if (schemaNodes != null && typeBuilder != null) {
1047 final Type baseInterface = childOf(typeBuilder);
1048 for (final DataSchemaNode schemaNode : schemaNodes) {
1049 if (!schemaNode.isAugmenting()) {
1050 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1058 * Adds to <code>typeBuilder</code> a method which is derived from
1059 * <code>schemaNode</code>.
1062 * data schema node which is added to <code>typeBuilder</code> as
1064 * @param typeBuilder
1065 * generated type builder to which is <code>schemaNode</code>
1066 * added as a method.
1072 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1073 final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1074 if (node != null && typeBuilder != null) {
1075 if (node instanceof LeafSchemaNode) {
1076 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1077 } else if (node instanceof LeafListSchemaNode) {
1078 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1079 } else if (node instanceof ContainerSchemaNode) {
1080 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1081 } else if (node instanceof ListSchemaNode) {
1082 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1083 } else if (node instanceof ChoiceSchemaNode) {
1084 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1086 // TODO: anyxml not yet supported
1087 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1088 typeBuilder.getFullyQualifiedName());
1094 * Converts <code>choiceNode</code> to the list of generated types for
1095 * choice and its cases.
1097 * The package names for choice and for its cases are created as
1098 * concatenation of the module package (<code>basePackageName</code>) and
1099 * names of all parents node.
1103 * @param basePackageName
1104 * string with the module package name
1108 * choice node which is mapped to generated type. Also child
1109 * nodes - cases are mapped to generated types.
1110 * @throws IllegalArgumentException
1112 * <li>if <code>basePackageName</code> is null</li>
1113 * <li>if <code>choiceNode</code> is null</li>
1116 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1117 final ChoiceSchemaNode choiceNode) {
1118 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1120 if (!choiceNode.isAddedByUses()) {
1121 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1122 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1123 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1124 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1125 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1126 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1128 final GeneratedType choiceType = choiceTypeBuilder.build();
1129 generateTypesFromChoiceCases(context, choiceType, choiceNode);
1131 constructGetter(parent, choiceType, choiceNode);
1136 * Converts <code>caseNodes</code> set to list of corresponding generated types.
1138 * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1139 * The package names for the builder is created as concatenation of the module package and names of all parents
1140 * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1141 * and <i>choice</i> type
1144 * current module context
1145 * @param refChoiceType
1146 * type which represents superior <i>case</i>
1148 * choice case node which is mapped to generated type
1149 * @throws IllegalArgumentException
1151 * <li>if <code>refChoiceType</code> equals null</li>
1152 * <li>if <code>caseNodes</code> equals null</li>
1155 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1156 final ChoiceSchemaNode choiceNode) {
1157 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1158 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1160 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1161 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1162 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1163 caseTypeBuilder.addImplementsType(refChoiceType);
1164 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1165 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1166 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1167 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1168 if (caseChildNodes != null) {
1169 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1171 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1172 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1174 if (parent instanceof AugmentationSchemaNode) {
1175 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1176 final SchemaPath targetPath = augSchema.getTargetPath();
1177 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1178 if (targetSchemaNode instanceof DataSchemaNode
1179 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1180 if (targetSchemaNode instanceof DerivableSchemaNode) {
1181 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1184 if (targetSchemaNode == null) {
1185 throw new IllegalStateException(
1186 "Failed to find target node from grouping for augmentation " + augSchema
1187 + " in module " + context.module().getName());
1190 parent = targetSchemaNode;
1193 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1194 Type childOfType = findChildNodeByPath(parent.getPath());
1195 if (childOfType == null) {
1196 childOfType = findGroupingByPath(parent.getPath());
1198 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1200 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1204 processUsesAugments(caseNode, context);
1209 * Generates list of generated types for all the cases of a choice which are
1210 * added to the choice through the augment.
1214 * @param basePackageName
1215 * string contains name of package to which augment belongs. If
1216 * an augmented choice is from an other package (pcg1) than an
1217 * augmenting choice (pcg2) then case's of the augmenting choice
1218 * will belong to pcg2.
1220 * Type which represents target choice
1222 * node which represents target choice
1223 * @param augmentedNodes
1224 * set of choice case nodes for which is checked if are/aren't
1225 * added to choice through augmentation
1226 * @throws IllegalArgumentException
1228 * <li>if <code>basePackageName</code> is null</li>
1229 * <li>if <code>targetType</code> is null</li>
1230 * <li>if <code>augmentedNodes</code> is null</li>
1233 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1234 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1235 final DataNodeContainer usesNodeParent) {
1236 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1237 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1239 for (final DataSchemaNode caseNode : augmentedNodes) {
1240 if (caseNode != null) {
1241 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1242 caseTypeBuilder.addImplementsType(targetType);
1244 CaseSchemaNode node = null;
1245 final String caseLocalName = caseNode.getQName().getLocalName();
1246 if (caseNode instanceof CaseSchemaNode) {
1247 node = (CaseSchemaNode) caseNode;
1248 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1249 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1250 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1251 if (dataSchemaNode instanceof ChoiceSchemaNode
1252 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1253 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1258 node = findNamedCase(targetNode, caseLocalName);
1260 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1261 if (childNodes != null) {
1262 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1264 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1265 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1270 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1271 final SchemaPath nodePath = targetNode.getPath();
1272 final SchemaPath parentSp = nodePath.getParent();
1273 if (parentSp.getParent() == null) {
1274 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1277 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1278 GeneratedTypeBuilder childOfType = null;
1279 if (parent instanceof CaseSchemaNode) {
1280 childOfType = findCaseByPath(parent.getPath());
1281 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1282 childOfType = findChildNodeByPath(parent.getPath());
1283 } else if (parent instanceof GroupingDefinition) {
1284 childOfType = findGroupingByPath(parent.getPath());
1287 if (childOfType == null) {
1288 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1294 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1295 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1296 return cases.isEmpty() ? null : cases.get(0);
1299 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1300 // New parser with encapsulated type
1301 if (leaf.getPath().equals(type.getPath())) {
1305 // Embedded type definition with new parser. Also takes care of the old parser with bits
1306 if (leaf.getPath().equals(type.getPath().getParent())) {
1313 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1314 final List<PatternConstraint> patternConstraints) {
1315 if (!patternConstraints.isEmpty()) {
1316 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1317 .append(BindingMapping.getPropertyName(leafName));
1318 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1319 typeProvider.resolveRegExpressions(patternConstraints));
1324 * Converts <code>leaf</code> to the getter method which is added to
1325 * <code>typeBuilder</code>.
1327 * @param typeBuilder
1328 * generated type builder to which is added getter method as
1329 * <code>leaf</code> mapping
1331 * leaf schema node which is mapped as getter method which is
1332 * added to <code>typeBuilder</code>
1334 * Module in which type was defined
1335 * @return boolean value
1337 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1339 * <li>true - in other cases</li>
1342 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1343 final ModuleContext context) {
1344 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1348 final Module parentModule = findParentModule(schemaContext, leaf);
1349 Type returnType = null;
1351 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1352 if (isInnerType(leaf, typeDef)) {
1353 if (typeDef instanceof EnumTypeDefinition) {
1354 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1355 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1356 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1357 typeBuilder, context);
1358 if (enumBuilder != null) {
1359 returnType = enumBuilder.toInstance(typeBuilder);
1361 typeProvider.putReferencedType(leaf.getPath(), returnType);
1362 } else if (typeDef instanceof UnionTypeDefinition) {
1363 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1365 if (genTOBuilder != null) {
1366 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1367 // Store the inner type within the union so that we can find the reference for it
1368 context.addInnerTypedefType(typeDef.getPath(), returnType);
1370 } else if (typeDef instanceof BitsTypeDefinition) {
1371 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1373 if (genTOBuilder != null) {
1374 returnType = genTOBuilder.build();
1377 // It is constrained version of already declared type (inner declared type exists,
1378 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1379 // In order to get proper class we need to look up closest derived type
1380 // and apply restrictions from leaf type
1381 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1382 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1384 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1387 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1388 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1389 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1392 if (returnType == null) {
1396 if (typeDef instanceof EnumTypeDefinition) {
1397 typeProvider.putReferencedType(leaf.getPath(), returnType);
1400 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1401 processContextRefExtension(leaf, getter, parentModule);
1405 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1406 // Returns DerivedType in case of new parser.
1407 final TypeDefinition<?> baseType = typeDef.getBaseType();
1408 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1411 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1412 final Module module) {
1413 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1414 final QName nodeType = node.getNodeType();
1415 if ("context-reference".equals(nodeType.getLocalName())) {
1416 final String nodeParam = node.getNodeParameter();
1417 IdentitySchemaNode identity = null;
1418 String basePackageName = null;
1419 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1420 final Iterator<String> iterator = splittedElement.iterator();
1421 final int length = Iterables.size(splittedElement);
1423 identity = findIdentityByName(module.getIdentities(), iterator.next());
1424 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1425 } else if (length == 2) {
1426 final String prefix = iterator.next();
1427 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1428 if (dependentModule == null) {
1429 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1432 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1433 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1435 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1438 if (identity == null) {
1439 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1443 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1444 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1445 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1446 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1451 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1452 for (final IdentitySchemaNode id : identities) {
1453 if (id.getQName().getLocalName().equals(name)) {
1460 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1461 for (final ModuleImport imp : imports) {
1462 if (imp.getPrefix().equals(prefix)) {
1463 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1469 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1470 final boolean isReadOnly) {
1471 if (leaf != null && toBuilder != null) {
1473 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1474 if (typeDef instanceof UnionTypeDefinition) {
1475 // GeneratedType for this type definition should have be already created
1476 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1477 returnType = mc.getTypedefs().get(typeDef.getPath());
1478 if (returnType == null) {
1479 // This may still be an inner type, try to find it
1480 returnType = mc.getInnerType(typeDef.getPath());
1482 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1483 // Annonymous enumeration (already generated, since it is inherited via uses).
1484 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1485 QName qname = originalLeaf.getQName();
1486 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1488 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1490 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1496 * Converts <code>leaf</code> schema node to property of generated TO
1500 * generated TO builder to which is <code>leaf</code> added as
1503 * leaf schema node which is added to <code>toBuilder</code> as
1508 * boolean value which says if leaf property is|isn't read only
1509 * @return boolean value
1511 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1512 * name equals null or if leaf is added by <i>uses</i>.</li>
1513 * <li>true - other cases</li>
1516 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1517 final Type returnType, final boolean isReadOnly) {
1518 if (returnType == null) {
1521 final String leafName = leaf.getQName().getLocalName();
1522 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1523 propBuilder.setReadOnly(isReadOnly);
1524 propBuilder.setReturnType(returnType);
1525 addComment(propBuilder, leaf);
1527 toBuilder.addEqualsIdentity(propBuilder);
1528 toBuilder.addHashIdentity(propBuilder);
1529 toBuilder.addToStringProperty(propBuilder);
1534 * Converts <code>node</code> leaf list schema node to getter method of
1535 * <code>typeBuilder</code>.
1537 * @param typeBuilder
1538 * generated type builder to which is <code>node</code> added as
1541 * leaf list schema node which is added to
1542 * <code>typeBuilder</code> as getter method
1543 * @param module module
1544 * @return boolean value
1546 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1547 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1548 * <li>false - other cases</li>
1551 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1552 final ModuleContext context) {
1553 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1557 final QName nodeName = node.getQName();
1559 final TypeDefinition<?> typeDef = node.getType();
1560 final Module parentModule = findParentModule(schemaContext, node);
1562 Type returnType = null;
1563 if (typeDef.getBaseType() == null) {
1564 if (typeDef instanceof EnumTypeDefinition) {
1565 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1566 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1567 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1568 typeBuilder, context);
1569 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1570 typeProvider.putReferencedType(node.getPath(), returnType);
1571 } else if (typeDef instanceof UnionTypeDefinition) {
1572 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1573 node, parentModule);
1574 if (genTOBuilder != null) {
1575 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1577 } else if (typeDef instanceof BitsTypeDefinition) {
1578 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1579 node, parentModule);
1580 returnType = genTOBuilder.build();
1582 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1583 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1584 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1587 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1588 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1589 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1592 final ParameterizedType listType = listTypeFor(returnType);
1593 constructGetter(typeBuilder, listType, node);
1597 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1598 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1599 final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1601 addCodegenInformation(returnType, parentModule, typeDef);
1602 returnType.setSchemaPath(typeDef.getPath());
1603 returnType.setModuleName(parentModule.getName());
1605 genTOBuilder.setTypedef(true);
1606 genTOBuilder.setIsUnion(true);
1607 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1611 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1614 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1615 method.setReturnType(returnType);
1616 method.addParameter(Types.STRING, "defaultValue");
1617 method.setAccessModifier(AccessModifier.PUBLIC);
1618 method.setStatic(true);
1620 final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1621 if (types == null) {
1622 typeProvider.getAdditionalTypes().put(parentModule,
1623 Sets.newHashSet(unionBuilder.build()));
1625 types.add(unionBuilder.build());
1627 return returnType.build();
1630 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1631 final GeneratedTypeBuilder typeBuilder) {
1632 // Append enclosing path hierarchy without dots
1633 final StringBuilder sb = new StringBuilder();
1634 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1635 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1636 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1637 unionBuilder.setIsUnionBuilder(true);
1638 return unionBuilder;
1641 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1642 final SchemaNode schemaNode) {
1643 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1646 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1647 final SchemaNode schemaNode, final Type baseInterface) {
1648 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1649 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1654 * Instantiates generated type builder with <code>packageName</code> and
1655 * <code>schemaNode</code>.
1657 * The new builder always implements
1658 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1659 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1660 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1662 * If <code>schemaNode</code> is instance of
1663 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1664 * DataNodeContainer} it can also implement nodes which are specified in
1667 * @param packageName
1668 * string with the name of the package to which
1669 * <code>schemaNode</code> belongs.
1671 * schema node for which is created generated type builder
1673 * parent type (can be null)
1674 * @return generated type builder <code>schemaNode</code>
1676 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1677 final Type baseInterface, final ModuleContext context) {
1678 final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1679 JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1681 it.addImplementsType(baseInterface);
1682 if (!(schemaNode instanceof GroupingDefinition)) {
1683 it.addImplementsType(augmentable(it));
1685 if (schemaNode instanceof DataNodeContainer) {
1686 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1687 groupingsToGenTypes(context, containerSchema.getGroupings());
1688 addImplementedInterfaceFromUses(containerSchema, it);
1695 * Wraps the calling of the same overloaded method.
1697 * @param packageName
1698 * string with the package name to which returning generated type
1701 * schema node which provide data about the schema node name
1702 * @return generated type builder for <code>schemaNode</code>
1704 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1705 final String prefix) {
1706 return addRawInterfaceDefinition(
1707 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1708 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1712 * Returns reference to generated type builder for specified
1713 * <code>schemaNode</code> with <code>packageName</code>.
1715 * Firstly the generated type builder is searched in
1716 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1717 * found it is created and added to <code>genTypeBuilders</code>.
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
1725 * return type name prefix
1726 * @return generated type builder for <code>schemaNode</code>
1727 * @throws IllegalArgumentException
1729 * <li>if <code>schemaNode</code> is null</li>
1730 * <li>if <code>packageName</code> is null</li>
1731 * <li>if QName of schema node is null</li>
1732 * <li>if schemaNode name is null</li>
1736 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1737 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1738 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1739 final String schemaNodeName = schemaNode.getQName().getLocalName();
1740 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1742 // FIXME: Validation of name conflict
1743 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1744 final Module module = findParentModule(schemaContext, schemaNode);
1745 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1746 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1748 addCodegenInformation(newType, module, schemaNode);
1749 newType.setSchemaPath(schemaNode.getPath());
1750 newType.setModuleName(module.getName());
1752 final String packageName = identifier.packageName();
1753 final String simpleName = identifier.simpleName();
1754 if (!genTypeBuilders.containsKey(packageName)) {
1755 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1756 builders.put(simpleName, newType);
1757 genTypeBuilders.put(packageName, builders);
1759 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1760 if (!builders.containsKey(simpleName)) {
1761 builders.put(simpleName, newType);
1768 * Creates the name of the getter method name from <code>localName</code>.
1771 * string with the name of the getter method
1774 * @return string with the name of the getter method for
1775 * <code>methodName</code> in JAVA method format
1777 public static String getterMethodName(final String localName, final Type returnType) {
1778 final StringBuilder method = new StringBuilder();
1779 if (BOOLEAN.equals(returnType)) {
1780 method.append("is");
1782 method.append("get");
1784 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1785 method.append(name);
1786 return method.toString();
1790 * Created a method signature builder as part of <code>interfaceBuilder</code>.
1792 * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1793 * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1795 * @param interfaceBuilder generated type builder for which the getter method should be created
1796 * @param returnType type which represents the return type of the getter method
1797 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1798 * @param comment string with comment for the getter method
1799 * @param status status from yang file, for deprecated annotation
1800 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1802 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1803 final SchemaNode node) {
1804 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1805 getterMethodName(node.getQName().getLocalName(), returnType));
1806 getMethod.setReturnType(returnType);
1808 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1809 if (!returnType.getPackageName().isEmpty()) {
1810 // The return type has a package, so it's not a primitive type
1811 getMethod.addAnnotation("javax.annotation", "Nullable");
1813 addComment(getMethod, node);
1819 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1820 * or to <code>genTOBuilder</code> as property.
1822 * @param basePackageName
1823 * string contains the module package name
1825 * data schema node which should be added as getter method to
1826 * <code>typeBuilder</code> or as a property to
1827 * <code>genTOBuilder</code> if is part of the list key
1828 * @param typeBuilder
1829 * generated type builder for the list schema node
1830 * @param genTOBuilder
1831 * generated TO builder for the list keys
1833 * list of string which contains names of the list keys
1836 * @throws IllegalArgumentException
1838 * <li>if <code>schemaNode</code> equals null</li>
1839 * <li>if <code>typeBuilder</code> equals null</li>
1842 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1843 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1844 final List<String> listKeys) {
1845 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1846 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1848 if (schemaNode instanceof LeafSchemaNode) {
1849 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1850 final String leafName = leaf.getQName().getLocalName();
1851 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1852 if (listKeys.contains(leafName)) {
1854 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1856 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1859 } else if (!schemaNode.isAddedByUses()) {
1860 if (schemaNode instanceof LeafListSchemaNode) {
1861 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1862 } else if (schemaNode instanceof ContainerSchemaNode) {
1863 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1864 (ContainerSchemaNode) schemaNode);
1865 } else if (schemaNode instanceof ChoiceSchemaNode) {
1866 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1867 } else if (schemaNode instanceof ListSchemaNode) {
1868 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1873 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1874 final GeneratedTOBuilder genTOBuilder) {
1875 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1877 if (genTOBuilder != null) {
1878 final GeneratedTransferObject genTO = genTOBuilder.build();
1879 // Add Identifiable.getKey() for items
1880 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1881 .addAnnotation(OVERRIDE_ANNOTATION);
1882 context.addGeneratedTOBuilder(genTOBuilder);
1887 * Selects the names of the list keys from <code>list</code> and returns
1888 * them as the list of the strings
1891 * of string with names of the list keys
1892 * @return list of string which represents names of the list keys. If the
1893 * <code>list</code> contains no keys then the empty list is
1896 private static List<String> listKeys(final ListSchemaNode list) {
1897 final List<String> listKeys = new ArrayList<>();
1899 final List<QName> keyDefinition = list.getKeyDefinition();
1900 if (keyDefinition != null) {
1901 for (final QName keyDef : keyDefinition) {
1902 listKeys.add(keyDef.getLocalName());
1909 * Generates for the <code>list</code> which contains any list keys special
1910 * generated TO builder.
1912 * @param packageName
1913 * string with package name to which the list belongs
1915 * list schema node which is source of data about the list name
1916 * @return generated TO builder which represents the keys of the
1917 * <code>list</code> or null if <code>list</code> is null or list of
1918 * key definitions is null or empty.
1920 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1921 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1922 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1923 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1924 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1930 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1932 * If more then one generated TO builder is created for enclosing then all
1933 * of the generated TO builders are added to <code>typeBuilder</code> as
1934 * enclosing transfer objects.
1937 * type definition which can be of type <code>UnionType</code> or
1938 * <code>BitsTypeDefinition</code>
1939 * @param typeBuilder
1940 * generated type builder to which is added generated TO created
1941 * from <code>typeDef</code>
1943 * string with name for generated TO builder
1944 * @param parentModule
1946 * @return generated TO builder for <code>typeDef</code>
1948 private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1949 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1950 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1951 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1954 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1955 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1956 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1957 for (final GeneratedTOBuilder genTOBuilder : types) {
1958 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1961 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1962 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1963 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1964 resultTOBuilder.addHashIdentity(genPropBuilder);
1965 resultTOBuilder.addToStringProperty(genPropBuilder);
1966 processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1967 return resultTOBuilder;
1971 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1972 * also added to <code>typeBuilder</code> as enclosing transfer object.
1974 * If more then one generated TO builder is created for enclosing then all
1975 * of the generated TO builders are added to <code>typeBuilder</code> as
1976 * enclosing transfer objects.
1979 * type definition which can be of type <code>UnionType</code> or
1980 * <code>BitsTypeDefinition</code>
1981 * @param typeBuilder
1982 * generated type builder to which is added generated TO created
1983 * from <code>typeDef</code>
1985 * string with name for generated TO builder
1986 * @param parentModule
1988 * @return generated TO builder for <code>typeDef</code>
1990 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1991 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1992 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1993 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1994 typeDef, parentModule.getName());
1995 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1996 return genTOBuilder;
2000 private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
2001 final List<GeneratedTOBuilder> genTOBuilders) {
2002 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2003 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2005 return genTOBuilders.get(0);
2009 * Adds the implemented types to type builder.
2011 * The method passes through the list of <i>uses</i> in
2012 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2013 * generated type from {@link ModuleContext#groupings
2014 * allGroupings} which is added as <i>implements type</i> to
2015 * <code>builder</code>
2017 * @param dataNodeContainer
2018 * element which contains the list of used YANG groupings
2020 * builder to which are added implemented types according to
2021 * <code>dataNodeContainer</code>
2022 * @return generated type builder with all implemented types
2024 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2025 final GeneratedTypeBuilder builder) {
2026 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2027 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2028 if (genType == null) {
2029 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2030 + builder.getName());
2033 builder.addImplementsType(genType);
2038 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2039 for (final ModuleContext ctx : genCtx.values()) {
2040 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2041 if (result != null) {
2048 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2049 for (final ModuleContext ctx : genCtx.values()) {
2050 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2051 if (result != null) {
2058 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2059 for (final ModuleContext ctx : genCtx.values()) {
2060 final GeneratedTypeBuilder result = ctx.getCase(path);
2061 if (result != null) {
2068 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2069 if (status == Status.DEPRECATED) {
2070 builder.addAnnotation(DEPRECATED_ANNOTATION);