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.netconf.sal.rest.doc.impl;
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;
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.Comparator;
26 import java.util.Date;
27 import java.util.GregorianCalendar;
28 import java.util.List;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import javax.ws.rs.core.UriInfo;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
36 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
37 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
38 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
39 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
40 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
41 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
42 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Delete;
43 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Get;
44 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
45 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Put;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class BaseYangSwaggerGenerator {
60 private static final Logger LOG = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
62 protected static final String API_VERSION = "1.0.0";
63 protected static final String SWAGGER_VERSION = "1.2";
64 protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
66 static final String MODULE_NAME_SUFFIX = "_module";
67 protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
68 private final ModelGenerator jsonConverter = new ModelGenerator();
70 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
71 private final ObjectMapper mapper = new ObjectMapper();
73 protected BaseYangSwaggerGenerator() {
74 mapper.registerModule(new JsonOrgModule());
75 mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
81 * @param schemaContext
83 * @return list of modules converted to swagger compliant resource list.
85 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
87 ResourceList resourceList = createResourceList();
89 Set<Module> modules = getSortedModules(schemaContext);
91 List<Resource> resources = new ArrayList<>(modules.size());
93 LOG.info("Modules found [{}]", modules.size());
95 for (Module module : modules) {
96 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
97 Resource resource = new Resource();
98 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
99 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
102 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
103 resources.add(resource);
105 LOG.debug("Could not generate doc for {},{}", module.getName(), revisionString);
109 resourceList.setApis(resources);
114 protected ResourceList createResourceList() {
115 ResourceList resourceList = new ResourceList();
116 resourceList.setApiVersion(API_VERSION);
117 resourceList.setSwaggerVersion(SWAGGER_VERSION);
121 protected String generatePath(UriInfo uriInfo, String name, String revision) {
122 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
123 return uri.toASCIIString();
126 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
130 if(revision != null && !revision.equals("0000-00-00")) {
131 rev = SIMPLE_DATE_FORMAT.parse(revision);
133 } catch (ParseException e) {
134 throw new IllegalArgumentException(e);
138 Calendar cal = new GregorianCalendar();
142 if(cal.get(Calendar.YEAR) < 1970) {
147 Module m = schemaContext.findModuleByName(module, rev);
148 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
150 return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
153 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
154 String basePath = createBasePathFromUriInfo(uriInfo);
156 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
163 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
164 String portPart = "";
165 int port = uriInfo.getBaseUri().getPort();
167 portPart = ":" + port;
169 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
170 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
175 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
176 ApiDeclaration doc = createApiDeclaration(basePath);
178 List<Api> apis = new ArrayList<Api>();
180 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
181 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
182 for (DataSchemaNode node : dataSchemaNodes) {
183 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
185 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
187 List<Parameter> pathParams = new ArrayList<Parameter>();
188 String resourcePath = getDataStorePath("/config/", context);
189 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
190 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
192 pathParams = new ArrayList<Parameter>();
193 resourcePath = getDataStorePath("/operational/", context);
194 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
198 Set<RpcDefinition> rpcs = m.getRpcs();
199 for (RpcDefinition rpcDefinition : rpcs) {
200 String resourcePath = getDataStorePath("/operations/", context);
201 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
204 LOG.debug("Number of APIs found [{}]", apis.size());
206 if (!apis.isEmpty()) {
208 JSONObject models = null;
211 models = jsonConverter.convertToJsonSchema(m, schemaContext);
212 doc.setModels(models);
213 if (LOG.isDebugEnabled()) {
214 LOG.debug(mapper.writeValueAsString(doc));
216 } catch (IOException | JSONException e) {
225 private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams,
226 final String resourcePath, final List<Api> apis) {
227 if (containsListOrContainer(m.getChildNodes())) {
228 final Api apiForRootPostUri = new Api();
229 apiForRootPostUri.setPath(resourcePath);
230 apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true));
231 apis.add(apiForRootPostUri);
235 protected ApiDeclaration createApiDeclaration(String basePath) {
236 ApiDeclaration doc = new ApiDeclaration();
237 doc.setApiVersion(API_VERSION);
238 doc.setSwaggerVersion(SWAGGER_VERSION);
239 doc.setBasePath(basePath);
240 doc.setProduces(Arrays.asList("application/json", "application/xml"));
244 protected String getDataStorePath(String dataStore, String context) {
245 return dataStore + context;
248 private String generateCacheKey(Module m) {
249 return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision()));
252 private String generateCacheKey(String module, String revision) {
253 return module + "(" + revision + ")";
256 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
257 boolean addConfigApi) {
260 List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams);
262 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
263 LOG.debug("Adding path: [{}]", resourcePath);
264 api.setPath(resourcePath);
266 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
267 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
268 DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
269 childSchemaNodes = dataNodeContainer.getChildNodes();
271 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
274 for (DataSchemaNode childNode : childSchemaNodes) {
275 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
276 // keep config and operation attributes separate.
277 if (childNode.isConfiguration() == addConfigApi) {
278 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
285 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
286 for (DataSchemaNode child : nodes) {
287 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
299 private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
300 List<Operation> operations = new ArrayList<>();
302 Get getBuilder = new Get(node, isConfig);
303 operations.add(getBuilder.pathParams(pathParams).build());
306 Put putBuilder = new Put(node.getQName().getLocalName(),
307 node.getDescription());
308 operations.add(putBuilder.pathParams(pathParams).build());
310 Delete deleteBuilder = new Delete(node);
311 operations.add(deleteBuilder.pathParams(pathParams).build());
313 if (containsListOrContainer(childSchemaNodes)) {
314 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node,
315 pathParams, isConfig));
326 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
327 List<Operation> operations = new ArrayList<>();
329 Post postBuilder = new Post(name, description, dataNodeContainer);
330 operations.add(postBuilder.pathParams(pathParams).build());
335 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
336 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>();
337 StringBuilder path = new StringBuilder();
338 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
339 path.append(localName);
341 if ((schemaNode instanceof ListSchemaNode)) {
342 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
343 for (final QName listKey : listKeys) {
344 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
345 pathListParams.add(((LeafSchemaNode) _dataChildByName));
347 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
349 path.append(pathParamIdentifier);
351 Parameter pathParam = new Parameter();
352 pathParam.setName(listKey.getLocalName());
353 pathParam.setDescription(_dataChildByName.getDescription());
354 pathParam.setType("string");
355 pathParam.setParamType("path");
357 pathParams.add(pathParam);
360 return path.toString();
363 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
365 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
366 rpc.setPath(resourcePath);
368 Operation operationSpec = new Operation();
369 operationSpec.setMethod("POST");
370 operationSpec.setNotes(rpcDefn.getDescription());
371 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
372 if (rpcDefn.getOutput() != null) {
373 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
375 if (rpcDefn.getInput() != null) {
376 Parameter payload = new Parameter();
377 payload.setParamType("body");
378 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
379 operationSpec.setParameters(Collections.singletonList(payload));
380 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
383 rpc.setOperations(Arrays.asList(operationSpec));
388 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
389 if (schemaContext == null) {
390 return new TreeSet<>();
393 Set<Module> modules = schemaContext.getModules();
395 SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() {
397 public int compare(Module module1, Module module2) {
398 int result = module1.getName().compareTo(module2.getName());
400 Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
401 Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
402 result = module1Revision.compareTo(module2Revision);
405 result = module1.getNamespace().compareTo(module2.getNamespace());
410 for (Module m : modules) {
412 sortedModules.add(m);
415 return sortedModules;