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