Merge "Changed NetconfDeviceDatastoreAdapter and NetconfDeviceTopologyAdapter to...
[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 final Logger LOG = 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
61     static final String MODULE_NAME_SUFFIX = "_module";
62     protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
63     private final ModelGenerator jsonConverter = new ModelGenerator();
64
65     // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
66     private final ObjectMapper mapper = new ObjectMapper();
67
68     protected BaseYangSwaggerGenerator() {
69         mapper.registerModule(new JsonOrgModule());
70         mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
71     }
72
73     /**
74      *
75      * @param uriInfo
76      * @param operType
77      * @return list of modules converted to swagger compliant resource list.
78      */
79     public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
80
81         ResourceList resourceList = createResourceList();
82
83         Set<Module> modules = getSortedModules(schemaContext);
84
85         List<Resource> resources = new ArrayList<>(modules.size());
86
87         LOG.info("Modules found [{}]", modules.size());
88
89         for (Module module : modules) {
90             String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
91             Resource resource = new Resource();
92             LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
93             ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
94
95             if (doc != null) {
96                 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
97                 resources.add(resource);
98             } else {
99                 LOG.debug("Could not generate doc for {},{}", module.getName(), revisionString);
100             }
101         }
102
103         resourceList.setApis(resources);
104
105         return resourceList;
106     }
107
108     protected ResourceList createResourceList() {
109         ResourceList resourceList = new ResourceList();
110         resourceList.setApiVersion(API_VERSION);
111         resourceList.setSwaggerVersion(SWAGGER_VERSION);
112         return resourceList;
113     }
114
115     protected String generatePath(UriInfo uriInfo, String name, String revision) {
116         URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
117         return uri.toASCIIString();
118     }
119
120     public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
121         Date rev = null;
122         try {
123             rev = SIMPLE_DATE_FORMAT.parse(revision);
124         } catch (ParseException e) {
125             throw new IllegalArgumentException(e);
126         }
127         Module m = schemaContext.findModuleByName(module, rev);
128         Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
129
130         return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
131     }
132
133     public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
134         String basePath = createBasePathFromUriInfo(uriInfo);
135
136         ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
137         if (doc != null) {
138             return doc;
139         }
140         return null;
141     }
142
143     protected String createBasePathFromUriInfo(UriInfo uriInfo) {
144         String portPart = "";
145         int port = uriInfo.getBaseUri().getPort();
146         if (port != -1) {
147             portPart = ":" + port;
148         }
149         String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
150                 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
151                 .toString();
152         return basePath;
153     }
154
155     public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
156         ApiDeclaration doc = createApiDeclaration(basePath);
157
158         List<Api> apis = new ArrayList<Api>();
159
160         Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
161         LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
162         for (DataSchemaNode node : dataSchemaNodes) {
163             if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
164
165                 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
166
167                 List<Parameter> pathParams = new ArrayList<Parameter>();
168                 String resourcePath = getDataStorePath("/config/", context);
169                 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
170                 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
171
172                 pathParams = new ArrayList<Parameter>();
173                 resourcePath = getDataStorePath("/operational/", context);
174                 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
175             }
176         }
177
178         Set<RpcDefinition> rpcs = m.getRpcs();
179         for (RpcDefinition rpcDefinition : rpcs) {
180             String resourcePath = getDataStorePath("/operations/", context);
181             addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
182         }
183
184         LOG.debug("Number of APIs found [{}]", apis.size());
185
186         if (!apis.isEmpty()) {
187             doc.setApis(apis);
188             JSONObject models = null;
189
190             try {
191                 models = jsonConverter.convertToJsonSchema(m, schemaContext);
192                 doc.setModels(models);
193                 if (LOG.isDebugEnabled()) {
194                     LOG.debug(mapper.writeValueAsString(doc));
195                 }
196             } catch (IOException | JSONException e) {
197                 e.printStackTrace();
198             }
199
200             return doc;
201         }
202         return null;
203     }
204
205     private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams,
206             final String resourcePath, final List<Api> apis) {
207         if (containsListOrContainer(m.getChildNodes())) {
208             final Api apiForRootPostUri = new Api();
209             apiForRootPostUri.setPath(resourcePath);
210             apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true));
211             apis.add(apiForRootPostUri);
212         }
213     }
214
215     protected ApiDeclaration createApiDeclaration(String basePath) {
216         ApiDeclaration doc = new ApiDeclaration();
217         doc.setApiVersion(API_VERSION);
218         doc.setSwaggerVersion(SWAGGER_VERSION);
219         doc.setBasePath(basePath);
220         doc.setProduces(Arrays.asList("application/json", "application/xml"));
221         return doc;
222     }
223
224     protected String getDataStorePath(String dataStore, String context) {
225         return dataStore + context;
226     }
227
228     private String generateCacheKey(Module m) {
229         return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
230     }
231
232     private String generateCacheKey(String module, String revision) {
233         return module + "(" + revision + ")";
234     }
235
236     private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
237             boolean addConfigApi) {
238
239         Api api = new Api();
240         List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
241
242         String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
243         LOG.debug("Adding path: [{}]", resourcePath);
244         api.setPath(resourcePath);
245
246         Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
247         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
248             DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
249             childSchemaNodes = dataNodeContainer.getChildNodes();
250         }
251         api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
252         apis.add(api);
253
254         for (DataSchemaNode childNode : childSchemaNodes) {
255             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
256                 // keep config and operation attributes separate.
257                 if (childNode.isConfiguration() == addConfigApi) {
258                     addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
259                 }
260             }
261         }
262
263     }
264
265     private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
266         for (DataSchemaNode child : nodes) {
267             if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
268                 return true;
269             }
270         }
271         return false;
272     }
273
274     /**
275      * @param node
276      * @param pathParams
277      * @return
278      */
279     private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
280         List<Operation> operations = new ArrayList<>();
281
282         OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
283         operations.add(getBuilder.pathParams(pathParams).build());
284
285         if (isConfig) {
286             OperationBuilder.Put putBuilder = new OperationBuilder.Put(node.getQName().getLocalName(),
287                     node.getDescription());
288             operations.add(putBuilder.pathParams(pathParams).build());
289
290             OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
291             operations.add(deleteBuilder.pathParams(pathParams).build());
292
293             if (containsListOrContainer(childSchemaNodes)) {
294                 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node,
295                         pathParams, isConfig));
296             }
297         }
298         return operations;
299     }
300
301     /**
302      * @param node
303      * @param pathParams
304      * @return
305      */
306     private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
307         List<Operation> operations = new ArrayList<>();
308         if (isConfig) {
309             OperationBuilder.Post postBuilder = new OperationBuilder.Post(name, description, dataNodeContainer);
310             operations.add(postBuilder.pathParams(pathParams).build());
311         }
312         return operations;
313     }
314
315     private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
316         ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
317         StringBuilder path = new StringBuilder();
318         String localName = resolvePathArgumentsName(schemaNode, schemaContext);
319         path.append(localName);
320
321         if ((schemaNode instanceof ListSchemaNode)) {
322             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
323             for (final QName listKey : listKeys) {
324                 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
325                 pathListParams.add(((LeafSchemaNode) _dataChildByName));
326
327                 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
328                         .toString();
329                 path.append(pathParamIdentifier);
330
331                 Parameter pathParam = new Parameter();
332                 pathParam.setName(listKey.getLocalName());
333                 pathParam.setDescription(_dataChildByName.getDescription());
334                 pathParam.setType("string");
335                 pathParam.setParamType("path");
336
337                 pathParams.add(pathParam);
338             }
339         }
340         return path.toString();
341     }
342
343     protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
344         Api rpc = new Api();
345         String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
346         rpc.setPath(resourcePath);
347
348         Operation operationSpec = new Operation();
349         operationSpec.setMethod("POST");
350         operationSpec.setNotes(rpcDefn.getDescription());
351         operationSpec.setNickname(rpcDefn.getQName().getLocalName());
352         if (rpcDefn.getOutput() != null) {
353             operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
354         }
355         if (rpcDefn.getInput() != null) {
356             Parameter payload = new Parameter();
357             payload.setParamType("body");
358             payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
359             operationSpec.setParameters(Collections.singletonList(payload));
360         }
361
362         rpc.setOperations(Arrays.asList(operationSpec));
363
364         apis.add(rpc);
365     }
366
367     protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
368         if (schemaContext == null) {
369             return new TreeSet<>();
370         }
371
372         Set<Module> modules = schemaContext.getModules();
373
374         SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
375             @Override
376             public int compare(Module o1, Module o2) {
377                 int result = o1.getName().compareTo(o2.getName());
378                 if (result == 0) {
379                     result = o1.getRevision().compareTo(o2.getRevision());
380                 }
381                 if (result == 0) {
382                     result = o1.getNamespace().compareTo(o2.getNamespace());
383                 }
384                 return result;
385             }
386         });
387         for (Module m : modules) {
388             if (m != null) {
389                 sortedModules.add(m);
390             }
391         }
392         return sortedModules;
393     }
394
395 }