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