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";
61 static final String MODULE_NAME_SUFFIX = "_module";
62 protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
63 private final ModelGenerator jsonConverter = new ModelGenerator();
65 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
66 private final ObjectMapper mapper = new ObjectMapper();
68 protected BaseYangSwaggerGenerator() {
69 mapper.registerModule(new JsonOrgModule());
70 mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
77 * @return list of modules converted to swagger compliant resource list.
79 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
81 ResourceList resourceList = createResourceList();
83 Set<Module> modules = getSortedModules(schemaContext);
85 List<Resource> resources = new ArrayList<>(modules.size());
87 _logger.info("Modules found [{}]", modules.size());
89 for (Module module : modules) {
90 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
91 Resource resource = new Resource();
92 _logger.debug("Working on [{},{}]...", module.getName(), revisionString);
93 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
96 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
97 resources.add(resource);
99 _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString);
103 resourceList.setApis(resources);
108 protected ResourceList createResourceList() {
109 ResourceList resourceList = new ResourceList();
110 resourceList.setApiVersion(API_VERSION);
111 resourceList.setSwaggerVersion(SWAGGER_VERSION);
115 protected String generatePath(UriInfo uriInfo, String name, String revision) {
116 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
117 return uri.toASCIIString();
120 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
123 rev = SIMPLE_DATE_FORMAT.parse(revision);
124 } catch (ParseException e) {
125 throw new IllegalArgumentException(e);
127 Module m = schemaContext.findModuleByName(module, rev);
128 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
130 return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
133 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
134 String basePath = createBasePathFromUriInfo(uriInfo);
136 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
143 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
144 String portPart = "";
145 int port = uriInfo.getBaseUri().getPort();
147 portPart = ":" + port;
149 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
150 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
155 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
156 ApiDeclaration doc = createApiDeclaration(basePath);
158 List<Api> apis = new ArrayList<Api>();
160 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
161 _logger.debug("child nodes size [{}]", dataSchemaNodes.size());
162 for (DataSchemaNode node : dataSchemaNodes) {
163 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
165 _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
167 List<Parameter> pathParams = new ArrayList<Parameter>();
168 String resourcePath = getDataStorePath("/config/", context);
169 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
170 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
172 pathParams = new ArrayList<Parameter>();
173 resourcePath = getDataStorePath("/operational/", context);
174 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
178 Set<RpcDefinition> rpcs = m.getRpcs();
179 for (RpcDefinition rpcDefinition : rpcs) {
180 String resourcePath = getDataStorePath("/operations/", context);
181 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
184 _logger.debug("Number of APIs found [{}]", apis.size());
186 if (!apis.isEmpty()) {
188 JSONObject models = null;
191 models = jsonConverter.convertToJsonSchema(m, schemaContext);
192 doc.setModels(models);
193 if (_logger.isDebugEnabled()) {
194 _logger.debug(mapper.writeValueAsString(doc));
196 } catch (IOException | JSONException e) {
205 private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams,
206 final String resourcePath, final List<Api> apis) {
207 if (containsListOrContainer(m.getChildNodes())) {
208 final Api apiForRootPostUri = new Api();
209 apiForRootPostUri.setPath(resourcePath);
210 apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true));
211 apis.add(apiForRootPostUri);
215 protected ApiDeclaration createApiDeclaration(String basePath) {
216 ApiDeclaration doc = new ApiDeclaration();
217 doc.setApiVersion(API_VERSION);
218 doc.setSwaggerVersion(SWAGGER_VERSION);
219 doc.setBasePath(basePath);
220 doc.setProduces(Arrays.asList("application/json", "application/xml"));
224 protected String getDataStorePath(String dataStore, String context) {
225 return dataStore + context;
228 private String generateCacheKey(Module m) {
229 return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
232 private String generateCacheKey(String module, String revision) {
233 return module + "(" + revision + ")";
236 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
237 boolean addConfigApi) {
240 List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
242 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
243 _logger.debug("Adding path: [{}]", resourcePath);
244 api.setPath(resourcePath);
246 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
247 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
248 DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
249 childSchemaNodes = dataNodeContainer.getChildNodes();
251 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
254 for (DataSchemaNode childNode : childSchemaNodes) {
255 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
256 // keep config and operation attributes separate.
257 if (childNode.isConfiguration() == addConfigApi) {
258 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
265 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
266 for (DataSchemaNode child : nodes) {
267 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
279 private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
280 List<Operation> operations = new ArrayList<>();
282 OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
283 operations.add(getBuilder.pathParams(pathParams).build());
286 OperationBuilder.Put putBuilder = new OperationBuilder.Put(node.getQName().getLocalName(),
287 node.getDescription());
288 operations.add(putBuilder.pathParams(pathParams).build());
290 OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
291 operations.add(deleteBuilder.pathParams(pathParams).build());
293 if (containsListOrContainer(childSchemaNodes)) {
294 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node,
295 pathParams, isConfig));
306 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
307 List<Operation> operations = new ArrayList<>();
309 OperationBuilder.Post postBuilder = new OperationBuilder.Post(name, description, dataNodeContainer);
310 operations.add(postBuilder.pathParams(pathParams).build());
315 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
316 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
317 StringBuilder path = new StringBuilder();
318 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
319 path.append(localName);
321 if ((schemaNode instanceof ListSchemaNode)) {
322 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
323 for (final QName listKey : listKeys) {
324 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
325 pathListParams.add(((LeafSchemaNode) _dataChildByName));
327 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
329 path.append(pathParamIdentifier);
331 Parameter pathParam = new Parameter();
332 pathParam.setName(listKey.getLocalName());
333 pathParam.setDescription(_dataChildByName.getDescription());
334 pathParam.setType("string");
335 pathParam.setParamType("path");
337 pathParams.add(pathParam);
340 return path.toString();
343 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
345 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
346 rpc.setPath(resourcePath);
348 Operation operationSpec = new Operation();
349 operationSpec.setMethod("POST");
350 operationSpec.setNotes(rpcDefn.getDescription());
351 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
352 if (rpcDefn.getOutput() != null) {
353 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
355 if (rpcDefn.getInput() != null) {
356 Parameter payload = new Parameter();
357 payload.setParamType("body");
358 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
359 operationSpec.setParameters(Collections.singletonList(payload));
362 rpc.setOperations(Arrays.asList(operationSpec));
367 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
368 if (schemaContext == null) {
369 return new TreeSet<>();
372 Set<Module> modules = schemaContext.getModules();
374 SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
376 public int compare(Module o1, Module o2) {
377 int result = o1.getName().compareTo(o2.getName());
379 result = o1.getRevision().compareTo(o2.getRevision());
382 result = o1.getNamespace().compareTo(o2.getNamespace());
387 for (Module m : modules) {
389 sortedModules.add(m);
392 return sortedModules;