Bug 7429 - Upgrade docgen in restconf to the latest draft of ietf-restconf
[netconf.git] / restconf / sal-rest-docgen / src / main / java / org / opendaylight / netconf / sal / rest / doc / impl / BaseYangSwaggerGenerator.java
index fd750b45407860841024ad5ba193f24720e1804d..55c62b24a1b38fa22b1a806b61f325340f91d94b 100644 (file)
@@ -62,6 +62,7 @@ public class BaseYangSwaggerGenerator {
     protected static final String API_VERSION = "1.0.0";
     protected static final String SWAGGER_VERSION = "1.2";
     protected static final String RESTCONF_CONTEXT_ROOT = "restconf";
+    private static final String RESTCONF_DRAFT = "18";
 
     static final String MODULE_NAME_SUFFIX = "_module";
     protected static final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
@@ -69,16 +70,18 @@ public class BaseYangSwaggerGenerator {
 
     // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>()
     private final ObjectMapper mapper = new ObjectMapper();
+    private static boolean newDraft;
 
     protected BaseYangSwaggerGenerator() {
-        mapper.registerModule(new JsonOrgModule());
-        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
+        this.mapper.registerModule(new JsonOrgModule());
+        this.mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
     }
 
     /**
      * Return list of modules converted to swagger compliant resource list.
      */
-    public ResourceList getResourceListing(final UriInfo uriInfo, final SchemaContext schemaContext, final String context) {
+    public ResourceList getResourceListing(final UriInfo uriInfo, final SchemaContext schemaContext,
+            final String context) {
 
         final ResourceList resourceList = createResourceList();
 
@@ -92,7 +95,8 @@ public class BaseYangSwaggerGenerator {
             final String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision());
             final Resource resource = new Resource();
             LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
-            final ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
+            final ApiDeclaration doc =
+                    getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context);
 
             if (doc != null) {
                 resource.setPath(generatePath(uriInfo, module.getName(), revisionString));
@@ -119,11 +123,12 @@ public class BaseYangSwaggerGenerator {
         return uri.toASCIIString();
     }
 
-    public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo, final SchemaContext schemaContext, final String context) {
+    public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo,
+            final SchemaContext schemaContext, final String context) {
         Date rev = null;
 
         try {
-            if (revision != null && !revision.equals("0000-00-00")) {
+            if ((revision != null) && !revision.equals("0000-00-00")) {
                 rev = SIMPLE_DATE_FORMAT.parse(revision);
             }
         } catch (final ParseException e) {
@@ -147,7 +152,8 @@ public class BaseYangSwaggerGenerator {
         return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
     }
 
-    public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo, final String context, final SchemaContext schemaContext) {
+    public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo,
+            final String context, final SchemaContext schemaContext) {
         final String basePath = createBasePathFromUriInfo(uriInfo);
 
         final ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext);
@@ -163,13 +169,14 @@ public class BaseYangSwaggerGenerator {
         if (port != -1) {
             portPart = ":" + port;
         }
-        final String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://")
-                .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT)
-                .toString();
+        final String basePath =
+                new StringBuilder(uriInfo.getBaseUri().getScheme()).append("://").append(uriInfo.getBaseUri().getHost())
+                        .append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT).toString();
         return basePath;
     }
 
-    public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath, final String context, final SchemaContext schemaContext) {
+    public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath, final String context,
+            final SchemaContext schemaContext) {
         final ApiDeclaration doc = createApiDeclaration(basePath);
 
         final List<Api> apis = new ArrayList<>();
@@ -185,34 +192,39 @@ public class BaseYangSwaggerGenerator {
                 String resourcePath;
 
                 /*
-                 * Only when the node's config statement is true, such apis as GET/PUT/POST/DELETE config
-                 * are added for this node.
+                 * Only when the node's config statement is true, such apis as
+                 * GET/PUT/POST/DELETE config are added for this node.
                  */
-                if (node.isConfiguration()) { // This node's config statement is true.
-                    resourcePath = getDataStorePath("/config/", context);
+                if (node.isConfiguration()) { // This node's config statement is
+                                              // true.
+                    resourcePath = getDataStorePath("config", context);
 
                     /*
-                     * When there are two or more top container or list nodes whose config statement is true in module,
-                     * make sure that only one root post link is added for this module.
+                     * When there are two or more top container or list nodes
+                     * whose config statement is true in module, make sure that
+                     * only one root post link is added for this module.
                      */
                     if (!hasAddRootPostLink) {
                         LOG.debug("Has added root post link for module {}", m.getName());
-                        addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis);
+                        addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, "config", apis);
+
                         hasAddRootPostLink = true;
                     }
 
-                    addApis(node, apis, resourcePath, pathParams, schemaContext, true);
+                    addApis(node, apis, resourcePath, pathParams, schemaContext, true, m.getName(), "config");
                 }
-
                 pathParams = new ArrayList<>();
-                resourcePath = getDataStorePath("/operational/", context);
-                addApis(node, apis, resourcePath, pathParams, schemaContext, false);
+                resourcePath = getDataStorePath("operational", context);
+
+                addApis(node, apis, resourcePath, pathParams, schemaContext, false, m.getName(), "operational");
             }
         }
 
         final Set<RpcDefinition> rpcs = m.getRpcs();
         for (final RpcDefinition rpcDefinition : rpcs) {
-            final String resourcePath = getDataStorePath("/operations/", context);
+            final String resourcePath;
+            resourcePath = getDataStorePath("operations", context);
+
             addRpcs(rpcDefinition, apis, resourcePath, schemaContext);
         }
 
@@ -223,10 +235,10 @@ public class BaseYangSwaggerGenerator {
             JSONObject models = null;
 
             try {
-                models = jsonConverter.convertToJsonSchema(m, schemaContext);
+                models = this.jsonConverter.convertToJsonSchema(m, schemaContext);
                 doc.setModels(models);
                 if (LOG.isDebugEnabled()) {
-                    LOG.debug(mapper.writeValueAsString(doc));
+                    LOG.debug(this.mapper.writeValueAsString(doc));
                 }
             } catch (IOException | JSONException e) {
                 LOG.error("Exception occured in ModelGenerator", e);
@@ -238,12 +250,12 @@ public class BaseYangSwaggerGenerator {
     }
 
     private void addRootPostLink(final Module module, final DataNodeContainer node, final List<Parameter> pathParams,
-                                 final String resourcePath, final List<Api> apis) {
+            final String resourcePath, final String dataStore, final List<Api> apis) {
         if (containsListOrContainer(module.getChildNodes())) {
             final Api apiForRootPostUri = new Api();
-            apiForRootPostUri.setPath(resourcePath);
+            apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
             apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
-                    module.getDescription(), module, pathParams, true));
+                    module.getDescription(), module, pathParams, true, ""));
             apis.add(apiForRootPostUri);
         }
     }
@@ -258,60 +270,83 @@ public class BaseYangSwaggerGenerator {
     }
 
     protected String getDataStorePath(final String dataStore, final String context) {
-        return dataStore + context;
+        if (newDraft) {
+            if ("config".contains(dataStore) || "operational".contains(dataStore)) {
+                return "/" + RESTCONF_DRAFT + "/data" + context;
+            } else {
+                return "/" + RESTCONF_DRAFT + "/operations" + context;
+            }
+        } else {
+            return "/" + dataStore + context;
+        }
     }
 
     private String generateCacheKey(final String module, final String revision) {
         return module + "(" + revision + ")";
     }
 
-    private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath, final List<Parameter> parentPathParams, final SchemaContext schemaContext,
-                         final boolean addConfigApi) {
-
+    private void addApis(final DataSchemaNode node, final List<Api> apis, final String parentPath,
+            final List<Parameter> parentPathParams, final SchemaContext schemaContext, final boolean addConfigApi,
+            final String parentName, final String dataStore) {
         final Api api = new Api();
         final List<Parameter> pathParams = new ArrayList<>(parentPathParams);
 
-        final String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/";
+        final String resourcePath = parentPath + "/" + createPath(node, pathParams, schemaContext);
         LOG.debug("Adding path: [{}]", resourcePath);
-        api.setPath(resourcePath);
+        api.setPath(resourcePath.concat(getContent(dataStore)));
 
-        Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
+        Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet();
         if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
             final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
             childSchemaNodes = dataNodeContainer.getChildNodes();
         }
-        api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes));
+        api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes, parentName));
         apis.add(api);
 
         for (final DataSchemaNode childNode : childSchemaNodes) {
-            if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
+            if ((childNode instanceof ListSchemaNode) || (childNode instanceof ContainerSchemaNode)) {
                 // keep config and operation attributes separate.
                 if (childNode.isConfiguration() == addConfigApi) {
-                    addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi);
+                    final String newParent = parentName + "/" + node.getQName().getLocalName();
+                    addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi, newParent,
+                            dataStore);
                 }
             }
         }
+    }
 
+    protected static String getContent(final String dataStore) {
+        if (newDraft) {
+            if ("operational".contains(dataStore)) {
+                return "?content=nonconfig";
+            } else if ("config".contains(dataStore)) {
+                return "?content=config";
+            } else {
+                return "";
+            }
+        } else {
+            return "";
+        }
     }
 
     private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) {
         for (final DataSchemaNode child : nodes) {
-            if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) {
+            if ((child instanceof ListSchemaNode) || (child instanceof ContainerSchemaNode)) {
                 return true;
             }
         }
         return false;
     }
 
-    private List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams, final boolean isConfig, final Iterable<DataSchemaNode> childSchemaNodes) {
+    private List<Operation> operation(final DataSchemaNode node, final List<Parameter> pathParams,
+            final boolean isConfig, final Iterable<DataSchemaNode> childSchemaNodes, final String parentName) {
         final List<Operation> operations = new ArrayList<>();
 
         final Get getBuilder = new Get(node, isConfig);
         operations.add(getBuilder.pathParams(pathParams).build());
 
         if (isConfig) {
-            final Put putBuilder = new Put(node.getQName().getLocalName(),
-                    node.getDescription());
+            final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName);
             operations.add(putBuilder.pathParams(pathParams).build());
 
             final Delete deleteBuilder = new Delete(node);
@@ -319,22 +354,25 @@ public class BaseYangSwaggerGenerator {
 
             if (containsListOrContainer(childSchemaNodes)) {
                 operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
-                        (DataNodeContainer) node, pathParams, isConfig));
+                        (DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
             }
         }
         return operations;
     }
 
-    private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, final List<Parameter> pathParams, final boolean isConfig) {
+    private List<Operation> operationPost(final String name, final String description,
+            final DataNodeContainer dataNodeContainer, final List<Parameter> pathParams, final boolean isConfig,
+            final String parentName) {
         final List<Operation> operations = new ArrayList<>();
         if (isConfig) {
-            final Post postBuilder = new Post(name, description, dataNodeContainer);
+            final Post postBuilder = new Post(name, parentName + name, description, dataNodeContainer);
             operations.add(postBuilder.pathParams(pathParams).build());
         }
         return operations;
     }
 
-    private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams, final SchemaContext schemaContext) {
+    private String createPath(final DataSchemaNode schemaNode, final List<Parameter> pathParams,
+            final SchemaContext schemaContext) {
         final ArrayList<LeafSchemaNode> pathListParams = new ArrayList<>();
         final StringBuilder path = new StringBuilder();
         final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
@@ -342,12 +380,20 @@ public class BaseYangSwaggerGenerator {
 
         if ((schemaNode instanceof ListSchemaNode)) {
             final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
+            StringBuilder keyBuilder = null;
+            if (newDraft) {
+                keyBuilder = new StringBuilder("=");
+            }
+
             for (final QName listKey : listKeys) {
                 final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
                 pathListParams.add(((LeafSchemaNode) dataChildByName));
-
-                final String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}")
-                        .toString();
+                final String pathParamIdentifier;
+                if (newDraft) {
+                    pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}").toString();
+                } else {
+                    pathParamIdentifier = "/{" + listKey.getLocalName() + "}";
+                }
                 path.append(pathParamIdentifier);
 
                 final Parameter pathParam = new Parameter();
@@ -357,14 +403,18 @@ public class BaseYangSwaggerGenerator {
                 pathParam.setParamType("path");
 
                 pathParams.add(pathParam);
+                if (newDraft) {
+                    keyBuilder = new StringBuilder(",");
+                }
             }
         }
         return path.toString();
     }
 
-    protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath, final SchemaContext schemaContext) {
+    protected void addRpcs(final RpcDefinition rpcDefn, final List<Api> apis, final String parentPath,
+            final SchemaContext schemaContext) {
         final Api rpc = new Api();
-        final String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext);
+        final String resourcePath = parentPath + "/" + resolvePathArgumentsName(rpcDefn, schemaContext);
         rpc.setPath(resourcePath);
 
         final Operation operationSpec = new Operation();
@@ -414,4 +464,7 @@ public class BaseYangSwaggerGenerator {
         return sortedModules;
     }
 
+    public void setDraft(final boolean draft) {
+        this.newDraft = draft;
+    }
 }