Delete netconf
[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 static org.opendaylight.controller.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.controller.sal.rest.doc.model.builder.OperationBuilder;
36 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
37 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
38 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
39 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
40 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
41 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.Module;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class BaseYangSwaggerGenerator {
55
56     private static final Logger LOG = 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
62     static final String MODULE_NAME_SUFFIX = "_module";
63     protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
64     private final ModelGenerator jsonConverter = new ModelGenerator();
65
66     // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
67     private final ObjectMapper mapper = new ObjectMapper();
68
69     protected BaseYangSwaggerGenerator() {
70         mapper.registerModule(new JsonOrgModule());
71         mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
72     }
73
74     /**
75      *
76      * @param uriInfo
77      * @param operType
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.debug("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 module, 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 m = schemaContext.findModuleByName(module, rev);
143         Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
144
145         return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
146     }
147
148     public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
149         String basePath = createBasePathFromUriInfo(uriInfo);
150
151         ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
152         if (doc != null) {
153             return doc;
154         }
155         return null;
156     }
157
158     protected String createBasePathFromUriInfo(UriInfo uriInfo) {
159         String portPart = "";
160         int port = uriInfo.getBaseUri().getPort();
161         if (port != -1) {
162             portPart = ":" + port;
163         }
164         String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
165                 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
166                 .toString();
167         return basePath;
168     }
169
170     public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
171         ApiDeclaration doc = createApiDeclaration(basePath);
172
173         List<Api> apis = new ArrayList<Api>();
174
175         Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
176         LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
177         for (DataSchemaNode node : dataSchemaNodes) {
178             if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
179
180                 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
181
182                 List<Parameter> pathParams = new ArrayList<Parameter>();
183                 String resourcePath = getDataStorePath("/config/", context);
184                 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
185                 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
186
187                 pathParams = new ArrayList<Parameter>();
188                 resourcePath = getDataStorePath("/operational/", context);
189                 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
190             }
191         }
192
193         Set<RpcDefinition> rpcs = m.getRpcs();
194         for (RpcDefinition rpcDefinition : rpcs) {
195             String resourcePath = getDataStorePath("/operations/", context);
196             addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
197         }
198
199         LOG.debug("Number of APIs found [{}]", apis.size());
200
201         if (!apis.isEmpty()) {
202             doc.setApis(apis);
203             JSONObject models = null;
204
205             try {
206                 models = jsonConverter.convertToJsonSchema(m, schemaContext);
207                 doc.setModels(models);
208                 if (LOG.isDebugEnabled()) {
209                     LOG.debug(mapper.writeValueAsString(doc));
210                 }
211             } catch (IOException | JSONException e) {
212                 e.printStackTrace();
213             }
214
215             return doc;
216         }
217         return null;
218     }
219
220     private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams,
221             final String resourcePath, final List<Api> apis) {
222         if (containsListOrContainer(m.getChildNodes())) {
223             final Api apiForRootPostUri = new Api();
224             apiForRootPostUri.setPath(resourcePath);
225             apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true));
226             apis.add(apiForRootPostUri);
227         }
228     }
229
230     protected ApiDeclaration createApiDeclaration(String basePath) {
231         ApiDeclaration doc = new ApiDeclaration();
232         doc.setApiVersion(API_VERSION);
233         doc.setSwaggerVersion(SWAGGER_VERSION);
234         doc.setBasePath(basePath);
235         doc.setProduces(Arrays.asList("application/json", "application/xml"));
236         return doc;
237     }
238
239     protected String getDataStorePath(String dataStore, String context) {
240         return dataStore + context;
241     }
242
243     private String generateCacheKey(Module m) {
244         return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
245     }
246
247     private String generateCacheKey(String module, String revision) {
248         return module + "(" + revision + ")";
249     }
250
251     private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
252             boolean addConfigApi) {
253
254         Api api = new Api();
255         List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
256
257         String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
258         LOG.debug("Adding path: [{}]", resourcePath);
259         api.setPath(resourcePath);
260
261         Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
262         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
263             DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
264             childSchemaNodes = dataNodeContainer.getChildNodes();
265         }
266         api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
267         apis.add(api);
268
269         for (DataSchemaNode childNode : childSchemaNodes) {
270             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
271                 // keep config and operation attributes separate.
272                 if (childNode.isConfiguration() == addConfigApi) {
273                     addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
274                 }
275             }
276         }
277
278     }
279
280     private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
281         for (DataSchemaNode child : nodes) {
282             if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
283                 return true;
284             }
285         }
286         return false;
287     }
288
289     /**
290      * @param node
291      * @param pathParams
292      * @return
293      */
294     private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
295         List<Operation> operations = new ArrayList<>();
296
297         OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
298         operations.add(getBuilder.pathParams(pathParams).build());
299
300         if (isConfig) {
301             OperationBuilder.Put putBuilder = new OperationBuilder.Put(node.getQName().getLocalName(),
302                     node.getDescription());
303             operations.add(putBuilder.pathParams(pathParams).build());
304
305             OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
306             operations.add(deleteBuilder.pathParams(pathParams).build());
307
308             if (containsListOrContainer(childSchemaNodes)) {
309                 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node,
310                         pathParams, isConfig));
311             }
312         }
313         return operations;
314     }
315
316     /**
317      * @param node
318      * @param pathParams
319      * @return
320      */
321     private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
322         List<Operation> operations = new ArrayList<>();
323         if (isConfig) {
324             OperationBuilder.Post postBuilder = new OperationBuilder.Post(name, description, dataNodeContainer);
325             operations.add(postBuilder.pathParams(pathParams).build());
326         }
327         return operations;
328     }
329
330     private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
331         ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
332         StringBuilder path = new StringBuilder();
333         String localName = resolvePathArgumentsName(schemaNode, schemaContext);
334         path.append(localName);
335
336         if ((schemaNode instanceof ListSchemaNode)) {
337             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
338             for (final QName listKey : listKeys) {
339                 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
340                 pathListParams.add(((LeafSchemaNode) _dataChildByName));
341
342                 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
343                         .toString();
344                 path.append(pathParamIdentifier);
345
346                 Parameter pathParam = new Parameter();
347                 pathParam.setName(listKey.getLocalName());
348                 pathParam.setDescription(_dataChildByName.getDescription());
349                 pathParam.setType("string");
350                 pathParam.setParamType("path");
351
352                 pathParams.add(pathParam);
353             }
354         }
355         return path.toString();
356     }
357
358     protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
359         Api rpc = new Api();
360         String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
361         rpc.setPath(resourcePath);
362
363         Operation operationSpec = new Operation();
364         operationSpec.setMethod("POST");
365         operationSpec.setNotes(rpcDefn.getDescription());
366         operationSpec.setNickname(rpcDefn.getQName().getLocalName());
367         if (rpcDefn.getOutput() != null) {
368             operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
369         }
370         if (rpcDefn.getInput() != null) {
371             Parameter payload = new Parameter();
372             payload.setParamType("body");
373             payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
374             operationSpec.setParameters(Collections.singletonList(payload));
375             operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
376         }
377
378         rpc.setOperations(Arrays.asList(operationSpec));
379
380         apis.add(rpc);
381     }
382
383     protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
384         if (schemaContext == null) {
385             return new TreeSet<>();
386         }
387
388         Set<Module> modules = schemaContext.getModules();
389
390         SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
391             @Override
392             public int compare(Module module1, Module module2) {
393                 int result = module1.getName().compareTo(module2.getName());
394                 if (result == 0) {
395                     Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
396                     Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
397                     result = module1Revision.compareTo(module2Revision);
398                 }
399                 if (result == 0) {
400                     result = module1.getNamespace().compareTo(module2.getNamespace());
401                 }
402                 return result;
403             }
404         });
405         for (Module m : modules) {
406             if (m != null) {
407                 sortedModules.add(m);
408             }
409         }
410         return sortedModules;
411     }
412
413 }