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 java.io.IOException;
12 import java.text.DateFormat;
13 import java.text.ParseException;
14 import java.text.SimpleDateFormat;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Comparator;
20 import java.util.Date;
21 import java.util.List;
23 import java.util.SortedSet;
24 import java.util.TreeSet;
26 import javax.ws.rs.core.UriInfo;
28 import org.json.JSONException;
29 import org.json.JSONObject;
30 import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder;
31 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
32 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
33 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
34 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
35 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
36 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.Module;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.fasterxml.jackson.databind.ObjectMapper;
50 import com.fasterxml.jackson.databind.SerializationFeature;
51 import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
52 import com.google.common.base.Preconditions;
54 public class BaseYangSwaggerGenerator {
56 private static Logger _logger = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
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 protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
62 private final ModelGenerator jsonConverter = new ModelGenerator();
64 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
65 private final ObjectMapper mapper = new ObjectMapper();
67 protected BaseYangSwaggerGenerator() {
68 mapper.registerModule(new JsonOrgModule());
69 mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
76 * @return list of modules converted to swagger compliant resource list.
78 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext,
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());
92 Resource resource = new Resource();
93 _logger.debug("Working on [{},{}]...", module.getName(), revisionString);
94 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo,
95 schemaContext, context);
98 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
99 resources.add(resource);
101 _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString);
105 resourceList.setApis(resources);
110 protected ResourceList createResourceList() {
111 ResourceList resourceList = new ResourceList();
112 resourceList.setApiVersion(API_VERSION);
113 resourceList.setSwaggerVersion(SWAGGER_VERSION);
117 protected String generatePath(UriInfo uriInfo, String name, String revision) {
118 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
119 return uri.toASCIIString();
122 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo,
123 SchemaContext schemaContext, String context) {
126 rev = SIMPLE_DATE_FORMAT.parse(revision);
127 } catch (ParseException e) {
128 throw new IllegalArgumentException(e);
130 Module m = schemaContext.findModuleByName(module, rev);
131 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module
134 return getApiDeclaration(m, rev, uriInfo, schemaContext, context);
137 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo,
138 SchemaContext schemaContext, String context) {
139 String basePath = createBasePathFromUriInfo(uriInfo);
141 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context);
148 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
149 String portPart = "";
150 int port = uriInfo.getBaseUri().getPort();
152 portPart = ":" + port;
154 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
155 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/")
156 .append(RESTCONF_CONTEXT_ROOT).toString();
160 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context) {
161 ApiDeclaration doc = createApiDeclaration(basePath);
163 List<Api> apis = new ArrayList<Api>();
165 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
166 _logger.debug("child nodes size [{}]", dataSchemaNodes.size());
167 for (DataSchemaNode node : dataSchemaNodes) {
168 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
170 _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node
171 .getQName().getLocalName());
173 List<Parameter> pathParams = new ArrayList<Parameter>();
174 String resourcePath = getDataStorePath("/config/", context) + m.getName() + ":";
175 addApis(node, apis, resourcePath, pathParams, true);
177 pathParams = new ArrayList<Parameter>();
178 resourcePath = getDataStorePath("/operational/", context) + m.getName() + ":";
179 addApis(node, apis, resourcePath, pathParams, false);
182 Set<RpcDefinition> rpcs = m.getRpcs();
183 for (RpcDefinition rpcDefinition : rpcs) {
184 String resourcePath = getDataStorePath("/operations/", context) + m.getName() + ":";
185 addRpcs(rpcDefinition, apis, resourcePath);
189 _logger.debug("Number of APIs found [{}]", apis.size());
191 if (!apis.isEmpty()) {
193 JSONObject models = null;
196 models = jsonConverter.convertToJsonSchema(m);
197 doc.setModels(models);
198 if (_logger.isDebugEnabled()) {
199 _logger.debug(mapper.writeValueAsString(doc));
201 } catch (IOException | JSONException e) {
210 protected ApiDeclaration createApiDeclaration(String basePath) {
211 ApiDeclaration doc = new ApiDeclaration();
212 doc.setApiVersion(API_VERSION);
213 doc.setSwaggerVersion(SWAGGER_VERSION);
214 doc.setBasePath(basePath);
215 doc.setProduces(Arrays.asList("application/json", "application/xml"));
219 protected String getDataStorePath(String dataStore, String context) {
220 return dataStore + context;
223 private String generateCacheKey(Module m) {
224 return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
227 private String generateCacheKey(String module, String revision) {
228 return module + "(" + revision + ")";
231 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath,
232 List<Parameter> parentPathParams, boolean addConfigApi) {
235 List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
237 String resourcePath = parentPath + createPath(node, pathParams) + "/";
238 _logger.debug("Adding path: [{}]", resourcePath);
239 api.setPath(resourcePath);
240 api.setOperations(operations(node, pathParams, addConfigApi));
242 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
243 DataNodeContainer schemaNode = (DataNodeContainer) node;
245 for (DataSchemaNode childNode : schemaNode.getChildNodes()) {
246 // We don't support going to leaf nodes today. Only lists and
248 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
249 // keep config and operation attributes separate.
250 if (childNode.isConfiguration() == addConfigApi) {
251 addApis(childNode, apis, resourcePath, pathParams, addConfigApi);
264 private List<Operation> operations(DataSchemaNode node, List<Parameter> pathParams,
266 List<Operation> operations = new ArrayList<>();
268 OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig);
269 operations.add(getBuilder.pathParams(pathParams).build());
272 OperationBuilder.Post postBuilder = new OperationBuilder.Post(node);
273 operations.add(postBuilder.pathParams(pathParams).build());
275 OperationBuilder.Put putBuilder = new OperationBuilder.Put(node);
276 operations.add(putBuilder.pathParams(pathParams).build());
278 OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node);
279 operations.add(deleteBuilder.pathParams(pathParams).build());
284 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams) {
285 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
286 StringBuilder path = new StringBuilder();
287 QName _qName = schemaNode.getQName();
288 String localName = _qName.getLocalName();
289 path.append(localName);
291 if ((schemaNode instanceof ListSchemaNode)) {
292 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
293 for (final QName listKey : listKeys) {
295 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode)
296 .getDataChildByName(listKey);
297 pathListParams.add(((LeafSchemaNode) _dataChildByName));
299 String pathParamIdentifier = new StringBuilder("/{")
300 .append(listKey.getLocalName()).append("}").toString();
301 path.append(pathParamIdentifier);
303 Parameter pathParam = new Parameter();
304 pathParam.setName(listKey.getLocalName());
305 pathParam.setDescription(_dataChildByName.getDescription());
306 pathParam.setType("string");
307 pathParam.setParamType("path");
309 pathParams.add(pathParam);
313 return path.toString();
316 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath) {
318 String resourcePath = parentPath + rpcDefn.getQName().getLocalName();
319 rpc.setPath(resourcePath);
321 Operation operationSpec = new Operation();
322 operationSpec.setMethod("POST");
323 operationSpec.setNotes(rpcDefn.getDescription());
324 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
325 if (rpcDefn.getOutput() != null) {
326 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
328 if (rpcDefn.getInput() != null) {
329 Parameter payload = new Parameter();
330 payload.setParamType("body");
331 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
332 operationSpec.setParameters(Collections.singletonList(payload));
335 rpc.setOperations(Arrays.asList(operationSpec));
340 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
341 if (schemaContext == null) {
342 return new TreeSet<>();
345 Set<Module> modules = schemaContext.getModules();
347 SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
349 public int compare(Module o1, Module o2) {
350 int result = o1.getName().compareTo(o2.getName());
352 result = o1.getRevision().compareTo(o2.getRevision());
355 result = o1.getNamespace().compareTo(o2.getNamespace());
360 for (Module m : modules) {
362 sortedModules.add(m);
365 return sortedModules;