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