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