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