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 = "17";
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 mapper.registerModule(new JsonOrgModule());
77 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, final String context) {
85 final ResourceList resourceList = createResourceList();
87 final Set<Module> modules = getSortedModules(schemaContext);
89 final List<Resource> resources = new ArrayList<>(modules.size());
91 LOG.info("Modules found [{}]", modules.size());
93 for (final Module module : modules) {
94 final String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
95 final Resource resource = new Resource();
96 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
97 final ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
100 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
101 resources.add(resource);
103 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
107 resourceList.setApis(resources);
112 protected ResourceList createResourceList() {
113 final ResourceList resourceList = new ResourceList();
114 resourceList.setApiVersion(API_VERSION);
115 resourceList.setSwaggerVersion(SWAGGER_VERSION);
119 protected String generatePath(final UriInfo uriInfo, final String name, final String revision) {
120 final URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
121 return uri.toASCIIString();
124 public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo, final SchemaContext schemaContext, final String context) {
128 if (revision != null && !revision.equals("0000-00-00")) {
129 rev = SIMPLE_DATE_FORMAT.parse(revision);
131 } catch (final ParseException e) {
132 throw new IllegalArgumentException(e);
136 final Calendar cal = new GregorianCalendar();
140 if (cal.get(Calendar.YEAR) < 1970) {
145 final Module module = schemaContext.findModuleByName(moduleName, rev);
146 Preconditions.checkArgument(module != null,
147 "Could not find module by name,revision: " + moduleName + "," + revision);
149 return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
152 public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo, final String context, final SchemaContext schemaContext) {
153 final String basePath = createBasePathFromUriInfo(uriInfo);
155 final ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
162 protected String createBasePathFromUriInfo(final UriInfo uriInfo) {
163 String portPart = "";
164 final int port = uriInfo.getBaseUri().getPort();
166 portPart = ":" + port;
168 final String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
169 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
174 public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath, final String context, final SchemaContext schemaContext) {
175 final ApiDeclaration doc = createApiDeclaration(basePath);
177 final List<Api> apis = new ArrayList<>();
178 boolean hasAddRootPostLink = false;
180 final Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
181 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
182 for (final DataSchemaNode node : dataSchemaNodes) {
183 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
184 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
186 List<Parameter> pathParams = new ArrayList<>();
190 * Only when the node's config statement is true, such apis as GET/PUT/POST/DELETE config
191 * are added for this node.
193 if (node.isConfiguration()) { // This node's config statement is true.
194 resourcePath = getDataStorePath("config", context);
197 * When there are two or more top container or list nodes whose config statement is true in module,
198 * make sure that only one root post link is added for this module.
200 if (!hasAddRootPostLink) {
201 LOG.debug("Has added root post link for module {}", m.getName());
202 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, "config", apis);
204 hasAddRootPostLink = true;
207 addApis(node, apis, resourcePath, pathParams, schemaContext, true, m.getName(), "config");
209 pathParams = new ArrayList<>();
210 resourcePath = getDataStorePath("operational", context);
212 addApis(node, apis, resourcePath, pathParams, schemaContext, false, m.getName(), "operational");
216 final Set<RpcDefinition> rpcs = m.getRpcs();
217 for (final RpcDefinition rpcDefinition : rpcs) {
218 final String resourcePath;
219 resourcePath = getDataStorePath("operations", context);
221 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
224 LOG.debug("Number of APIs found [{}]", apis.size());
226 if (!apis.isEmpty()) {
228 JSONObject models = null;
231 models = jsonConverter.convertToJsonSchema(m, schemaContext);
232 doc.setModels(models);
233 if (LOG.isDebugEnabled()) {
234 LOG.debug(mapper.writeValueAsString(doc));
236 } catch (IOException | JSONException e) {
237 LOG.error("Exception occured in ModelGenerator", e);
245 private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
246 final String resourcePath, final String dataStore, final List<Api> apis) {
247 if (containsListOrContainer(module.getChildNodes())) {
248 final Api apiForRootPostUri = new Api();
249 apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
250 apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
251 module.getDescription(), module, pathParams, true, ""));
252 apis.add(apiForRootPostUri);
256 protected ApiDeclaration createApiDeclaration(final String basePath) {
257 final ApiDeclaration doc = new ApiDeclaration();
258 doc.setApiVersion(API_VERSION);
259 doc.setSwaggerVersion(SWAGGER_VERSION);
260 doc.setBasePath(basePath);
261 doc.setProduces(Arrays.asList("application/json", "application/xml"));
265 protected String getDataStorePath(final String dataStore, final String context) {
267 if ("config".contains(dataStore) || "operational".contains(dataStore)) {
268 return "/" + RESTCONF_DRAFT + "/data" + context;
270 return "/" + RESTCONF_DRAFT + "/operations" + context;
273 return "/" + dataStore + context;
277 private String generateCacheKey(final String module, final String revision) {
278 return module + "(" + revision + ")";
281 private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath, final List<Parameter> parentPathParams,
282 final SchemaContext schemaContext, final boolean addConfigApi, final String parentName, final String dataStore) {
283 final Api api = new Api();
284 final List<Parameter> pathParams = new ArrayList<>(parentPathParams);
286 final String resourcePath = parentPath + "/" + createPath(node, pathParams, schemaContext);
287 LOG.debug("Adding path: [{}]", resourcePath);
288 api.setPath(resourcePath.concat(getContent(dataStore)));
290 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
291 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
292 final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
293 childSchemaNodes = dataNodeContainer.getChildNodes();
295 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes, parentName));
298 for (final DataSchemaNode childNode : childSchemaNodes) {
299 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
300 // keep config and operation attributes separate.
301 if (childNode.isConfiguration() == addConfigApi) {
302 final String newParent = parentName + "/" + node.getQName().getLocalName();
303 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi, newParent, dataStore);
309 protected static String getContent(final String dataStore) {
311 if ("operational".contains(dataStore)) {
312 return "?content=nonconfig";
313 } else if ("config".contains(dataStore)) {
314 return "?content=config";
322 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
323 for (final DataSchemaNode child : nodes) {
324 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
331 private List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams, final boolean isConfig,
332 final Iterable<DataSchemaNode> childSchemaNodes, final String parentName) {
333 final List<Operation> operations = new ArrayList<>();
335 final Get getBuilder = new Get(node, isConfig);
336 operations.add(getBuilder.pathParams(pathParams).build());
339 final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName);
340 operations.add(putBuilder.pathParams(pathParams).build());
342 final Delete deleteBuilder = new Delete(node);
343 operations.add(deleteBuilder.pathParams(pathParams).build());
345 if (containsListOrContainer(childSchemaNodes)) {
346 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
347 (DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
353 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer,
354 final List<Parameter> pathParams, final boolean isConfig, final String parentName) {
355 final List<Operation> operations = new ArrayList<>();
357 final Post postBuilder = new Post(name, parentName + name, description, dataNodeContainer);
358 operations.add(postBuilder.pathParams(pathParams).build());
363 private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams, final SchemaContext schemaContext) {
364 final ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
365 final StringBuilder path = new StringBuilder();
366 final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
367 path.append(localName);
369 if ((schemaNode instanceof ListSchemaNode)) {
370 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
371 StringBuilder keyBuilder = null;
373 keyBuilder = new StringBuilder("=");
376 for (final QName listKey : listKeys) {
377 final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
378 pathListParams.add(((LeafSchemaNode) dataChildByName));
379 final String pathParamIdentifier;
381 pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}")
384 pathParamIdentifier = "/{" + listKey.getLocalName() + "}";
386 path.append(pathParamIdentifier);
388 final Parameter pathParam = new Parameter();
389 pathParam.setName(listKey.getLocalName());
390 pathParam.setDescription(dataChildByName.getDescription());
391 pathParam.setType("string");
392 pathParam.setParamType("path");
394 pathParams.add(pathParam);
396 keyBuilder = new StringBuilder(",");
400 return path.toString();
403 protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath, final SchemaContext schemaContext) {
404 final Api rpc = new Api();
405 final String resourcePath = parentPath + "/" + resolvePathArgumentsName(rpcDefn, schemaContext);
406 rpc.setPath(resourcePath);
408 final Operation operationSpec = new Operation();
409 operationSpec.setMethod("POST");
410 operationSpec.setNotes(rpcDefn.getDescription());
411 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
412 if (rpcDefn.getOutput() != null) {
413 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP);
415 if (rpcDefn.getInput() != null) {
416 final Parameter payload = new Parameter();
417 payload.setParamType("body");
418 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input" + OperationBuilder.TOP);
419 operationSpec.setParameters(Collections.singletonList(payload));
420 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
423 rpc.setOperations(Arrays.asList(operationSpec));
428 protected SortedSet<Module> getSortedModules(final SchemaContext schemaContext) {
429 if (schemaContext == null) {
430 return new TreeSet<>();
433 final Set<Module> modules = schemaContext.getModules();
435 final SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
436 int result = module1.getName().compareTo(module2.getName());
438 final Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
439 final Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
440 result = module1Revision.compareTo(module2Revision);
443 result = module1.getNamespace().compareTo(module2.getNamespace());
447 for (final Module m : modules) {
449 sortedModules.add(m);
452 return sortedModules;
455 public void setDraft(final boolean draft) {
456 this.newDraft = draft;