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 static 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);
78 * Return list of modules converted to swagger compliant resource list.
80 public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) {
82 ResourceList resourceList = createResourceList();
84 Set<Module> modules = getSortedModules(schemaContext);
86 List<Resource> resources = new ArrayList<>(modules.size());
88 LOG.info("Modules found [{}]", modules.size());
90 for (Module module : modules) {
91 String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
92 Resource resource = new Resource();
93 LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
94 ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
97 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
98 resources.add(resource);
100 LOG.warn("Could not generate doc for {},{}", module.getName(), revisionString);
104 resourceList.setApis(resources);
109 protected ResourceList createResourceList() {
110 ResourceList resourceList = new ResourceList();
111 resourceList.setApiVersion(API_VERSION);
112 resourceList.setSwaggerVersion(SWAGGER_VERSION);
116 protected String generatePath(UriInfo uriInfo, String name, String revision) {
117 URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build();
118 return uri.toASCIIString();
121 public ApiDeclaration getApiDeclaration(String moduleName, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) {
125 if (revision != null && !revision.equals("0000-00-00")) {
126 rev = SIMPLE_DATE_FORMAT.parse(revision);
128 } catch (ParseException e) {
129 throw new IllegalArgumentException(e);
133 Calendar cal = new GregorianCalendar();
137 if (cal.get(Calendar.YEAR) < 1970) {
142 Module module = schemaContext.findModuleByName(moduleName, rev);
143 Preconditions.checkArgument(module != null,
144 "Could not find module by name,revision: " + moduleName + "," + revision);
146 return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
149 public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) {
150 String basePath = createBasePathFromUriInfo(uriInfo);
152 ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
159 protected String createBasePathFromUriInfo(UriInfo uriInfo) {
160 String portPart = "";
161 int port = uriInfo.getBaseUri().getPort();
163 portPart = ":" + port;
165 String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
166 .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
171 public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) {
172 ApiDeclaration doc = createApiDeclaration(basePath);
174 List<Api> apis = new ArrayList<>();
176 Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes();
177 LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
178 for (DataSchemaNode node : dataSchemaNodes) {
179 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
181 LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
183 List<Parameter> pathParams = new ArrayList<>();
184 String resourcePath = getDataStorePath("/config/", context);
185 addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
186 addApis(node, apis, resourcePath, pathParams, schemaContext, true);
188 pathParams = new ArrayList<>();
189 resourcePath = getDataStorePath("/operational/", context);
190 addApis(node, apis, resourcePath, pathParams, schemaContext, false);
194 Set<RpcDefinition> rpcs = m.getRpcs();
195 for (RpcDefinition rpcDefinition : rpcs) {
196 String resourcePath = getDataStorePath("/operations/", context);
197 addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
200 LOG.debug("Number of APIs found [{}]", apis.size());
202 if (!apis.isEmpty()) {
204 JSONObject models = null;
207 models = jsonConverter.convertToJsonSchema(m, schemaContext);
208 doc.setModels(models);
209 if (LOG.isDebugEnabled()) {
210 LOG.debug(mapper.writeValueAsString(doc));
212 } catch (IOException | JSONException e) {
213 LOG.error("Exception occured in ModelGenerator", e);
221 private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
222 final String resourcePath, final List<Api> apis) {
223 if (containsListOrContainer(module.getChildNodes())) {
224 final Api apiForRootPostUri = new Api();
225 apiForRootPostUri.setPath(resourcePath);
226 apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
227 module.getDescription(), module, pathParams, true));
228 apis.add(apiForRootPostUri);
232 protected ApiDeclaration createApiDeclaration(String basePath) {
233 ApiDeclaration doc = new ApiDeclaration();
234 doc.setApiVersion(API_VERSION);
235 doc.setSwaggerVersion(SWAGGER_VERSION);
236 doc.setBasePath(basePath);
237 doc.setProduces(Arrays.asList("application/json", "application/xml"));
241 protected String getDataStorePath(String dataStore, String context) {
242 return dataStore + context;
245 private String generateCacheKey(String module, String revision) {
246 return module + "(" + revision + ")";
249 private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext,
250 boolean addConfigApi) {
253 List<Parameter> pathParams = new ArrayList<>(parentPathParams);
255 String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
256 LOG.debug("Adding path: [{}]", resourcePath);
257 api.setPath(resourcePath);
259 Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
260 if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
261 DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
262 childSchemaNodes = dataNodeContainer.getChildNodes();
264 api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
267 for (DataSchemaNode childNode : childSchemaNodes) {
268 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
269 // keep config and operation attributes separate.
270 if (childNode.isConfiguration() == addConfigApi) {
271 addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
278 private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
279 for (DataSchemaNode child : nodes) {
280 if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
287 private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) {
288 List<Operation> operations = new ArrayList<>();
290 Get getBuilder = new Get(node, isConfig);
291 operations.add(getBuilder.pathParams(pathParams).build());
294 Put putBuilder = new Put(node.getQName().getLocalName(),
295 node.getDescription());
296 operations.add(putBuilder.pathParams(pathParams).build());
298 Delete deleteBuilder = new Delete(node);
299 operations.add(deleteBuilder.pathParams(pathParams).build());
301 if (containsListOrContainer(childSchemaNodes)) {
302 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
303 (DataNodeContainer) node, pathParams, isConfig));
309 private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) {
310 List<Operation> operations = new ArrayList<>();
312 Post postBuilder = new Post(name, description, dataNodeContainer);
313 operations.add(postBuilder.pathParams(pathParams).build());
318 private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) {
319 ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
320 StringBuilder path = new StringBuilder();
321 String localName = resolvePathArgumentsName(schemaNode, schemaContext);
322 path.append(localName);
324 if ((schemaNode instanceof ListSchemaNode)) {
325 final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
326 for (final QName listKey : listKeys) {
327 DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
328 pathListParams.add(((LeafSchemaNode) dataChildByName));
330 String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
332 path.append(pathParamIdentifier);
334 Parameter pathParam = new Parameter();
335 pathParam.setName(listKey.getLocalName());
336 pathParam.setDescription(dataChildByName.getDescription());
337 pathParam.setType("string");
338 pathParam.setParamType("path");
340 pathParams.add(pathParam);
343 return path.toString();
346 protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) {
348 String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
349 rpc.setPath(resourcePath);
351 Operation operationSpec = new Operation();
352 operationSpec.setMethod("POST");
353 operationSpec.setNotes(rpcDefn.getDescription());
354 operationSpec.setNickname(rpcDefn.getQName().getLocalName());
355 if (rpcDefn.getOutput() != null) {
356 operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output");
358 if (rpcDefn.getInput() != null) {
359 Parameter payload = new Parameter();
360 payload.setParamType("body");
361 payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input");
362 operationSpec.setParameters(Collections.singletonList(payload));
363 operationSpec.setConsumes(OperationBuilder.CONSUMES_PUT_POST);
366 rpc.setOperations(Arrays.asList(operationSpec));
371 protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) {
372 if (schemaContext == null) {
373 return new TreeSet<>();
376 Set<Module> modules = schemaContext.getModules();
378 SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
379 int result = module1.getName().compareTo(module2.getName());
381 Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
382 Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
383 result = module1Revision.compareTo(module2Revision);
386 result = module1.getNamespace().compareTo(module2.getNamespace());
390 for (Module m : modules) {
392 sortedModules.add(m);
395 return sortedModules;