2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sal.rest.doc.impl;
10 import static org.opendaylight.controller.sal.rest.doc.util.RestDocgenUtil.resolvePathArgumentsName;
12 import com.fasterxml.jackson.databind.ObjectMapper;
13 import com.fasterxml.jackson.databind.SerializationFeature;
14 import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
15 import com.google.common.base.Preconditions;
16 import java.io.IOException;
18 import java.text.DateFormat;
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.Date;
27 import java.util.List;
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.controller.sal.rest.doc.model.builder.OperationBuilder;
35 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
36 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
37 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
38 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
39 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
40 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public class BaseYangSwaggerGenerator {
55 private static Logger _logger = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
57 protected static final String API_VERSION = "1.0.0";
58 protected static final String SWAGGER_VERSION = "1.2";
59 protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
60 protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
61 private final ModelGenerator jsonConverter = new ModelGenerator();
63 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
64 private final ObjectMapper mapper = new ObjectMapper();
66 protected BaseYangSwaggerGenerator() {
67 mapper.registerModule(new JsonOrgModule());
68 mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
75 * @return list of modules converted to swagger compliant resource list.
77 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
79 ResourceList resourceList = createResourceList();
81 Set<Module> modules = getSortedModules(schemaContext);
83 List<Resource> resources = new ArrayList<>(modules.size());
85 _logger.info("Modules found [{}]", modules.size());
87 for (Module module : modules) {
88 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
89 Resource resource = new Resource();
90 _logger.debug("Working on [{},{}]...", module.getName(), revisionString);
91 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
94 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
95 resources.add(resource);
97 _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString);
101 resourceList.setApis(resources);
106 protected ResourceList createResourceList() {
107 ResourceList resourceList = new ResourceList();
108 resourceList.setApiVersion(API_VERSION);
109 resourceList.setSwaggerVersion(SWAGGER_VERSION);
113 protected String generatePath(UriInfo uriInfo, String name, String revision) {
114 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
115 return uri.toASCIIString();
118 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
121 rev = SIMPLE_DATE_FORMAT.parse(revision);
122 } catch (ParseException e) {
123 throw new IllegalArgumentException(e);
125 Module m = schemaContext.findModuleByName(module, rev);
126 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
128 return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
131 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
132 String basePath = createBasePathFromUriInfo(uriInfo);
134 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
141 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
142 String portPart = "";
143 int port = uriInfo.getBaseUri().getPort();
145 portPart = ":" + port;
147 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
148 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
153 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
154 ApiDeclaration doc = createApiDeclaration(basePath);
156 List<Api> apis = new ArrayList<Api>();
158 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
159 _logger.debug("child nodes size [{}]", dataSchemaNodes.size());
160 for (DataSchemaNode node : dataSchemaNodes) {
161 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
163 _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
165 List<Parameter> pathParams = new ArrayList<Parameter>();
166 String resourcePath = getDataStorePath("/config/", context);
167 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
169 pathParams = new ArrayList<Parameter>();
170 resourcePath = getDataStorePath("/operational/", context);
171 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
174 Set<RpcDefinition> rpcs = m.getRpcs();
175 for (RpcDefinition rpcDefinition : rpcs) {
176 String resourcePath = getDataStorePath("/operations/", context);
177 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
181 _logger.debug("Number of APIs found [{}]", apis.size());
183 if (!apis.isEmpty()) {
185 JSONObject models = null;
188 models = jsonConverter.convertToJsonSchema(m, schemaContext);
189 doc.setModels(models);
190 if (_logger.isDebugEnabled()) {
191 _logger.debug(mapper.writeValueAsString(doc));
193 } catch (IOException | JSONException e) {
202 protected ApiDeclaration createApiDeclaration(String basePath) {
203 ApiDeclaration doc = new ApiDeclaration();
204 doc.setApiVersion(API_VERSION);
205 doc.setSwaggerVersion(SWAGGER_VERSION);
206 doc.setBasePath(basePath);
207 doc.setProduces(Arrays.asList("application/json", "application/xml"));
211 protected String getDataStorePath(String dataStore, String context) {
212 return dataStore + context;
215 private String generateCacheKey(Module m) {
216 return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
219 private String generateCacheKey(String module, String revision) {
220 return module + "(" + revision + ")";
223 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
224 boolean addConfigApi) {
227 List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
229 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
230 _logger.debug("Adding path: [{}]", resourcePath);
231 api.setPath(resourcePath);
232 api.setOperations(operations(node, pathParams, addConfigApi));
234 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
235 DataNodeContainer schemaNode = (DataNodeContainer) node;
237 for (DataSchemaNode childNode : schemaNode.getChildNodes()) {
238 // We don't support going to leaf nodes today. Only lists and
240 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
241 // keep config and operation attributes separate.
242 if (childNode.isConfiguration() == addConfigApi) {
243 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
256 private List<Operation> operations(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig) {
257 List<Operation> operations = new ArrayList<>();
259 OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
260 operations.add(getBuilder.pathParams(pathParams).build());
263 OperationBuilder.Post postBuilder = new OperationBuilder.Post(node);
264 operations.add(postBuilder.pathParams(pathParams).build());
266 OperationBuilder.Put putBuilder = new OperationBuilder.Put(node);
267 operations.add(putBuilder.pathParams(pathParams).build());
269 OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
270 operations.add(deleteBuilder.pathParams(pathParams).build());
275 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
276 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
277 StringBuilder path = new StringBuilder();
278 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
279 path.append(localName);
281 if ((schemaNode instanceof ListSchemaNode)) {
282 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
283 for (final QName listKey : listKeys) {
284 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
285 pathListParams.add(((LeafSchemaNode) _dataChildByName));
287 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
289 path.append(pathParamIdentifier);
291 Parameter pathParam = new Parameter();
292 pathParam.setName(listKey.getLocalName());
293 pathParam.setDescription(_dataChildByName.getDescription());
294 pathParam.setType("string");
295 pathParam.setParamType("path");
297 pathParams.add(pathParam);
300 return path.toString();
303 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
305 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
306 rpc.setPath(resourcePath);
308 Operation operationSpec = new Operation();
309 operationSpec.setMethod("POST");
310 operationSpec.setNotes(rpcDefn.getDescription());
311 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
312 if (rpcDefn.getOutput() != null) {
313 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
315 if (rpcDefn.getInput() != null) {
316 Parameter payload = new Parameter();
317 payload.setParamType("body");
318 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
319 operationSpec.setParameters(Collections.singletonList(payload));
322 rpc.setOperations(Arrays.asList(operationSpec));
327 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
328 if (schemaContext == null) {
329 return new TreeSet<>();
332 Set<Module> modules = schemaContext.getModules();
334 SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
336 public int compare(Module o1, Module o2) {
337 int result = o1.getName().compareTo(o2.getName());
339 result = o1.getRevision().compareTo(o2.getRevision());
342 result = o1.getNamespace().compareTo(o2.getNamespace());
347 for (Module m : modules) {
349 sortedModules.add(m);
352 return sortedModules;