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";
66 static final String MODULE_NAME_SUFFIX = "_module";
67 protected static 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);
79 * Return list of modules converted to swagger compliant resource list.
81 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
83 ResourceList resourceList = createResourceList();
85 Set<Module> modules = getSortedModules(schemaContext);
87 List<Resource> resources = new ArrayList<>(modules.size());
89 LOG.info("Modules found [{}]", modules.size());
91 for (Module module : modules) {
92 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
93 Resource resource = new Resource();
94 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
95 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
98 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
99 resources.add(resource);
101 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
105 resourceList.setApis(resources);
110 protected ResourceList createResourceList() {
111 ResourceList resourceList = new ResourceList();
112 resourceList.setApiVersion(API_VERSION);
113 resourceList.setSwaggerVersion(SWAGGER_VERSION);
117 protected String generatePath(UriInfo uriInfo, String name, String revision) {
118 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
119 return uri.toASCIIString();
122 public ApiDeclaration getApiDeclaration(String moduleName, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
126 if (revision != null && !revision.equals("0000-00-00")) {
127 rev = SIMPLE_DATE_FORMAT.parse(revision);
129 } catch (ParseException e) {
130 throw new IllegalArgumentException(e);
134 Calendar cal = new GregorianCalendar();
138 if (cal.get(Calendar.YEAR) < 1970) {
143 Module module = schemaContext.findModuleByName(moduleName, rev);
144 Preconditions.checkArgument(module != null,
145 "Could not find module by name,revision: " + moduleName + "," + revision);
147 return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
150 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
151 String basePath = createBasePathFromUriInfo(uriInfo);
153 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
160 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
161 String portPart = "";
162 int port = uriInfo.getBaseUri().getPort();
164 portPart = ":" + port;
166 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
167 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
172 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
173 ApiDeclaration doc = createApiDeclaration(basePath);
175 List<Api> apis = new ArrayList<>();
176 boolean hasAddRootPostLink = false;
178 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
179 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
180 for (DataSchemaNode node : dataSchemaNodes) {
181 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
182 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
184 List<Parameter> pathParams = new ArrayList<>();
188 * Only when the node's config statement is true, such apis as GET/PUT/POST/DELETE config
189 * are added for this node.
191 if (node.isConfiguration()) { // This node's config statement is true.
192 resourcePath = getDataStorePath("/config/", context);
195 * When there are two or more top container or list nodes whose config statement is true in module,
196 * make sure that only one root post link is added for this module.
198 if (!hasAddRootPostLink) {
199 LOG.debug("Has added root post link for module {}", m.getName());
200 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
201 hasAddRootPostLink = true;
204 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
207 pathParams = new ArrayList<>();
208 resourcePath = getDataStorePath("/operational/", context);
209 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
213 Set<RpcDefinition> rpcs = m.getRpcs();
214 for (RpcDefinition rpcDefinition : rpcs) {
215 String resourcePath = getDataStorePath("/operations/", context);
216 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
219 LOG.debug("Number of APIs found [{}]", apis.size());
221 if (!apis.isEmpty()) {
223 JSONObject models = null;
226 models = jsonConverter.convertToJsonSchema(m, schemaContext);
227 doc.setModels(models);
228 if (LOG.isDebugEnabled()) {
229 LOG.debug(mapper.writeValueAsString(doc));
231 } catch (IOException | JSONException e) {
232 LOG.error("Exception occured in ModelGenerator", e);
240 private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
241 final String resourcePath, final List<Api> apis) {
242 if (containsListOrContainer(module.getChildNodes())) {
243 final Api apiForRootPostUri = new Api();
244 apiForRootPostUri.setPath(resourcePath);
245 apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
246 module.getDescription(), module, pathParams, true));
247 apis.add(apiForRootPostUri);
251 protected ApiDeclaration createApiDeclaration(String basePath) {
252 ApiDeclaration doc = new ApiDeclaration();
253 doc.setApiVersion(API_VERSION);
254 doc.setSwaggerVersion(SWAGGER_VERSION);
255 doc.setBasePath(basePath);
256 doc.setProduces(Arrays.asList("application/json", "application/xml"));
260 protected String getDataStorePath(String dataStore, String context) {
261 return dataStore + context;
264 private String generateCacheKey(String module, String revision) {
265 return module + "(" + revision + ")";
268 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
269 boolean addConfigApi) {
272 List<Parameter> pathParams = new ArrayList<>(parentPathParams);
274 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
275 LOG.debug("Adding path: [{}]", resourcePath);
276 api.setPath(resourcePath);
278 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
279 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
280 DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
281 childSchemaNodes = dataNodeContainer.getChildNodes();
283 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
286 for (DataSchemaNode childNode : childSchemaNodes) {
287 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
288 // keep config and operation attributes separate.
289 if (childNode.isConfiguration() == addConfigApi) {
290 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
297 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
298 for (DataSchemaNode child : nodes) {
299 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
306 private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
307 List<Operation> operations = new ArrayList<>();
309 Get getBuilder = new Get(node, isConfig);
310 operations.add(getBuilder.pathParams(pathParams).build());
313 Put putBuilder = new Put(node.getQName().getLocalName(),
314 node.getDescription());
315 operations.add(putBuilder.pathParams(pathParams).build());
317 Delete deleteBuilder = new Delete(node);
318 operations.add(deleteBuilder.pathParams(pathParams).build());
320 if (containsListOrContainer(childSchemaNodes)) {
321 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
322 (DataNodeContainer) node, pathParams, isConfig));
328 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
329 List<Operation> operations = new ArrayList<>();
331 Post postBuilder = new Post(name, description, dataNodeContainer);
332 operations.add(postBuilder.pathParams(pathParams).build());
337 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
338 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
339 StringBuilder path = new StringBuilder();
340 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
341 path.append(localName);
343 if ((schemaNode instanceof ListSchemaNode)) {
344 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
345 for (final QName listKey : listKeys) {
346 DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
347 pathListParams.add(((LeafSchemaNode) dataChildByName));
349 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
351 path.append(pathParamIdentifier);
353 Parameter pathParam = new Parameter();
354 pathParam.setName(listKey.getLocalName());
355 pathParam.setDescription(dataChildByName.getDescription());
356 pathParam.setType("string");
357 pathParam.setParamType("path");
359 pathParams.add(pathParam);
362 return path.toString();
365 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
367 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
368 rpc.setPath(resourcePath);
370 Operation operationSpec = new Operation();
371 operationSpec.setMethod("POST");
372 operationSpec.setNotes(rpcDefn.getDescription());
373 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
374 if (rpcDefn.getOutput() != null) {
375 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
377 if (rpcDefn.getInput() != null) {
378 Parameter payload = new Parameter();
379 payload.setParamType("body");
380 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
381 operationSpec.setParameters(Collections.singletonList(payload));
382 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
385 rpc.setOperations(Arrays.asList(operationSpec));
390 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
391 if (schemaContext == null) {
392 return new TreeSet<>();
395 Set<Module> modules = schemaContext.getModules();
397 SortedSet<Module> sortedModules = new TreeSet<>((module1, 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());
409 for (Module m : modules) {
411 sortedModules.add(m);
414 return sortedModules;