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