0d3ad6979c96260475e12511ab5135d7856aee39
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / impl / RpcActionGenHelper.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.mdsal.binding.javav2.generator.impl;
10
11 import static com.google.common.base.Preconditions.checkState;
12 import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.annotateDeprecatedIfNecessary;
13 import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.checkModuleAndModuleName;
14 import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.createDescription;
15 import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.addImplementedInterfaceFromUses;
16 import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.addRawInterfaceDefinition;
17 import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.moduleTypeBuilder;
18 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
19 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
20 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.ACTION;
21 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INPUT;
22 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INSTANCE_IDENTIFIER;
23 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INSTANTIABLE;
24 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.KEYED_INSTANCE_IDENTIFIER;
25 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.LIST_ACTION;
26 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.OUTPUT;
27 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.RPC;
28 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.RPC_CALLBACK;
29 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.TREE_NODE;
30 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.augmentable;
31 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.CLASS;
32 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.VOID;
33 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.parameterizedTypeFor;
34
35 import com.google.common.annotations.Beta;
36 import com.google.common.base.Optional;
37 import java.util.Collection;
38 import java.util.Map;
39 import java.util.Set;
40 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
41 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes;
42 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
43 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
44 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
45 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
46 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
49 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
58
59 /**
60  *
61  * Util class used for generation of types for RPCs, routedRPCs and Actions (YANG 1.1 only)
62  * in Binding spec. v2. In case of routed RPC detected in input YANG, RPC is turned to Action.
63  *
64  */
65 @Beta
66 final class RpcActionGenHelper {
67
68     private static final QName CONTEXT_REFERENCE =
69             QName.create("urn:opendaylight:yang:extension:yang-ext", "2013-07-09", "context-reference").intern();
70
71     private RpcActionGenHelper() {
72         throw new UnsupportedOperationException("Util class");
73     }
74
75     /**
76      * Let's find out what context we are talking about
77      * 1. routed RPC
78      * 2. global RPC
79      *
80      * In 1st case, we need Binding Generator behave like YANG 1.1 Action
81      *
82      * @param schemaNode RPC input node
83      * @return presence optional
84      */
85     private static Optional<QName> getRoutingContext(final DataSchemaNode schemaNode) {
86         for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
87             if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
88                 return Optional.fromNullable(extension.getQName());
89             }
90         }
91         return Optional.absent();
92     }
93
94     /**
95      * Converts Yang 1.1 <b>Actions</b> to list of <code>Type</code> objects.
96      * @param module  module from which is obtained set of all Action objects to
97      *            iterate over them
98      * @param genCtx input, generated context
99      * @param verboseClassComments verbosity switch
100      * @return generated context
101      */
102     static Map<Module, ModuleContext> actionMethodsToGenType(final Module module, Map<Module, ModuleContext> genCtx,
103             final SchemaContext schemaContext, final boolean verboseClassComments, Map<String, Map<String,
104             GeneratedTypeBuilder>> genTypeBuilders, TypeProvider typeProvider) {
105
106         checkModuleAndModuleName(module);
107         final Collection<DataSchemaNode> potentials = module.getChildNodes();
108         for (DataSchemaNode potential : potentials) {
109             if (potential instanceof ActionNodeContainer) {
110                 final Set<ActionDefinition> actions = ((ActionNodeContainer) potential).getActions();
111                 for (ActionDefinition action: actions) {
112                     genCtx.get(module).addTopLevelNodeType(resolveOperation(potential, action, module,
113                             schemaContext, verboseClassComments, genTypeBuilders, genCtx, typeProvider, true,
114                             BindingNamespaceType.Data));
115                 }
116             }
117         }
118         return genCtx;
119     }
120
121     /**
122      * Converts global <b>RPCs</b> inputs and outputs sub-statements of the module
123      * to the list of <code>Type</code> objects. In addition, containers
124      * and lists which belong to input or output are also part of returning list.
125      * Detected routed RPCs are turned to Yang 1.1 Actions
126      *
127      * @param module
128      *            module from which is obtained set of all RPC objects to
129      *            iterate over them
130      * @param genCtx input, generated context
131      * @param verboseClassComments verbosity switch
132      *
133      * @throws IllegalArgumentException
134      *             <ul>
135      *             <li>if the module is null</li>
136      *             <li>if the name of module is null</li>
137      *             </ul>
138      * @throws IllegalStateException
139      *             if set of RPCs from module is null
140      *
141      * @return generated context
142      */
143      static Map<Module, ModuleContext> rpcMethodsToGenType(final Module module, Map<Module, ModuleContext> genCtx,
144             final SchemaContext schemaContext, final boolean verboseClassComments, Map<String, Map<String,
145              GeneratedTypeBuilder>> genTypeBuilders, TypeProvider typeProvider) {
146
147         checkModuleAndModuleName(module);
148         final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
149         checkState(rpcDefinitions != null, "Set of RPCs from module " + module.getName() + " cannot be NULL.");
150         if (rpcDefinitions.isEmpty()) {
151             return genCtx;
152         }
153
154         for (final RpcDefinition rpc : rpcDefinitions) {
155             //FIXME: get correct parent for routed RPCs only
156             DataSchemaNode parent = null;
157
158             ContainerSchemaNode input = rpc.getInput();
159             boolean isAction = false;
160             if (input != null) {
161                 for (DataSchemaNode schemaNode : input.getChildNodes()) {
162                     if (getRoutingContext(schemaNode).isPresent()) {
163                         isAction = true;
164                         break;
165                     }
166                 }
167             }
168
169             //routedRPC?
170             if (isAction) {
171                 genCtx.get(module).addTopLevelNodeType(resolveOperation(parent, rpc, module, schemaContext,
172                         verboseClassComments, genTypeBuilders, genCtx, typeProvider, true,
173                         BindingNamespaceType.Data));
174             } else {
175                 //global RPC only
176                 genCtx.get(module).addTopLevelNodeType(resolveOperation(parent, rpc, module, schemaContext,
177                         verboseClassComments, genTypeBuilders, genCtx, typeProvider, false,
178                         BindingNamespaceType.Data));
179
180             }
181         }
182         return genCtx;
183     }
184
185     //TODO: This method should be reusable for convertion of action that is in grouping.
186     /**
187      * Converts RPC, Action or routed RPC into generated type
188      * @return generated type
189      */
190     private static GeneratedTypeBuilder resolveOperation(final DataSchemaNode parent, final OperationDefinition operation,
191             final Module module, final SchemaContext schemaContext, final boolean verboseClassComments,
192             Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
193             TypeProvider typeProvider, final boolean isAction, final BindingNamespaceType namespaceType) {
194
195         //operation name
196         final String operationName = operation.getQName().getLocalName();
197         //concrete operation name
198         final StringBuilder sb = new StringBuilder(operationName).append('_');
199         if (isAction) {
200             sb.append("Action");
201         } else {
202             sb.append("Rpc");
203         }
204         final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, sb.toString(),
205                 verboseClassComments);
206
207         final String basePackageName = interfaceBuilder.getPackageName();
208
209         interfaceBuilder.setDescription(createDescription(operation, interfaceBuilder.getFullyQualifiedName(),
210                 schemaContext, verboseClassComments, namespaceType));
211         final String operationComment = encodeAngleBrackets(operation.getDescription());
212         final MethodSignatureBuilder operationMethod = interfaceBuilder.addMethod("invoke");
213
214         //input
215         final ContainerSchemaNode input = operation.getInput();
216         final GeneratedTypeBuilder inType = resolveOperationNode(interfaceBuilder, module, operation.getInput(),
217                 basePackageName, schemaContext, operationName, verboseClassComments, typeProvider, genTypeBuilders,
218                 genCtx, true, namespaceType);
219         annotateDeprecatedIfNecessary(operation.getStatus(), inType);
220         inType.setParentTypeForBuilder(interfaceBuilder);
221         genCtx.get(module).addChildNodeType(input, inType);
222
223         //output
224         final ContainerSchemaNode output = operation.getOutput();
225         final GeneratedTypeBuilder outType = resolveOperationNode(interfaceBuilder, module, operation.getOutput(),
226                 basePackageName, schemaContext, operationName, verboseClassComments, typeProvider, genTypeBuilders,
227                 genCtx, false, namespaceType);
228         annotateDeprecatedIfNecessary(operation.getStatus(), outType);
229         outType.setParentTypeForBuilder(interfaceBuilder);
230         genCtx.get(module).addChildNodeType(output, outType);
231
232         final GeneratedType inTypeInstance = inType.toInstance();
233         operationMethod.addParameter(inTypeInstance, "input");
234
235         if (isAction) {
236             //action, routed RPC
237             checkState(parent != null, "Parent node of " + operation.getQName().getLocalName() + " can't be NULL");
238             GeneratedTypeBuilder parentType = genCtx.get(module).getChildNode(parent.getPath());
239             checkState(parentType != null, "Parent generated type for " + parent
240                     + " data schema node must have been generated already");
241             annotateDeprecatedIfNecessary(parent.getStatus(), parentType);
242
243             if (parent instanceof ListSchemaNode) {
244                 //ListAction
245                 GeneratedTransferObject keyType = null;
246                 for (MethodSignatureBuilder method : parentType.getMethodDefinitions()) {
247                     if (method.getName().equals("getKey")) {
248                         keyType = (GeneratedTransferObject) method.toInstance(parentType).getReturnType();
249                     }
250                 }
251
252                 operationMethod.addParameter(
253                         parameterizedTypeFor(KEYED_INSTANCE_IDENTIFIER, parentType, keyType), "kii");
254                 interfaceBuilder.addImplementsType(parameterizedTypeFor(LIST_ACTION, parentType, inType, outType));
255             } else {
256                 //Action
257                 GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, parentType, parentType,
258                         ((ContainerSchemaNode) parent).getChildNodes(), genCtx, schemaContext, verboseClassComments,
259                         genTypeBuilders, typeProvider, namespaceType);
260                 operationMethod.addParameter(parameterizedTypeFor(INSTANCE_IDENTIFIER, parentType), "ii");
261                 interfaceBuilder.addImplementsType(parameterizedTypeFor(ACTION, parentType, inType, outType));
262             }
263         } else {
264             //RPC
265             interfaceBuilder.addImplementsType(parameterizedTypeFor(RPC, inType, outType));
266         }
267
268         interfaceBuilder.addImplementsType(TREE_NODE);
269         operationMethod.addParameter(parameterizedTypeFor(RPC_CALLBACK, outType), "callback");
270
271         operationMethod.setComment(operationComment);
272         operationMethod.setReturnType(VOID);
273
274         return interfaceBuilder;
275     }
276
277     private static GeneratedTypeBuilder resolveOperationNode(GeneratedTypeBuilder parent, final Module module, final
278             ContainerSchemaNode operationNode, final String basePackageName, final SchemaContext schemaContext, final String
279             operationName, final boolean verboseClassComments, TypeProvider typeProvider, Map<String, Map<String,
280             GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx, final boolean isInput,
281             final BindingNamespaceType namespaceType) {
282         final GeneratedTypeBuilder nodeType = addRawInterfaceDefinition(basePackageName, operationNode, schemaContext,
283                 operationName, "", verboseClassComments, genTypeBuilders, namespaceType);
284         addImplementedInterfaceFromUses(operationNode, nodeType, genCtx);
285         nodeType.addImplementsType(parameterizedTypeFor(BindingTypes.TREE_CHILD_NODE, parent, parameterizedTypeFor
286                 (BindingTypes.ITEM, parent)));
287         if (isInput) {
288             nodeType.addImplementsType(parameterizedTypeFor(INPUT, nodeType));
289         } else {
290             nodeType.addImplementsType(parameterizedTypeFor(OUTPUT, nodeType));
291         }
292         nodeType.addImplementsType(parameterizedTypeFor(INSTANTIABLE, nodeType));
293         nodeType.addImplementsType(augmentable(nodeType));
294         GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, nodeType, nodeType, operationNode.getChildNodes(), genCtx,
295                 schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType);
296
297         final MethodSignatureBuilder nodeMethod = nodeType.addMethod("implementedInterface");
298         nodeMethod.setReturnType(parameterizedTypeFor(CLASS, nodeType));
299         nodeMethod.addAnnotation("", "Override");
300
301         return nodeType;
302     }
303 }