Merge "Bug 5708: Schemaless netconf mount point"
[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         boolean hasAddRootPostLink = false;
176
177         Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
178         LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
179         for (DataSchemaNode node : dataSchemaNodes) {
180             if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
181                 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
182
183                 List<Parameter> pathParams = new ArrayList<>();
184                 String resourcePath;
185
186                 /*
187                  * Only when the node's config statement is true, such apis as GET/PUT/POST/DELETE config
188                  * are added for this node.
189                  */
190                 if (node.isConfiguration()) { // This node's config statement is true.
191                     resourcePath = getDataStorePath("/config/", context);
192
193                     /*
194                      * When there are two or more top container or list nodes whose config statement is true in module,
195                      * make sure that only one root post link is added for this module.
196                      */
197                     if (!hasAddRootPostLink) {
198                         LOG.debug("Has added root post link for module {}", m.getName());
199                         addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
200                         hasAddRootPostLink = true;
201                     }
202
203                     addApis(node, apis, resourcePath, pathParams, schemaContext, true);
204                 }
205
206                 pathParams = new ArrayList<>();
207                 resourcePath = getDataStorePath("/operational/", context);
208                 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
209             }
210         }
211
212         Set<RpcDefinition> rpcs = m.getRpcs();
213         for (RpcDefinition rpcDefinition : rpcs) {
214             String resourcePath = getDataStorePath("/operations/", context);
215             addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
216         }
217
218         LOG.debug("Number of APIs found [{}]", apis.size());
219
220         if (!apis.isEmpty()) {
221             doc.setApis(apis);
222             JSONObject models = null;
223
224             try {
225                 models = jsonConverter.convertToJsonSchema(m, schemaContext);
226                 doc.setModels(models);
227                 if (LOG.isDebugEnabled()) {
228                     LOG.debug(mapper.writeValueAsString(doc));
229                 }
230             } catch (IOException | JSONException e) {
231                 LOG.error("Exception occured in ModelGenerator", e);
232             }
233
234             return doc;
235         }
236         return null;
237     }
238
239     private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
240             final String resourcePath, final List<Api> apis) {
241         if (containsListOrContainer(module.getChildNodes())) {
242             final Api apiForRootPostUri = new Api();
243             apiForRootPostUri.setPath(resourcePath);
244             apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
245                     module.getDescription(), module, pathParams, true));
246             apis.add(apiForRootPostUri);
247         }
248     }
249
250     protected ApiDeclaration createApiDeclaration(String basePath) {
251         ApiDeclaration doc = new ApiDeclaration();
252         doc.setApiVersion(API_VERSION);
253         doc.setSwaggerVersion(SWAGGER_VERSION);
254         doc.setBasePath(basePath);
255         doc.setProduces(Arrays.asList("application/json", "application/xml"));
256         return doc;
257     }
258
259     protected String getDataStorePath(String dataStore, String context) {
260         return dataStore + context;
261     }
262
263     private String generateCacheKey(String module, String revision) {
264         return module + "(" + revision + ")";
265     }
266
267     private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
268             boolean addConfigApi) {
269
270         Api api = new Api();
271         List<Parameter> pathParams = new ArrayList<>(parentPathParams);
272
273         String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
274         LOG.debug("Adding path: [{}]", resourcePath);
275         api.setPath(resourcePath);
276
277         Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
278         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
279             DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
280             childSchemaNodes = dataNodeContainer.getChildNodes();
281         }
282         api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
283         apis.add(api);
284
285         for (DataSchemaNode childNode : childSchemaNodes) {
286             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
287                 // keep config and operation attributes separate.
288                 if (childNode.isConfiguration() == addConfigApi) {
289                     addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
290                 }
291             }
292         }
293
294     }
295
296     private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
297         for (DataSchemaNode child : nodes) {
298             if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
299                 return true;
300             }
301         }
302         return false;
303     }
304
305     private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
306         List<Operation> operations = new ArrayList<>();
307
308         Get getBuilder = new Get(node, isConfig);
309         operations.add(getBuilder.pathParams(pathParams).build());
310
311         if (isConfig) {
312             Put putBuilder = new Put(node.getQName().getLocalName(),
313                     node.getDescription());
314             operations.add(putBuilder.pathParams(pathParams).build());
315
316             Delete deleteBuilder = new Delete(node);
317             operations.add(deleteBuilder.pathParams(pathParams).build());
318
319             if (containsListOrContainer(childSchemaNodes)) {
320                 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
321                         (DataNodeContainer) node, pathParams, isConfig));
322             }
323         }
324         return operations;
325     }
326
327     private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
328         List<Operation> operations = new ArrayList<>();
329         if (isConfig) {
330             Post postBuilder = new Post(name, description, dataNodeContainer);
331             operations.add(postBuilder.pathParams(pathParams).build());
332         }
333         return operations;
334     }
335
336     private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
337         ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
338         StringBuilder path = new StringBuilder();
339         String localName = resolvePathArgumentsName(schemaNode, schemaContext);
340         path.append(localName);
341
342         if ((schemaNode instanceof ListSchemaNode)) {
343             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
344             for (final QName listKey : listKeys) {
345                 DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
346                 pathListParams.add(((LeafSchemaNode) dataChildByName));
347
348                 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
349                         .toString();
350                 path.append(pathParamIdentifier);
351
352                 Parameter pathParam = new Parameter();
353                 pathParam.setName(listKey.getLocalName());
354                 pathParam.setDescription(dataChildByName.getDescription());
355                 pathParam.setType("string");
356                 pathParam.setParamType("path");
357
358                 pathParams.add(pathParam);
359             }
360         }
361         return path.toString();
362     }
363
364     protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
365         Api rpc = new Api();
366         String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
367         rpc.setPath(resourcePath);
368
369         Operation operationSpec = new Operation();
370         operationSpec.setMethod("POST");
371         operationSpec.setNotes(rpcDefn.getDescription());
372         operationSpec.setNickname(rpcDefn.getQName().getLocalName());
373         if (rpcDefn.getOutput() != null) {
374             operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
375         }
376         if (rpcDefn.getInput() != null) {
377             Parameter payload = new Parameter();
378             payload.setParamType("body");
379             payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
380             operationSpec.setParameters(Collections.singletonList(payload));
381             operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
382         }
383
384         rpc.setOperations(Arrays.asList(operationSpec));
385
386         apis.add(rpc);
387     }
388
389     protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
390         if (schemaContext == null) {
391             return new TreeSet<>();
392         }
393
394         Set<Module> modules = schemaContext.getModules();
395
396         SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
397             int result = module1.getName().compareTo(module2.getName());
398             if (result == 0) {
399                 Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
400                 Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
401                 result = module1Revision.compareTo(module2Revision);
402             }
403             if (result == 0) {
404                 result = module1.getNamespace().compareTo(module2.getNamespace());
405             }
406             return result;
407         });
408         for (Module m : modules) {
409             if (m != null) {
410                 sortedModules.add(m);
411             }
412         }
413         return sortedModules;
414     }
415
416 }