Bug 6382 - add apidoc for latest restconf draft
[netconf.git] / restconf / sal-rest-docgen / src / main / java / org / opendaylight / netconf / 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.netconf.sal.rest.doc.impl;
9
10 import static org.opendaylight.netconf.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.Calendar;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Date;
27 import java.util.GregorianCalendar;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import javax.ws.rs.core.UriInfo;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
36 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Delete;
37 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Get;
38 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
39 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Put;
40 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
41 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
42 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
43 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
44 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
45 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
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.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 public class BaseYangSwaggerGenerator {
59
60     private static final Logger LOG = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
61
62     protected static final String API_VERSION = "1.0.0";
63     protected static final String SWAGGER_VERSION = "1.2";
64     protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
65     private static final String RESTCONF_DRAFT = "17";
66
67     static final String MODULE_NAME_SUFFIX = "_module";
68     protected static final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
69     private final ModelGenerator jsonConverter = new ModelGenerator();
70
71     // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
72     private final ObjectMapper mapper = new ObjectMapper();
73     private static boolean newDraft;
74
75     protected BaseYangSwaggerGenerator() {
76         mapper.registerModule(new JsonOrgModule());
77         mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
78     }
79
80     /**
81      * Return list of modules converted to swagger compliant resource list.
82      */
83     public ResourceList getResourceListing(final UriInfo uriInfo, final SchemaContext schemaContext, final String context) {
84
85         final ResourceList resourceList = createResourceList();
86
87         final Set<Module> modules = getSortedModules(schemaContext);
88
89         final List<Resource> resources = new ArrayList<>(modules.size());
90
91         LOG.info("Modules found [{}]", modules.size());
92
93         for (final Module module : modules) {
94             final String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
95             final Resource resource = new Resource();
96             LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
97             final ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
98
99             if (doc != null) {
100                 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
101                 resources.add(resource);
102             } else {
103                 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
104             }
105         }
106
107         resourceList.setApis(resources);
108
109         return resourceList;
110     }
111
112     protected ResourceList createResourceList() {
113         final ResourceList resourceList = new ResourceList();
114         resourceList.setApiVersion(API_VERSION);
115         resourceList.setSwaggerVersion(SWAGGER_VERSION);
116         return resourceList;
117     }
118
119     protected String generatePath(final UriInfo uriInfo, final String name, final String revision) {
120         final URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
121         return uri.toASCIIString();
122     }
123
124     public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo, final SchemaContext schemaContext, final String context) {
125         Date rev = null;
126
127         try {
128             if (revision != null && !revision.equals("0000-00-00")) {
129                 rev = SIMPLE_DATE_FORMAT.parse(revision);
130             }
131         } catch (final ParseException e) {
132             throw new IllegalArgumentException(e);
133         }
134
135         if (rev != null) {
136             final Calendar cal = new GregorianCalendar();
137
138             cal.setTime(rev);
139
140             if (cal.get(Calendar.YEAR) < 1970) {
141                 rev = null;
142             }
143         }
144
145         final Module module = schemaContext.findModuleByName(moduleName, rev);
146         Preconditions.checkArgument(module != null,
147                 "Could not find module by name,revision: " + moduleName + "," + revision);
148
149         return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
150     }
151
152     public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo, final String context, final SchemaContext schemaContext) {
153         final String basePath = createBasePathFromUriInfo(uriInfo);
154
155         final ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
156         if (doc != null) {
157             return doc;
158         }
159         return null;
160     }
161
162     protected String createBasePathFromUriInfo(final UriInfo uriInfo) {
163         String portPart = "";
164         final int port = uriInfo.getBaseUri().getPort();
165         if (port != -1) {
166             portPart = ":" + port;
167         }
168         final String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
169                 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
170                 .toString();
171         return basePath;
172     }
173
174     public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath, final String context, final SchemaContext schemaContext) {
175         final ApiDeclaration doc = createApiDeclaration(basePath);
176
177         final List<Api> apis = new ArrayList<>();
178         boolean hasAddRootPostLink = false;
179
180         final Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
181         LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
182         for (final DataSchemaNode node : dataSchemaNodes) {
183             if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
184                 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
185
186                 List<Parameter> pathParams = new ArrayList<>();
187                 String resourcePath;
188
189                 /*
190                  * Only when the node's config statement is true, such apis as GET/PUT/POST/DELETE config
191                  * are added for this node.
192                  */
193                 if (node.isConfiguration()) { // This node's config statement is true.
194                     resourcePath = getDataStorePath("config", context);
195
196                     /*
197                      * When there are two or more top container or list nodes whose config statement is true in module,
198                      * make sure that only one root post link is added for this module.
199                      */
200                     if (!hasAddRootPostLink) {
201                         LOG.debug("Has added root post link for module {}", m.getName());
202                         addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, "config", apis);
203
204                         hasAddRootPostLink = true;
205                     }
206
207                     addApis(node, apis, resourcePath, pathParams, schemaContext, true, m.getName(), "config");
208                 }
209                 pathParams = new ArrayList<>();
210                 resourcePath = getDataStorePath("operational", context);
211
212                 addApis(node, apis, resourcePath, pathParams, schemaContext, false, m.getName(), "operational");
213             }
214         }
215
216         final Set<RpcDefinition> rpcs = m.getRpcs();
217         for (final RpcDefinition rpcDefinition : rpcs) {
218             final String resourcePath;
219             resourcePath = getDataStorePath("operations", context);
220
221             addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
222         }
223
224         LOG.debug("Number of APIs found [{}]", apis.size());
225
226         if (!apis.isEmpty()) {
227             doc.setApis(apis);
228             JSONObject models = null;
229
230             try {
231                 models = jsonConverter.convertToJsonSchema(m, schemaContext);
232                 doc.setModels(models);
233                 if (LOG.isDebugEnabled()) {
234                     LOG.debug(mapper.writeValueAsString(doc));
235                 }
236             } catch (IOException | JSONException e) {
237                 LOG.error("Exception occured in ModelGenerator", e);
238             }
239
240             return doc;
241         }
242         return null;
243     }
244
245     private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
246                                  final String resourcePath, final String dataStore, final List<Api> apis) {
247         if (containsListOrContainer(module.getChildNodes())) {
248             final Api apiForRootPostUri = new Api();
249             apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
250             apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
251                     module.getDescription(), module, pathParams, true, ""));
252             apis.add(apiForRootPostUri);
253         }
254     }
255
256     protected ApiDeclaration createApiDeclaration(final String basePath) {
257         final ApiDeclaration doc = new ApiDeclaration();
258         doc.setApiVersion(API_VERSION);
259         doc.setSwaggerVersion(SWAGGER_VERSION);
260         doc.setBasePath(basePath);
261         doc.setProduces(Arrays.asList("application/json", "application/xml"));
262         return doc;
263     }
264
265     protected String getDataStorePath(final String dataStore, final String context) {
266         if (newDraft) {
267             if ("config".contains(dataStore) || "operational".contains(dataStore)) {
268                 return "/" + RESTCONF_DRAFT + "/data" + context;
269             } else {
270                 return "/" + RESTCONF_DRAFT + "/operations" + context;
271             }
272         } else {
273             return "/" + dataStore + context;
274         }
275     }
276
277     private String generateCacheKey(final String module, final String revision) {
278         return module + "(" + revision + ")";
279     }
280
281     private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath, final List<Parameter> parentPathParams,
282                          final SchemaContext schemaContext, final boolean addConfigApi, final String parentName, final String dataStore) {
283         final Api api = new Api();
284         final List<Parameter> pathParams = new ArrayList<>(parentPathParams);
285
286         final String resourcePath = parentPath + "/" + createPath(node, pathParams, schemaContext);
287         LOG.debug("Adding path: [{}]", resourcePath);
288         api.setPath(resourcePath.concat(getContent(dataStore)));
289
290         Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
291         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
292             final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
293             childSchemaNodes = dataNodeContainer.getChildNodes();
294         }
295         api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes, parentName));
296         apis.add(api);
297
298         for (final DataSchemaNode childNode : childSchemaNodes) {
299             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
300                 // keep config and operation attributes separate.
301                 if (childNode.isConfiguration() == addConfigApi) {
302                     final String newParent = parentName + "/" + node.getQName().getLocalName();
303                     addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi, newParent, dataStore);
304                 }
305             }
306         }
307     }
308
309     protected static String getContent(final String dataStore) {
310         if (newDraft) {
311             if ("operational".contains(dataStore)) {
312                 return "?content=nonconfig";
313             } else if ("config".contains(dataStore)) {
314                 return "?content=config";
315             } else {
316                 return "";
317             }
318         } else {
319             return "";
320         }
321     }
322     private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
323         for (final DataSchemaNode child : nodes) {
324             if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
325                 return true;
326             }
327         }
328         return false;
329     }
330
331     private List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams, final boolean isConfig,
332                                       final Iterable<DataSchemaNode> childSchemaNodes, final String parentName) {
333         final List<Operation> operations = new ArrayList<>();
334
335         final Get getBuilder = new Get(node, isConfig);
336         operations.add(getBuilder.pathParams(pathParams).build());
337
338         if (isConfig) {
339             final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName);
340             operations.add(putBuilder.pathParams(pathParams).build());
341
342             final Delete deleteBuilder = new Delete(node);
343             operations.add(deleteBuilder.pathParams(pathParams).build());
344
345             if (containsListOrContainer(childSchemaNodes)) {
346                 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
347                         (DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
348             }
349         }
350         return operations;
351     }
352
353     private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer,
354                                           final List<Parameter> pathParams, final boolean isConfig, final String parentName) {
355         final List<Operation> operations = new ArrayList<>();
356         if (isConfig) {
357             final Post postBuilder = new Post(name, parentName + name, description, dataNodeContainer);
358             operations.add(postBuilder.pathParams(pathParams).build());
359         }
360         return operations;
361     }
362
363     private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams, final SchemaContext schemaContext) {
364         final ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
365         final StringBuilder path = new StringBuilder();
366         final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
367         path.append(localName);
368
369         if ((schemaNode instanceof ListSchemaNode)) {
370             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
371             StringBuilder keyBuilder = null;
372             if (newDraft) {
373                 keyBuilder = new StringBuilder("=");
374             }
375
376             for (final QName listKey : listKeys) {
377                 final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
378                 pathListParams.add(((LeafSchemaNode) dataChildByName));
379                 final String pathParamIdentifier;
380                 if (newDraft) {
381                     pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}")
382                             .toString();
383                 } else {
384                     pathParamIdentifier = "/{" + listKey.getLocalName() + "}";
385                 }
386                 path.append(pathParamIdentifier);
387
388                 final Parameter pathParam = new Parameter();
389                 pathParam.setName(listKey.getLocalName());
390                 pathParam.setDescription(dataChildByName.getDescription());
391                 pathParam.setType("string");
392                 pathParam.setParamType("path");
393
394                 pathParams.add(pathParam);
395                 if (newDraft) {
396                     keyBuilder = new StringBuilder(",");
397                 }
398             }
399         }
400         return path.toString();
401     }
402
403     protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath, final SchemaContext schemaContext) {
404         final Api rpc = new Api();
405         final String resourcePath = parentPath + "/" + resolvePathArgumentsName(rpcDefn, schemaContext);
406         rpc.setPath(resourcePath);
407
408         final Operation operationSpec = new Operation();
409         operationSpec.setMethod("POST");
410         operationSpec.setNotes(rpcDefn.getDescription());
411         operationSpec.setNickname(rpcDefn.getQName().getLocalName());
412         if (rpcDefn.getOutput() != null) {
413             operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP);
414         }
415         if (rpcDefn.getInput() != null) {
416             final Parameter payload = new Parameter();
417             payload.setParamType("body");
418             payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input" + OperationBuilder.TOP);
419             operationSpec.setParameters(Collections.singletonList(payload));
420             operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
421         }
422
423         rpc.setOperations(Arrays.asList(operationSpec));
424
425         apis.add(rpc);
426     }
427
428     protected SortedSet<Module> getSortedModules(final SchemaContext schemaContext) {
429         if (schemaContext == null) {
430             return new TreeSet<>();
431         }
432
433         final Set<Module> modules = schemaContext.getModules();
434
435         final SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
436             int result = module1.getName().compareTo(module2.getName());
437             if (result == 0) {
438                 final Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
439                 final Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
440                 result = module1Revision.compareTo(module2Revision);
441             }
442             if (result == 0) {
443                 result = module1.getNamespace().compareTo(module2.getNamespace());
444             }
445             return result;
446         });
447         for (final Module m : modules) {
448             if (m != null) {
449                 sortedModules.add(m);
450             }
451         }
452         return sortedModules;
453     }
454
455     public void setDraft(final boolean draft) {
456         this.newDraft = draft;
457     }
458 }