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