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.Collections;
18 import java.util.Comparator;
19 import java.util.Date;
20 import java.util.List;
22 import java.util.SortedSet;
23 import java.util.TreeSet;
25 import javax.ws.rs.core.UriInfo;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder;
30 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
31 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
32 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
33 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
34 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
35 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.fasterxml.jackson.databind.SerializationFeature;
50 import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
51 import com.google.common.base.Preconditions;
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,
80 ResourceList resourceList = createResourceList();
82 Set<Module> modules = getSortedModules(schemaContext);
84 List<Resource> resources = new ArrayList<>(modules.size());
86 _logger.info("Modules found [{}]", modules.size());
88 for (Module module : modules) {
89 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,
94 schemaContext, context);
97 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
98 resources.add(resource);
100 _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString);
104 resourceList.setApis(resources);
109 protected ResourceList createResourceList() {
110 ResourceList resourceList = new ResourceList();
111 resourceList.setApiVersion(API_VERSION);
112 resourceList.setSwaggerVersion(SWAGGER_VERSION);
116 protected String generatePath(UriInfo uriInfo, String name, String revision) {
117 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
118 return uri.toASCIIString();
121 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo,
122 SchemaContext schemaContext, String context) {
125 rev = SIMPLE_DATE_FORMAT.parse(revision);
126 } catch (ParseException e) {
127 throw new IllegalArgumentException(e);
129 Module m = schemaContext.findModuleByName(module, rev);
130 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module
133 return getApiDeclaration(m, rev, uriInfo, schemaContext, context);
136 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo,
137 SchemaContext schemaContext, String context) {
138 String basePath = createBasePathFromUriInfo(uriInfo);
140 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context);
147 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
148 String portPart = "";
149 int port = uriInfo.getBaseUri().getPort();
151 portPart = ":" + port;
153 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
154 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/")
155 .append(RESTCONF_CONTEXT_ROOT).toString();
159 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context) {
160 ApiDeclaration doc = createApiDeclaration(basePath);
162 List<Api> apis = new ArrayList<Api>();
164 Set<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
165 _logger.debug("child nodes size [{}]", dataSchemaNodes.size());
166 for (DataSchemaNode node : dataSchemaNodes) {
167 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
169 _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node
170 .getQName().getLocalName());
172 List<Parameter> pathParams = new ArrayList<Parameter>();
173 String resourcePath = getDataStorePath("/config/", context) + m.getName() + ":";
174 addApis(node, apis, resourcePath, pathParams, true);
176 pathParams = new ArrayList<Parameter>();
177 resourcePath = getDataStorePath("/operational/", context) + m.getName() + ":";
178 addApis(node, apis, resourcePath, pathParams, false);
181 Set<RpcDefinition> rpcs = m.getRpcs();
182 for (RpcDefinition rpcDefinition : rpcs) {
183 String resourcePath = getDataStorePath("/operations/", context) + m.getName() + ":";
184 addRpcs(rpcDefinition, apis, resourcePath);
188 _logger.debug("Number of APIs found [{}]", apis.size());
190 if (!apis.isEmpty()) {
192 JSONObject models = null;
195 models = jsonConverter.convertToJsonSchema(m);
196 doc.setModels(models);
197 if (_logger.isDebugEnabled()) {
198 _logger.debug(mapper.writeValueAsString(doc));
200 } catch (IOException | JSONException e) {
209 protected ApiDeclaration createApiDeclaration(String basePath) {
210 ApiDeclaration doc = new ApiDeclaration();
211 doc.setApiVersion(API_VERSION);
212 doc.setSwaggerVersion(SWAGGER_VERSION);
213 doc.setBasePath(basePath);
214 doc.setProduces(Arrays.asList("application/json", "application/xml"));
218 protected String getDataStorePath(String dataStore, String context) {
219 return dataStore + context;
222 private String generateCacheKey(Module m) {
223 return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
226 private String generateCacheKey(String module, String revision) {
227 return module + "(" + revision + ")";
230 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath,
231 List<Parameter> parentPathParams, boolean addConfigApi) {
234 List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
236 String resourcePath = parentPath + createPath(node, pathParams) + "/";
237 _logger.debug("Adding path: [{}]", resourcePath);
238 api.setPath(resourcePath);
239 api.setOperations(operations(node, pathParams, addConfigApi));
241 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
242 DataNodeContainer schemaNode = (DataNodeContainer) node;
243 Set<DataSchemaNode> dataSchemaNodes = schemaNode.getChildNodes();
245 for (DataSchemaNode childNode : dataSchemaNodes) {
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;