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