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