RPC registrations should not throw
[controller.git] / opendaylight / md-sal / sal-rest-docgen / src / main / java / org / opendaylight / controller / sal / rest / doc / impl / BaseYangSwaggerGenerator.java
1 /*
2  * Copyright (c) 2014 Brocade Communications 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 package org.opendaylight.controller.sal.rest.doc.impl;
9
10 import java.io.IOException;
11 import java.net.URI;
12 import java.text.DateFormat;
13 import java.text.ParseException;
14 import java.text.SimpleDateFormat;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.Date;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.SortedSet;
23 import java.util.TreeSet;
24
25 import javax.ws.rs.core.UriInfo;
26
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder;
30 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
31 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
32 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
33 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
34 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
35 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.fasterxml.jackson.databind.SerializationFeature;
50 import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
51 import com.google.common.base.Preconditions;
52
53 public class BaseYangSwaggerGenerator {
54
55     private static Logger _logger = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
56
57     protected static final String API_VERSION = "1.0.0";
58     protected static final String SWAGGER_VERSION = "1.2";
59     protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
60     protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
61     private final ModelGenerator jsonConverter = new ModelGenerator();
62
63     // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
64     private final ObjectMapper mapper = new ObjectMapper();
65
66     protected BaseYangSwaggerGenerator() {
67         mapper.registerModule(new JsonOrgModule());
68         mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
69     }
70
71     /**
72      *
73      * @param uriInfo
74      * @param operType
75      * @return list of modules converted to swagger compliant resource list.
76      */
77     public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext,
78             String context) {
79
80         ResourceList resourceList = createResourceList();
81
82         Set<Module> modules = getSortedModules(schemaContext);
83
84         List<Resource> resources = new ArrayList<>(modules.size());
85
86         _logger.info("Modules found [{}]", modules.size());
87
88         for (Module module : modules) {
89             String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
90
91             Resource resource = new Resource();
92             _logger.debug("Working on [{},{}]...", module.getName(), revisionString);
93             ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo,
94                     schemaContext, context);
95
96             if (doc != null) {
97                 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
98                 resources.add(resource);
99             } else {
100                 _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString);
101             }
102         }
103
104         resourceList.setApis(resources);
105
106         return resourceList;
107     }
108
109     protected ResourceList createResourceList() {
110         ResourceList resourceList = new ResourceList();
111         resourceList.setApiVersion(API_VERSION);
112         resourceList.setSwaggerVersion(SWAGGER_VERSION);
113         return resourceList;
114     }
115
116     protected String generatePath(UriInfo uriInfo, String name, String revision) {
117         URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
118         return uri.toASCIIString();
119     }
120
121     public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo,
122             SchemaContext schemaContext, String context) {
123         Date rev = null;
124         try {
125             rev = SIMPLE_DATE_FORMAT.parse(revision);
126         } catch (ParseException e) {
127             throw new IllegalArgumentException(e);
128         }
129         Module m = schemaContext.findModuleByName(module, rev);
130         Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module
131                 + "," + revision);
132
133         return getApiDeclaration(m, rev, uriInfo, schemaContext, context);
134     }
135
136     public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo,
137             SchemaContext schemaContext, String context) {
138         String basePath = createBasePathFromUriInfo(uriInfo);
139
140         ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context);
141         if (doc != null) {
142             return doc;
143         }
144         return null;
145     }
146
147     protected String createBasePathFromUriInfo(UriInfo uriInfo) {
148         String portPart = "";
149         int port = uriInfo.getBaseUri().getPort();
150         if (port != -1) {
151             portPart = ":" + port;
152         }
153         String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
154                 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/")
155                 .append(RESTCONF_CONTEXT_ROOT).toString();
156         return basePath;
157     }
158
159     public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context) {
160         ApiDeclaration doc = createApiDeclaration(basePath);
161
162         List<Api> apis = new ArrayList<Api>();
163
164         Set<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
165         _logger.debug("child nodes size [{}]", dataSchemaNodes.size());
166         for (DataSchemaNode node : dataSchemaNodes) {
167             if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
168
169                 _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node
170                         .getQName().getLocalName());
171
172                 List<Parameter> pathParams = new ArrayList<Parameter>();
173                 String resourcePath = getDataStorePath("/config/", context) + m.getName() + ":";
174                 addApis(node, apis, resourcePath, pathParams, true);
175
176                 pathParams = new ArrayList<Parameter>();
177                 resourcePath = getDataStorePath("/operational/", context) + m.getName() + ":";
178                 addApis(node, apis, resourcePath, pathParams, false);
179             }
180
181             Set<RpcDefinition> rpcs = m.getRpcs();
182             for (RpcDefinition rpcDefinition : rpcs) {
183                 String resourcePath = getDataStorePath("/operations/", context) + m.getName() + ":";
184                 addRpcs(rpcDefinition, apis, resourcePath);
185             }
186         }
187
188         _logger.debug("Number of APIs found [{}]", apis.size());
189
190         if (!apis.isEmpty()) {
191             doc.setApis(apis);
192             JSONObject models = null;
193
194             try {
195                 models = jsonConverter.convertToJsonSchema(m);
196                 doc.setModels(models);
197                 if (_logger.isDebugEnabled()) {
198                     _logger.debug(mapper.writeValueAsString(doc));
199                 }
200             } catch (IOException | JSONException e) {
201                 e.printStackTrace();
202             }
203
204             return doc;
205         }
206         return null;
207     }
208
209     protected ApiDeclaration createApiDeclaration(String basePath) {
210         ApiDeclaration doc = new ApiDeclaration();
211         doc.setApiVersion(API_VERSION);
212         doc.setSwaggerVersion(SWAGGER_VERSION);
213         doc.setBasePath(basePath);
214         doc.setProduces(Arrays.asList("application/json", "application/xml"));
215         return doc;
216     }
217
218     protected String getDataStorePath(String dataStore, String context) {
219         return dataStore + context;
220     }
221
222     private String generateCacheKey(Module m) {
223         return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
224     }
225
226     private String generateCacheKey(String module, String revision) {
227         return module + "(" + revision + ")";
228     }
229
230     private void addApis(DataSchemaNode node, List<Api> apis, String parentPath,
231             List<Parameter> parentPathParams, boolean addConfigApi) {
232
233         Api api = new Api();
234         List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
235
236         String resourcePath = parentPath + createPath(node, pathParams) + "/";
237         _logger.debug("Adding path: [{}]", resourcePath);
238         api.setPath(resourcePath);
239         api.setOperations(operations(node, pathParams, addConfigApi));
240         apis.add(api);
241         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
242             DataNodeContainer schemaNode = (DataNodeContainer) node;
243             Set<DataSchemaNode> dataSchemaNodes = schemaNode.getChildNodes();
244
245             for (DataSchemaNode childNode : dataSchemaNodes) {
246                 // We don't support going to leaf nodes today. Only lists and
247                 // containers.
248                 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
249                     // keep config and operation attributes separate.
250                     if (childNode.isConfiguration() == addConfigApi) {
251                         addApis(childNode, apis, resourcePath, pathParams, addConfigApi);
252                     }
253                 }
254             }
255         }
256
257     }
258
259     /**
260      * @param node
261      * @param pathParams
262      * @return
263      */
264     private List<Operation> operations(DataSchemaNode node, List<Parameter> pathParams,
265             boolean isConfig) {
266         List<Operation> operations = new ArrayList<>();
267
268         OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
269         operations.add(getBuilder.pathParams(pathParams).build());
270
271         if (isConfig) {
272             OperationBuilder.Post postBuilder = new OperationBuilder.Post(node);
273             operations.add(postBuilder.pathParams(pathParams).build());
274
275             OperationBuilder.Put putBuilder = new OperationBuilder.Put(node);
276             operations.add(putBuilder.pathParams(pathParams).build());
277
278             OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
279             operations.add(deleteBuilder.pathParams(pathParams).build());
280         }
281         return operations;
282     }
283
284     private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams) {
285         ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
286         StringBuilder path = new StringBuilder();
287         QName _qName = schemaNode.getQName();
288         String localName = _qName.getLocalName();
289         path.append(localName);
290
291         if ((schemaNode instanceof ListSchemaNode)) {
292             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
293             for (final QName listKey : listKeys) {
294                 {
295                     DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode)
296                             .getDataChildByName(listKey);
297                     pathListParams.add(((LeafSchemaNode) _dataChildByName));
298
299                     String pathParamIdentifier = new StringBuilder("/{")
300                             .append(listKey.getLocalName()).append("}").toString();
301                     path.append(pathParamIdentifier);
302
303                     Parameter pathParam = new Parameter();
304                     pathParam.setName(listKey.getLocalName());
305                     pathParam.setDescription(_dataChildByName.getDescription());
306                     pathParam.setType("string");
307                     pathParam.setParamType("path");
308
309                     pathParams.add(pathParam);
310                 }
311             }
312         }
313         return path.toString();
314     }
315
316     protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath) {
317         Api rpc = new Api();
318         String resourcePath = parentPath + rpcDefn.getQName().getLocalName();
319         rpc.setPath(resourcePath);
320
321         Operation operationSpec = new Operation();
322         operationSpec.setMethod("POST");
323         operationSpec.setNotes(rpcDefn.getDescription());
324         operationSpec.setNickname(rpcDefn.getQName().getLocalName());
325         if (rpcDefn.getOutput() != null) {
326             operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
327         }
328         if (rpcDefn.getInput() != null) {
329             Parameter payload = new Parameter();
330             payload.setParamType("body");
331             payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
332             operationSpec.setParameters(Collections.singletonList(payload));
333         }
334
335         rpc.setOperations(Arrays.asList(operationSpec));
336
337         apis.add(rpc);
338     }
339
340     protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
341         if (schemaContext == null) {
342             return new TreeSet<>();
343         }
344
345         Set<Module> modules = schemaContext.getModules();
346
347         SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
348             @Override
349             public int compare(Module o1, Module o2) {
350                 int result = o1.getName().compareTo(o2.getName());
351                 if (result == 0) {
352                     result = o1.getRevision().compareTo(o2.getRevision());
353                 }
354                 if (result == 0) {
355                     result = o1.getNamespace().compareTo(o2.getNamespace());
356                 }
357                 return result;
358             }
359         });
360         for (Module m : modules) {
361             if (m != null) {
362                 sortedModules.add(m);
363             }
364         }
365         return sortedModules;
366     }
367 }