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.Date;
26 import java.util.GregorianCalendar;
27 import java.util.List;
29 import java.util.SortedSet;
30 import java.util.TreeSet;
31 import javax.ws.rs.core.UriInfo;
32 import org.json.JSONException;
33 import org.json.JSONObject;
34 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
35 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
36 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
37 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
38 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
39 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
40 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
41 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Delete;
42 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Get;
43 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
44 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Put;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 public class BaseYangSwaggerGenerator {
59 private static final Logger LOG = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class);
61 protected static final String API_VERSION = "1.0.0";
62 protected static final String SWAGGER_VERSION = "1.2";
63 protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
65 static final String MODULE_NAME_SUFFIX = "_module";
66 protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
67 private final ModelGenerator jsonConverter = new ModelGenerator();
69 // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
70 private final ObjectMapper mapper = new ObjectMapper();
72 protected BaseYangSwaggerGenerator() {
73 mapper.registerModule(new JsonOrgModule());
74 mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
80 * @param schemaContext
82 * @return list of modules converted to swagger compliant resource list.
84 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
86 ResourceList resourceList = createResourceList();
88 Set<Module> modules = getSortedModules(schemaContext);
90 List<Resource> resources = new ArrayList<>(modules.size());
92 LOG.info("Modules found [{}]", modules.size());
94 for (Module module : modules) {
95 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
96 Resource resource = new Resource();
97 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
98 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
101 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
102 resources.add(resource);
104 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
108 resourceList.setApis(resources);
113 protected ResourceList createResourceList() {
114 ResourceList resourceList = new ResourceList();
115 resourceList.setApiVersion(API_VERSION);
116 resourceList.setSwaggerVersion(SWAGGER_VERSION);
120 protected String generatePath(UriInfo uriInfo, String name, String revision) {
121 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
122 return uri.toASCIIString();
125 public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
129 if(revision != null && !revision.equals("0000-00-00")) {
130 rev = SIMPLE_DATE_FORMAT.parse(revision);
132 } catch (ParseException e) {
133 throw new IllegalArgumentException(e);
137 Calendar cal = new GregorianCalendar();
141 if(cal.get(Calendar.YEAR) < 1970) {
146 Module m = schemaContext.findModuleByName(module, rev);
147 Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision);
149 return getApiDeclaration(m, rev, uriInfo, context, schemaContext);
152 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
153 String basePath = createBasePathFromUriInfo(uriInfo);
155 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
162 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
163 String portPart = "";
164 int port = uriInfo.getBaseUri().getPort();
166 portPart = ":" + port;
168 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
169 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
174 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
175 ApiDeclaration doc = createApiDeclaration(basePath);
177 List<Api> apis = new ArrayList<>();
179 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
180 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
181 for (DataSchemaNode node : dataSchemaNodes) {
182 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
184 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
186 List<Parameter> pathParams = new ArrayList<>();
187 String resourcePath = getDataStorePath("/config/", context);
188 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
189 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
191 pathParams = new ArrayList<>();
192 resourcePath = getDataStorePath("/operational/", context);
193 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
197 Set<RpcDefinition> rpcs = m.getRpcs();
198 for (RpcDefinition rpcDefinition : rpcs) {
199 String resourcePath = getDataStorePath("/operations/", context);
200 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
203 LOG.debug("Number of APIs found [{}]", apis.size());
205 if (!apis.isEmpty()) {
207 JSONObject models = null;
210 models = jsonConverter.convertToJsonSchema(m, schemaContext);
211 doc.setModels(models);
212 if (LOG.isDebugEnabled()) {
213 LOG.debug(mapper.writeValueAsString(doc));
215 } catch (IOException | JSONException e) {
216 LOG.error("Exception occured in ModelGenerator", e);
224 private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams,
225 final String resourcePath, final List<Api> apis) {
226 if (containsListOrContainer(m.getChildNodes())) {
227 final Api apiForRootPostUri = new Api();
228 apiForRootPostUri.setPath(resourcePath);
229 apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true));
230 apis.add(apiForRootPostUri);
234 protected ApiDeclaration createApiDeclaration(String basePath) {
235 ApiDeclaration doc = new ApiDeclaration();
236 doc.setApiVersion(API_VERSION);
237 doc.setSwaggerVersion(SWAGGER_VERSION);
238 doc.setBasePath(basePath);
239 doc.setProduces(Arrays.asList("application/json", "application/xml"));
243 protected String getDataStorePath(String dataStore, String context) {
244 return dataStore + context;
247 private String generateCacheKey(String module, String revision) {
248 return module + "(" + revision + ")";
251 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
252 boolean addConfigApi) {
255 List<Parameter> pathParams = new ArrayList<>(parentPathParams);
257 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
258 LOG.debug("Adding path: [{}]", resourcePath);
259 api.setPath(resourcePath);
261 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
262 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
263 DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
264 childSchemaNodes = dataNodeContainer.getChildNodes();
266 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
269 for (DataSchemaNode childNode : childSchemaNodes) {
270 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
271 // keep config and operation attributes separate.
272 if (childNode.isConfiguration() == addConfigApi) {
273 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
280 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
281 for (DataSchemaNode child : nodes) {
282 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
294 private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
295 List<Operation> operations = new ArrayList<>();
297 Get getBuilder = new Get(node, isConfig);
298 operations.add(getBuilder.pathParams(pathParams).build());
301 Put putBuilder = new Put(node.getQName().getLocalName(),
302 node.getDescription());
303 operations.add(putBuilder.pathParams(pathParams).build());
305 Delete deleteBuilder = new Delete(node);
306 operations.add(deleteBuilder.pathParams(pathParams).build());
308 if (containsListOrContainer(childSchemaNodes)) {
309 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node,
310 pathParams, isConfig));
321 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
322 List<Operation> operations = new ArrayList<>();
324 Post postBuilder = new Post(name, description, dataNodeContainer);
325 operations.add(postBuilder.pathParams(pathParams).build());
330 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
331 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
332 StringBuilder path = new StringBuilder();
333 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
334 path.append(localName);
336 if ((schemaNode instanceof ListSchemaNode)) {
337 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
338 for (final QName listKey : listKeys) {
339 DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
340 pathListParams.add(((LeafSchemaNode) _dataChildByName));
342 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
344 path.append(pathParamIdentifier);
346 Parameter pathParam = new Parameter();
347 pathParam.setName(listKey.getLocalName());
348 pathParam.setDescription(_dataChildByName.getDescription());
349 pathParam.setType("string");
350 pathParam.setParamType("path");
352 pathParams.add(pathParam);
355 return path.toString();
358 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
360 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
361 rpc.setPath(resourcePath);
363 Operation operationSpec = new Operation();
364 operationSpec.setMethod("POST");
365 operationSpec.setNotes(rpcDefn.getDescription());
366 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
367 if (rpcDefn.getOutput() != null) {
368 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
370 if (rpcDefn.getInput() != null) {
371 Parameter payload = new Parameter();
372 payload.setParamType("body");
373 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
374 operationSpec.setParameters(Collections.singletonList(payload));
375 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
378 rpc.setOperations(Arrays.asList(operationSpec));
383 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
384 if (schemaContext == null) {
385 return new TreeSet<>();
388 Set<Module> modules = schemaContext.getModules();
390 SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
391 int result = module1.getName().compareTo(module2.getName());
393 Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
394 Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
395 result = module1Revision.compareTo(module2Revision);
398 result = module1.getNamespace().compareTo(module2.getNamespace());
402 for (Module m : modules) {
404 sortedModules.add(m);
407 return sortedModules;