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.databind.node.ObjectNode;
15 import com.google.common.base.Preconditions;
16 import java.io.IOException;
18 import java.time.format.DateTimeParseException;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Optional;
26 import java.util.SortedSet;
27 import java.util.TreeSet;
28 import javax.ws.rs.core.UriInfo;
29 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
30 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Delete;
31 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Get;
32 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
33 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Put;
34 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
35 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
36 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
37 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
38 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
39 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.Revision;
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.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class BaseYangSwaggerGenerator {
54 private static final Logger LOG = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
56 protected static final String API_VERSION = "1.0.0";
57 protected static final String SWAGGER_VERSION = "1.2";
58 protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
59 private static final String RESTCONF_DRAFT = "18";
61 static final String MODULE_NAME_SUFFIX = "_module";
62 private final ModelGenerator jsonConverter = new ModelGenerator();
64 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
65 private final ObjectMapper mapper = new ObjectMapper();
66 private volatile boolean newDraft;
68 protected BaseYangSwaggerGenerator() {
69 this.mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
73 * Return list of modules converted to swagger compliant resource list.
75 public ResourceList getResourceListing(final UriInfo uriInfo, final SchemaContext schemaContext,
76 final String context) {
78 final ResourceList resourceList = createResourceList();
80 final Set<Module> modules = getSortedModules(schemaContext);
82 final List<Resource> resources = new ArrayList<>(modules.size());
84 LOG.info("Modules found [{}]", modules.size());
86 for (final Module module : modules) {
87 final String revisionString = module.getQNameModule().getRevision().map(Revision::toString).orElse(null);
88 final Resource resource = new Resource();
89 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
90 final ApiDeclaration doc =
91 getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
94 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
95 resources.add(resource);
97 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
101 resourceList.setApis(resources);
106 protected ResourceList createResourceList() {
107 final ResourceList resourceList = new ResourceList();
108 resourceList.setApiVersion(API_VERSION);
109 resourceList.setSwaggerVersion(SWAGGER_VERSION);
113 protected String generatePath(final UriInfo uriInfo, final String name, final String revision) {
114 final URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
115 return uri.toASCIIString();
118 public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo,
119 final SchemaContext schemaContext, final String context) {
120 final Optional<Revision> rev;
123 rev = Revision.ofNullable(revision);
124 } catch (final DateTimeParseException e) {
125 throw new IllegalArgumentException(e);
128 final Module module = schemaContext.findModule(moduleName, rev).orElse(null);
129 Preconditions.checkArgument(module != null,
130 "Could not find module by name,revision: " + moduleName + "," + revision);
132 return getApiDeclaration(module, uriInfo, context, schemaContext);
135 public ApiDeclaration getApiDeclaration(final Module module, final UriInfo uriInfo,
136 final String context, final SchemaContext schemaContext) {
137 final String basePath = createBasePathFromUriInfo(uriInfo);
139 final ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
146 protected String createBasePathFromUriInfo(final UriInfo uriInfo) {
147 String portPart = "";
148 final int port = uriInfo.getBaseUri().getPort();
150 portPart = ":" + port;
152 final String basePath =
153 new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://").append(uriInfo.getBaseUri().getHost())
154 .append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT).toString();
158 public ApiDeclaration getSwaggerDocSpec(final Module module, final String basePath, final String context,
159 final SchemaContext schemaContext) {
160 final ApiDeclaration doc = createApiDeclaration(basePath);
162 final List<Api> apis = new ArrayList<>();
163 boolean hasAddRootPostLink = false;
165 final Collection<DataSchemaNode> dataSchemaNodes = module.getChildNodes();
166 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
167 for (final DataSchemaNode node : dataSchemaNodes) {
168 if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) {
169 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
171 List<Parameter> pathParams = new ArrayList<>();
175 * Only when the node's config statement is true, such apis as
176 * GET/PUT/POST/DELETE config are added for this node.
178 if (node.isConfiguration()) { // This node's config statement is
180 resourcePath = getDataStorePath("config", context);
183 * When there are two or more top container or list nodes
184 * whose config statement is true in module, make sure that
185 * only one root post link is added for this module.
187 if (!hasAddRootPostLink) {
188 LOG.debug("Has added root post link for module {}", module.getName());
189 addRootPostLink(module, (DataNodeContainer) node, pathParams, resourcePath, "config", apis);
191 hasAddRootPostLink = true;
194 addApis(node, apis, resourcePath, pathParams, schemaContext, true, module.getName(), "config");
196 pathParams = new ArrayList<>();
197 resourcePath = getDataStorePath("operational", context);
199 addApis(node, apis, resourcePath, pathParams, schemaContext, false, module.getName(), "operational");
203 final Set<RpcDefinition> rpcs = module.getRpcs();
204 for (final RpcDefinition rpcDefinition : rpcs) {
205 final String resourcePath;
206 resourcePath = getDataStorePath("operations", context);
208 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
211 LOG.debug("Number of APIs found [{}]", apis.size());
213 if (!apis.isEmpty()) {
215 ObjectNode models = null;
218 models = this.jsonConverter.convertToJsonSchema(module, schemaContext);
219 doc.setModels(models);
220 if (LOG.isDebugEnabled()) {
221 LOG.debug(this.mapper.writeValueAsString(doc));
223 } catch (IOException e) {
224 LOG.error("Exception occured in ModelGenerator", e);
232 private void addRootPostLink(final Module module, final DataNodeContainer node,
233 final List<Parameter> pathParams, final String resourcePath, final String dataStore, final List<Api> apis) {
234 if (containsListOrContainer(module.getChildNodes())) {
235 final Api apiForRootPostUri = new Api();
236 apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
237 apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
238 module.getDescription().orElse(null), module, pathParams, true, ""));
239 apis.add(apiForRootPostUri);
243 protected ApiDeclaration createApiDeclaration(final String basePath) {
244 final ApiDeclaration doc = new ApiDeclaration();
245 doc.setApiVersion(API_VERSION);
246 doc.setSwaggerVersion(SWAGGER_VERSION);
247 doc.setBasePath(basePath);
248 doc.setProduces(Arrays.asList("application/json", "application/xml"));
252 protected String getDataStorePath(final String dataStore, final String context) {
254 if ("config".contains(dataStore) || "operational".contains(dataStore)) {
255 return "/" + RESTCONF_DRAFT + "/data" + context;
257 return "/" + RESTCONF_DRAFT + "/operations" + context;
260 return "/" + dataStore + context;
263 private static String generateCacheKey(final String module, final String revision) {
264 return module + "(" + revision + ")";
267 private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath,
268 final List<Parameter> parentPathParams, final SchemaContext schemaContext, final boolean addConfigApi,
269 final String parentName, final String dataStore) {
270 final Api api = new Api();
271 final List<Parameter> pathParams = new ArrayList<>(parentPathParams);
273 final String resourcePath = parentPath + "/" + createPath(node, pathParams, schemaContext);
274 LOG.debug("Adding path: [{}]", resourcePath);
275 api.setPath(resourcePath.concat(getContent(dataStore)));
277 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
278 if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) {
279 final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
280 childSchemaNodes = dataNodeContainer.getChildNodes();
282 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes, parentName));
285 for (final DataSchemaNode childNode : childSchemaNodes) {
286 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
287 // keep config and operation attributes separate.
288 if (childNode.isConfiguration() == addConfigApi) {
289 final String newParent = parentName + "/" + node.getQName().getLocalName();
290 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi, newParent,
297 protected String getContent(final String dataStore) {
299 if ("operational".contains(dataStore)) {
300 return "?content=nonconfig";
301 } else if ("config".contains(dataStore)) {
302 return "?content=config";
311 private static boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
312 for (final DataSchemaNode child : nodes) {
313 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
320 private static List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams,
321 final boolean isConfig, final Iterable<DataSchemaNode> childSchemaNodes, final String parentName) {
322 final List<Operation> operations = new ArrayList<>();
324 final Get getBuilder = new Get(node, isConfig);
325 operations.add(getBuilder.pathParams(pathParams).build());
328 final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription().orElse(null),
330 operations.add(putBuilder.pathParams(pathParams).build());
332 final Delete deleteBuilder = new Delete(node);
333 operations.add(deleteBuilder.pathParams(pathParams).build());
335 if (containsListOrContainer(childSchemaNodes)) {
336 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription().orElse(null),
337 (DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
343 private static List<Operation> operationPost(final String name, final String description,
344 final DataNodeContainer dataNodeContainer, final List<Parameter> pathParams, final boolean isConfig,
345 final String parentName) {
346 final List<Operation> operations = new ArrayList<>();
348 final Post postBuilder = new Post(name, parentName + name, description, dataNodeContainer);
349 operations.add(postBuilder.pathParams(pathParams).build());
354 private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams,
355 final SchemaContext schemaContext) {
356 final StringBuilder path = new StringBuilder();
357 final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
358 path.append(localName);
360 if (schemaNode instanceof ListSchemaNode) {
361 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
362 StringBuilder keyBuilder = null;
364 keyBuilder = new StringBuilder("=");
367 for (final QName listKey : listKeys) {
368 final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
369 final String pathParamIdentifier;
371 pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}").toString();
373 pathParamIdentifier = "/{" + listKey.getLocalName() + "}";
375 path.append(pathParamIdentifier);
377 final Parameter pathParam = new Parameter();
378 pathParam.setName(listKey.getLocalName());
379 pathParam.setDescription(dataChildByName.getDescription().orElse(null));
380 pathParam.setType("string");
381 pathParam.setParamType("path");
383 pathParams.add(pathParam);
385 keyBuilder = new StringBuilder(",");
389 return path.toString();
392 protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath,
393 final SchemaContext schemaContext) {
394 final Api rpc = new Api();
395 final String resourcePath = parentPath + "/" + resolvePathArgumentsName(rpcDefn, schemaContext);
396 rpc.setPath(resourcePath);
398 final Operation operationSpec = new Operation();
399 operationSpec.setMethod("POST");
400 operationSpec.setNotes(rpcDefn.getDescription().orElse(null));
401 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
402 if (!rpcDefn.getOutput().getChildNodes().isEmpty()) {
403 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP);
405 if (!rpcDefn.getInput().getChildNodes().isEmpty()) {
406 final Parameter payload = new Parameter();
407 payload.setParamType("body");
408 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input" + OperationBuilder.TOP);
409 operationSpec.setParameters(Collections.singletonList(payload));
410 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
413 rpc.setOperations(Arrays.asList(operationSpec));
418 protected SortedSet<Module> getSortedModules(final SchemaContext schemaContext) {
419 if (schemaContext == null) {
420 return new TreeSet<>();
423 final Set<Module> modules = schemaContext.getModules();
425 final SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
426 int result = module1.getName().compareTo(module2.getName());
428 result = Revision.compare(module1.getRevision(), module2.getRevision());
431 result = module1.getNamespace().compareTo(module2.getNamespace());
435 for (final Module m : modules) {
437 sortedModules.add(m);
440 return sortedModules;
443 public void setDraft(final boolean draft) {
444 this.newDraft = draft;
447 protected boolean isNewDraft() {