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;
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.Calendar;
24 import java.util.Collection;
25 import java.util.Collections;
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.model.builder.OperationBuilder.Delete;
37 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Get;
38 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
39 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Put;
40 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
41 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
42 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
43 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
44 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
45 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
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";
65 private static final String RESTCONF_DRAFT = "18";
67 static final String MODULE_NAME_SUFFIX = "_module";
68 protected static final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
69 private final ModelGenerator jsonConverter = new ModelGenerator();
71 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
72 private final ObjectMapper mapper = new ObjectMapper();
73 private static boolean newDraft;
75 protected BaseYangSwaggerGenerator() {
76 this.mapper.registerModule(new JsonOrgModule());
77 this.mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
81 * Return list of modules converted to swagger compliant resource list.
83 public ResourceList getResourceListing(final UriInfo uriInfo, final SchemaContext schemaContext,
84 final String context) {
86 final ResourceList resourceList = createResourceList();
88 final Set<Module> modules = getSortedModules(schemaContext);
90 final List<Resource> resources = new ArrayList<>(modules.size());
92 LOG.info("Modules found [{}]", modules.size());
94 for (final Module module : modules) {
95 final String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
96 final Resource resource = new Resource();
97 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
98 final ApiDeclaration doc =
99 getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
102 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
103 resources.add(resource);
105 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
109 resourceList.setApis(resources);
114 protected ResourceList createResourceList() {
115 final ResourceList resourceList = new ResourceList();
116 resourceList.setApiVersion(API_VERSION);
117 resourceList.setSwaggerVersion(SWAGGER_VERSION);
121 protected String generatePath(final UriInfo uriInfo, final String name, final String revision) {
122 final URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
123 return uri.toASCIIString();
126 public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo,
127 final SchemaContext schemaContext, final String context) {
131 if ((revision != null) && !revision.equals("0000-00-00")) {
132 rev = SIMPLE_DATE_FORMAT.parse(revision);
134 } catch (final ParseException e) {
135 throw new IllegalArgumentException(e);
139 final Calendar cal = new GregorianCalendar();
143 if (cal.get(Calendar.YEAR) < 1970) {
148 final Module module = schemaContext.findModuleByName(moduleName, rev);
149 Preconditions.checkArgument(module != null,
150 "Could not find module by name,revision: " + moduleName + "," + revision);
152 return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
155 public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo,
156 final String context, final SchemaContext schemaContext) {
157 final String basePath = createBasePathFromUriInfo(uriInfo);
159 final ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
166 protected String createBasePathFromUriInfo(final UriInfo uriInfo) {
167 String portPart = "";
168 final int port = uriInfo.getBaseUri().getPort();
170 portPart = ":" + port;
172 final String basePath =
173 new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://").append(uriInfo.getBaseUri().getHost())
174 .append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT).toString();
178 public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath, final String context,
179 final SchemaContext schemaContext) {
180 final ApiDeclaration doc = createApiDeclaration(basePath);
182 final List<Api> apis = new ArrayList<>();
183 boolean hasAddRootPostLink = false;
185 final Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
186 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
187 for (final DataSchemaNode node : dataSchemaNodes) {
188 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
189 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
191 List<Parameter> pathParams = new ArrayList<>();
195 * Only when the node's config statement is true, such apis as
196 * GET/PUT/POST/DELETE config are added for this node.
198 if (node.isConfiguration()) { // This node's config statement is
200 resourcePath = getDataStorePath("config", context);
203 * When there are two or more top container or list nodes
204 * whose config statement is true in module, make sure that
205 * only one root post link is added for this module.
207 if (!hasAddRootPostLink) {
208 LOG.debug("Has added root post link for module {}", m.getName());
209 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, "config", apis);
211 hasAddRootPostLink = true;
214 addApis(node, apis, resourcePath, pathParams, schemaContext, true, m.getName(), "config");
216 pathParams = new ArrayList<>();
217 resourcePath = getDataStorePath("operational", context);
219 addApis(node, apis, resourcePath, pathParams, schemaContext, false, m.getName(), "operational");
223 final Set<RpcDefinition> rpcs = m.getRpcs();
224 for (final RpcDefinition rpcDefinition : rpcs) {
225 final String resourcePath;
226 resourcePath = getDataStorePath("operations", context);
228 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
231 LOG.debug("Number of APIs found [{}]", apis.size());
233 if (!apis.isEmpty()) {
235 JSONObject models = null;
238 models = this.jsonConverter.convertToJsonSchema(m, schemaContext);
239 doc.setModels(models);
240 if (LOG.isDebugEnabled()) {
241 LOG.debug(this.mapper.writeValueAsString(doc));
243 } catch (IOException | JSONException e) {
244 LOG.error("Exception occured in ModelGenerator", e);
252 private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
253 final String resourcePath, final String dataStore, final List<Api> apis) {
254 if (containsListOrContainer(module.getChildNodes())) {
255 final Api apiForRootPostUri = new Api();
256 apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
257 apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
258 module.getDescription(), module, pathParams, true, ""));
259 apis.add(apiForRootPostUri);
263 protected ApiDeclaration createApiDeclaration(final String basePath) {
264 final ApiDeclaration doc = new ApiDeclaration();
265 doc.setApiVersion(API_VERSION);
266 doc.setSwaggerVersion(SWAGGER_VERSION);
267 doc.setBasePath(basePath);
268 doc.setProduces(Arrays.asList("application/json", "application/xml"));
272 protected String getDataStorePath(final String dataStore, final String context) {
274 if ("config".contains(dataStore) || "operational".contains(dataStore)) {
275 return "/" + RESTCONF_DRAFT + "/data" + context;
277 return "/" + RESTCONF_DRAFT + "/operations" + context;
280 return "/" + dataStore + context;
284 private String generateCacheKey(final String module, final String revision) {
285 return module + "(" + revision + ")";
288 private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath,
289 final List<Parameter> parentPathParams, final SchemaContext schemaContext, final boolean addConfigApi,
290 final String parentName, final String dataStore) {
291 final Api api = new Api();
292 final List<Parameter> pathParams = new ArrayList<>(parentPathParams);
294 final String resourcePath = parentPath + "/" + createPath(node, pathParams, schemaContext);
295 LOG.debug("Adding path: [{}]", resourcePath);
296 api.setPath(resourcePath.concat(getContent(dataStore)));
298 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
299 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
300 final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
301 childSchemaNodes = dataNodeContainer.getChildNodes();
303 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes, parentName));
306 for (final DataSchemaNode childNode : childSchemaNodes) {
307 if ((childNode instanceof ListSchemaNode) || (childNode instanceof ContainerSchemaNode)) {
308 // keep config and operation attributes separate.
309 if (childNode.isConfiguration() == addConfigApi) {
310 final String newParent = parentName + "/" + node.getQName().getLocalName();
311 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi, newParent,
318 protected static String getContent(final String dataStore) {
320 if ("operational".contains(dataStore)) {
321 return "?content=nonconfig";
322 } else if ("config".contains(dataStore)) {
323 return "?content=config";
332 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
333 for (final DataSchemaNode child : nodes) {
334 if ((child instanceof ListSchemaNode) || (child instanceof ContainerSchemaNode)) {
341 private List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams,
342 final boolean isConfig, final Iterable<DataSchemaNode> childSchemaNodes, final String parentName) {
343 final List<Operation> operations = new ArrayList<>();
345 final Get getBuilder = new Get(node, isConfig);
346 operations.add(getBuilder.pathParams(pathParams).build());
349 final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName);
350 operations.add(putBuilder.pathParams(pathParams).build());
352 final Delete deleteBuilder = new Delete(node);
353 operations.add(deleteBuilder.pathParams(pathParams).build());
355 if (containsListOrContainer(childSchemaNodes)) {
356 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
357 (DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
363 private List<Operation> operationPost(final String name, final String description,
364 final DataNodeContainer dataNodeContainer, final List<Parameter> pathParams, final boolean isConfig,
365 final String parentName) {
366 final List<Operation> operations = new ArrayList<>();
368 final Post postBuilder = new Post(name, parentName + name, description, dataNodeContainer);
369 operations.add(postBuilder.pathParams(pathParams).build());
374 private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams,
375 final SchemaContext schemaContext) {
376 final ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
377 final StringBuilder path = new StringBuilder();
378 final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
379 path.append(localName);
381 if ((schemaNode instanceof ListSchemaNode)) {
382 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
383 StringBuilder keyBuilder = null;
385 keyBuilder = new StringBuilder("=");
388 for (final QName listKey : listKeys) {
389 final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
390 pathListParams.add(((LeafSchemaNode) dataChildByName));
391 final String pathParamIdentifier;
393 pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}").toString();
395 pathParamIdentifier = "/{" + listKey.getLocalName() + "}";
397 path.append(pathParamIdentifier);
399 final Parameter pathParam = new Parameter();
400 pathParam.setName(listKey.getLocalName());
401 pathParam.setDescription(dataChildByName.getDescription());
402 pathParam.setType("string");
403 pathParam.setParamType("path");
405 pathParams.add(pathParam);
407 keyBuilder = new StringBuilder(",");
411 return path.toString();
414 protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath,
415 final SchemaContext schemaContext) {
416 final Api rpc = new Api();
417 final String resourcePath = parentPath + "/" + resolvePathArgumentsName(rpcDefn, schemaContext);
418 rpc.setPath(resourcePath);
420 final Operation operationSpec = new Operation();
421 operationSpec.setMethod("POST");
422 operationSpec.setNotes(rpcDefn.getDescription());
423 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
424 if (rpcDefn.getOutput() != null) {
425 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP);
427 if (rpcDefn.getInput() != null) {
428 final Parameter payload = new Parameter();
429 payload.setParamType("body");
430 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input" + OperationBuilder.TOP);
431 operationSpec.setParameters(Collections.singletonList(payload));
432 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
435 rpc.setOperations(Arrays.asList(operationSpec));
440 protected SortedSet<Module> getSortedModules(final SchemaContext schemaContext) {
441 if (schemaContext == null) {
442 return new TreeSet<>();
445 final Set<Module> modules = schemaContext.getModules();
447 final SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
448 int result = module1.getName().compareTo(module2.getName());
450 final Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
451 final Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
452 result = module1Revision.compareTo(module2Revision);
455 result = module1.getNamespace().compareTo(module2.getNamespace());
459 for (final Module m : modules) {
461 sortedModules.add(m);
464 return sortedModules;
467 public void setDraft(final boolean draft) {
468 this.newDraft = draft;