From: Robert Varga Date: Tue, 10 Jun 2014 12:51:08 +0000 (+0200) Subject: BUG-272: fix issues in sal-rest-docgen X-Git-Tag: release/helium~664^2 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=def85878437256907879623007d53209b5ae8c1c BUG-272: fix issues in sal-rest-docgen This fixes some small issues in sal-rest-docgen. Change-Id: I52e0dd0d4aaed1363f203e81acf3922b4dd285b5 Signed-off-by: Robert Varga --- diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java index 9c180014d7..934412d95a 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java @@ -7,11 +7,13 @@ */ package org.opendaylight.controller.sal.rest.doc; +import java.util.Collection; +import java.util.Collections; + import org.opendaylight.controller.sal.core.api.Broker; import org.opendaylight.controller.sal.core.api.Provider; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.controller.sal.rest.doc.impl.ApiDocGenerator; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; @@ -20,74 +22,69 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collection; -import java.util.Collections; - - -public class DocProvider implements BundleActivator, - ServiceTrackerCustomizer, - Provider, - AutoCloseable { - - private Logger _logger = LoggerFactory.getLogger(DocProvider.class); - - private ServiceTracker brokerServiceTracker; - private BundleContext bundleContext; - private Broker.ProviderSession session; - - @Override - public void close() throws Exception { - stop(bundleContext); - } - - @Override - public void onSessionInitiated(Broker.ProviderSession providerSession) { - SchemaService schemaService = providerSession.getService(SchemaService.class); - ApiDocGenerator.getInstance().setSchemaService(schemaService); - - _logger.debug("Restconf API Explorer started"); - - } - - @Override - public Collection getProviderFunctionality() { - return Collections.emptySet(); - } - - @Override - public void start(BundleContext context) throws Exception { - bundleContext = context; - brokerServiceTracker = new ServiceTracker(context, Broker.class, this); - brokerServiceTracker.open(); - } - - @Override - public void stop(BundleContext context) throws Exception { - if (brokerServiceTracker != null) - brokerServiceTracker.close(); - - if (session != null) - session.close(); - } - - @Override - public Broker addingService(ServiceReference reference) { - Broker broker = bundleContext.getService(reference); - session = broker.registerProvider(this, bundleContext); - return broker; - } - - @Override - public void modifiedService(ServiceReference reference, Broker service) { - if (session != null) - session.close(); - - Broker broker = bundleContext.getService(reference); - session = broker.registerProvider(this, bundleContext); - } - - @Override - public void removedService(ServiceReference reference, Broker service) { - bundleContext.ungetService(reference); - } +public class DocProvider implements BundleActivator, ServiceTrackerCustomizer, Provider, AutoCloseable { + + private static final Logger _logger = LoggerFactory.getLogger(DocProvider.class); + + private ServiceTracker brokerServiceTracker; + private BundleContext bundleContext; + private Broker.ProviderSession session; + + @Override + public void close() throws Exception { + stop(bundleContext); + } + + @Override + public void onSessionInitiated(final Broker.ProviderSession providerSession) { + SchemaService schemaService = providerSession.getService(SchemaService.class); + ApiDocGenerator.getInstance().setSchemaService(schemaService); + + _logger.debug("Restconf API Explorer started"); + } + + @Override + public Collection getProviderFunctionality() { + return Collections.emptySet(); + } + + @Override + public void start(final BundleContext context) throws Exception { + bundleContext = context; + brokerServiceTracker = new ServiceTracker<>(context, Broker.class, this); + brokerServiceTracker.open(); + } + + @Override + public void stop(final BundleContext context) throws Exception { + if (brokerServiceTracker != null) { + brokerServiceTracker.close(); + } + + if (session != null) { + session.close(); + } + } + + @Override + public Broker addingService(final ServiceReference reference) { + Broker broker = bundleContext.getService(reference); + session = broker.registerProvider(this, bundleContext); + return broker; + } + + @Override + public void modifiedService(final ServiceReference reference, final Broker service) { + if (session != null) { + session.close(); + } + + Broker broker = bundleContext.getService(reference); + session = broker.registerProvider(this, bundleContext); + } + + @Override + public void removedService(final ServiceReference reference, final Broker service) { + bundleContext.ungetService(reference); + } } diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGenerator.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGenerator.java index 3662090b87..bcd11bcb06 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGenerator.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGenerator.java @@ -7,137 +7,157 @@ */ package org.opendaylight.controller.sal.rest.doc.impl; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; -import com.google.common.base.Preconditions; +import java.io.IOException; +import java.net.URI; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.UriInfo; + import org.json.JSONException; import org.json.JSONObject; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder; -import org.opendaylight.controller.sal.rest.doc.swagger.*; +import org.opendaylight.controller.sal.rest.doc.swagger.Api; +import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration; +import org.opendaylight.controller.sal.rest.doc.swagger.Operation; +import org.opendaylight.controller.sal.rest.doc.swagger.Parameter; +import org.opendaylight.controller.sal.rest.doc.swagger.Resource; +import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.*; +import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; +import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.Module; +import org.opendaylight.yangtools.yang.model.api.RpcDefinition; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.core.UriInfo; -import java.io.IOException; -import java.net.URI; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; +import com.google.common.base.Preconditions; /** * This class gathers all yang defined {@link Module}s and generates Swagger compliant documentation. */ public class ApiDocGenerator { - private static Logger _logger = LoggerFactory.getLogger(ApiDocGenerator.class); - - private static final ApiDocGenerator INSTANCE = new ApiDocGenerator(); - private ObjectMapper mapper = new ObjectMapper(); - private final ModelGenerator jsonConverter = new ModelGenerator(); - - private SchemaService schemaService; - - private final String API_VERSION = "1.0.0"; - private final String SWAGGER_VERSION = "1.2"; - private final String RESTCONF_CONTEXT_ROOT = "restconf"; - private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - - //For now its {@link HashMap}. It will be changed to thread-safe Map when schema change listener is implemented. - private final Map MODULE_DOC_CACHE = new HashMap(); - - private ApiDocGenerator(){ - mapper.registerModule(new JsonOrgModule()); - mapper.configure(SerializationFeature.INDENT_OUTPUT, true); - } - - /** - * Returns singleton instance - * @return - */ - public static ApiDocGenerator getInstance() { - return INSTANCE; - } - - /** - * - * @param schemaService - */ - public void setSchemaService(SchemaService schemaService) { - this.schemaService = schemaService; - } - /** - * - * @param uriInfo - * @return list of modules converted to swagger compliant resource list. - */ - public ResourceList getResourceListing(UriInfo uriInfo) { - - Preconditions.checkState(schemaService != null); - SchemaContext schemaContext = schemaService.getGlobalContext(); - Preconditions.checkState(schemaContext != null); - - Set modules = schemaContext.getModules(); - - ResourceList resourceList = new ResourceList(); - resourceList.setApiVersion(API_VERSION); - resourceList.setSwaggerVersion(SWAGGER_VERSION); - - List resources = new ArrayList<>(modules.size()); - _logger.info("Modules found [{}]", modules.size()); - - for (Module module : modules) { - Resource resource = new Resource(); - String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision()); - - _logger.debug("Working on [{},{}]...", module.getName(), revisionString); - ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo); - - if (doc != null) { - URI uri = uriInfo.getRequestUriBuilder(). - path(generateCacheKey(module.getName(), revisionString)). - build(); - - resource.setPath(uri.toASCIIString()); - resources.add(resource); - } else { - _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString); - } - } + private static final Logger _logger = LoggerFactory.getLogger(ApiDocGenerator.class); - resourceList.setApis(resources); + private static final ApiDocGenerator INSTANCE = new ApiDocGenerator(); + private final ObjectMapper mapper = new ObjectMapper(); + private final ModelGenerator jsonConverter = new ModelGenerator(); - return resourceList; - } + private SchemaService schemaService; - public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo) { + private static final String API_VERSION = "1.0.0"; + private static final String SWAGGER_VERSION = "1.2"; + private static final String RESTCONF_CONTEXT_ROOT = "restconf"; + private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - //Lookup cache - String cacheKey = generateCacheKey(module, revision); + //For now its {@link HashMap}. It will be changed to thread-safe Map when schema change listener is implemented. + private final Map MODULE_DOC_CACHE = new HashMap(); - if (MODULE_DOC_CACHE.containsKey(cacheKey)) { - _logger.debug("Serving from cache for {}", cacheKey); - return MODULE_DOC_CACHE.get(cacheKey); + private ApiDocGenerator(){ + mapper.registerModule(new JsonOrgModule()); + mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } - Date rev = null; - try { - rev = SIMPLE_DATE_FORMAT.parse(revision); - } catch (ParseException e) { - throw new IllegalArgumentException(e); + /** + * Returns singleton instance + * @return + */ + public static ApiDocGenerator getInstance() { + return INSTANCE; } - SchemaContext schemaContext = schemaService.getGlobalContext(); - Preconditions.checkState(schemaContext != null); + /** + * + * @param schemaService + */ + public void setSchemaService(final SchemaService schemaService) { + this.schemaService = schemaService; + } + /** + * + * @param uriInfo + * @return list of modules converted to swagger compliant resource list. + */ + public ResourceList getResourceListing(final UriInfo uriInfo) { + + Preconditions.checkState(schemaService != null); + SchemaContext schemaContext = schemaService.getGlobalContext(); + Preconditions.checkState(schemaContext != null); + + Set modules = schemaContext.getModules(); + + ResourceList resourceList = new ResourceList(); + resourceList.setApiVersion(API_VERSION); + resourceList.setSwaggerVersion(SWAGGER_VERSION); + + List resources = new ArrayList<>(modules.size()); + _logger.info("Modules found [{}]", modules.size()); + + for (Module module : modules) { + Resource resource = new Resource(); + String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision()); + + _logger.debug("Working on [{},{}]...", module.getName(), revisionString); + ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo); + + if (doc != null) { + URI uri = uriInfo.getRequestUriBuilder(). + path(generateCacheKey(module.getName(), revisionString)). + build(); + + resource.setPath(uri.toASCIIString()); + resources.add(resource); + } else { + _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString); + } + } + + resourceList.setApis(resources); + + return resourceList; + } + + public ApiDeclaration getApiDeclaration(final String module, final String revision, final UriInfo uriInfo) { + + //Lookup cache + String cacheKey = generateCacheKey(module, revision); - Module m = schemaContext.findModuleByName(module, rev); - Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision); + if (MODULE_DOC_CACHE.containsKey(cacheKey)) { + _logger.debug("Serving from cache for {}", cacheKey); + return MODULE_DOC_CACHE.get(cacheKey); + } + + Date rev = null; + try { + rev = SIMPLE_DATE_FORMAT.parse(revision); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } - String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()) + SchemaContext schemaContext = schemaService.getGlobalContext(); + Preconditions.checkState(schemaContext != null); + + Module m = schemaContext.findModuleByName(module, rev); + Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision); + + String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()) .append("://") .append(uriInfo.getBaseUri().getHost()) .append(":") @@ -146,161 +166,161 @@ public class ApiDocGenerator { .append(RESTCONF_CONTEXT_ROOT) .toString(); - ApiDeclaration doc = getSwaggerDocSpec(m, basePath); - MODULE_DOC_CACHE.put(cacheKey, doc); - return doc; - } + ApiDeclaration doc = getSwaggerDocSpec(m, basePath); + MODULE_DOC_CACHE.put(cacheKey, doc); + return doc; + } - public ApiDeclaration getSwaggerDocSpec(Module m, String basePath) { - ApiDeclaration doc = new ApiDeclaration(); - doc.setApiVersion(API_VERSION); - doc.setSwaggerVersion(SWAGGER_VERSION); - doc.setBasePath(basePath); - doc.setProduces(Arrays.asList("application/json", "application/xml")); + public ApiDeclaration getSwaggerDocSpec(final Module m, final String basePath) { + ApiDeclaration doc = new ApiDeclaration(); + doc.setApiVersion(API_VERSION); + doc.setSwaggerVersion(SWAGGER_VERSION); + doc.setBasePath(basePath); + doc.setProduces(Arrays.asList("application/json", "application/xml")); - List apis = new ArrayList(); + List apis = new ArrayList(); - Set dataSchemaNodes = m.getChildNodes(); - _logger.debug("child nodes size [{}]", dataSchemaNodes.size()); - for (DataSchemaNode node : dataSchemaNodes) { - if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { + Set dataSchemaNodes = m.getChildNodes(); + _logger.debug("child nodes size [{}]", dataSchemaNodes.size()); + for (DataSchemaNode node : dataSchemaNodes) { + if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { - _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName()); + _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName()); - List pathParams = null; - if (node.isConfiguration()) { - pathParams = new ArrayList(); - String resourcePath = "/config/" + m.getName() + ":"; - addApis(node, apis, resourcePath, pathParams, true); + List pathParams = null; + if (node.isConfiguration()) { + pathParams = new ArrayList(); + String resourcePath = "/config/" + m.getName() + ":"; + addApis(node, apis, resourcePath, pathParams, true); + } + + pathParams = new ArrayList(); + String resourcePath = "/operational/" + m.getName() + ":"; + addApis(node, apis, resourcePath, pathParams, false); + } } - pathParams = new ArrayList(); - String resourcePath = "/operational/" + m.getName() + ":"; - addApis(node, apis, resourcePath, pathParams, false); - } - } + Set rpcs = m.getRpcs(); + for (RpcDefinition rpcDefinition : rpcs) { + String resourcePath = "/operations/" + m.getName() + ":"; + addRpcs(rpcDefinition, apis, resourcePath); - Set rpcs = m.getRpcs(); - for (RpcDefinition rpcDefinition : rpcs) { - String resourcePath = "/operations/" + m.getName() + ":"; - addRpcs(rpcDefinition, apis, resourcePath); + } + _logger.debug("Number of APIs found [{}]", apis.size()); + doc.setApis(apis); + JSONObject models = null; + + try { + models = jsonConverter.convertToJsonSchema(m); + doc.setModels(models); + _logger.debug(mapper.writeValueAsString(doc)); + } catch (IOException | JSONException e) { + e.printStackTrace(); + } + return doc; } - _logger.debug("Number of APIs found [{}]", apis.size()); - doc.setApis(apis); - JSONObject models = null; - - try { - models = jsonConverter.convertToJsonSchema(m); - doc.setModels(models); - _logger.debug(mapper.writeValueAsString(doc)); - } catch (IOException | JSONException e) { - e.printStackTrace(); + + private String generateCacheKey(final Module m) { + return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision())); } - return doc; - } - - private String generateCacheKey(Module m) { - return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision())); - } - - private String generateCacheKey(String module, String revision) { - return module + "," + revision; - } - - private void addApis(DataSchemaNode node, - List apis, - String parentPath, - List parentPathParams, - boolean addConfigApi) { - - Api api = new Api(); - List pathParams = new ArrayList(parentPathParams); - - String resourcePath = parentPath + createPath(node, pathParams) + "/"; - _logger.debug("Adding path: [{}]", resourcePath); - api.setPath(resourcePath); - api.setOperations(operations(node, pathParams, addConfigApi)); - apis.add(api); - if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { - DataNodeContainer schemaNode = (DataNodeContainer) node; - Set dataSchemaNodes = schemaNode.getChildNodes(); - - for (DataSchemaNode childNode : dataSchemaNodes) { - addApis(childNode, apis, resourcePath, pathParams, addConfigApi); - } + private String generateCacheKey(final String module, final String revision) { + return module + "," + revision; } - } + private void addApis(final DataSchemaNode node, + final List apis, + final String parentPath, + final List parentPathParams, + final boolean addConfigApi) { + + Api api = new Api(); + List pathParams = new ArrayList(parentPathParams); + + String resourcePath = parentPath + createPath(node, pathParams) + "/"; + _logger.debug("Adding path: [{}]", resourcePath); + api.setPath(resourcePath); + api.setOperations(operations(node, pathParams, addConfigApi)); + apis.add(api); + if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { + DataNodeContainer schemaNode = (DataNodeContainer) node; + Set dataSchemaNodes = schemaNode.getChildNodes(); + + for (DataSchemaNode childNode : dataSchemaNodes) { + addApis(childNode, apis, resourcePath, pathParams, addConfigApi); + } + } - private void addRpcs(RpcDefinition rpcDefn, List apis, String parentPath) { - Api rpc = new Api(); - String resourcePath = parentPath + rpcDefn.getQName().getLocalName(); - rpc.setPath(resourcePath); + } + + private void addRpcs(final RpcDefinition rpcDefn, final List apis, final String parentPath) { + Api rpc = new Api(); + String resourcePath = parentPath + rpcDefn.getQName().getLocalName(); + rpc.setPath(resourcePath); - Operation operationSpec = new Operation(); - operationSpec.setMethod("POST"); - operationSpec.setNotes(rpcDefn.getDescription()); - operationSpec.setNickname(rpcDefn.getQName().getLocalName()); - rpc.setOperations(Arrays.asList(operationSpec)); + Operation operationSpec = new Operation(); + operationSpec.setMethod("POST"); + operationSpec.setNotes(rpcDefn.getDescription()); + operationSpec.setNickname(rpcDefn.getQName().getLocalName()); + rpc.setOperations(Arrays.asList(operationSpec)); - apis.add(rpc); - } + apis.add(rpc); + } - /** - * @param node - * @param pathParams - * @return - */ - private List operations(DataSchemaNode node, List pathParams, boolean isConfig) { - List operations = new ArrayList<>(); + /** + * @param node + * @param pathParams + * @return + */ + private List operations(final DataSchemaNode node, final List pathParams, final boolean isConfig) { + List operations = new ArrayList<>(); - OperationBuilder.Get getBuilder = new OperationBuilder.Get(node); - operations.add(getBuilder.pathParams(pathParams).build()); + OperationBuilder.Get getBuilder = new OperationBuilder.Get(node); + operations.add(getBuilder.pathParams(pathParams).build()); - if (isConfig) { - OperationBuilder.Post postBuilder = new OperationBuilder.Post(node); - operations.add(postBuilder.pathParams(pathParams).build()); + if (isConfig) { + OperationBuilder.Post postBuilder = new OperationBuilder.Post(node); + operations.add(postBuilder.pathParams(pathParams).build()); - OperationBuilder.Put putBuilder = new OperationBuilder.Put(node); - operations.add(putBuilder.pathParams(pathParams).build()); + OperationBuilder.Put putBuilder = new OperationBuilder.Put(node); + operations.add(putBuilder.pathParams(pathParams).build()); - OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node); - operations.add(deleteBuilder.pathParams(pathParams).build()); + OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node); + operations.add(deleteBuilder.pathParams(pathParams).build()); + } + return operations; } - return operations; - } - - private String createPath(final DataSchemaNode schemaNode, List pathParams) { - ArrayList pathListParams = new ArrayList(); - StringBuilder path = new StringBuilder(); - QName _qName = schemaNode.getQName(); - String localName = _qName.getLocalName(); - path.append(localName); - - if ((schemaNode instanceof ListSchemaNode)) { - final List listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition(); - for (final QName listKey : listKeys) { - { - DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey); - pathListParams.add(((LeafSchemaNode) _dataChildByName)); - - String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}").toString(); - path.append(pathParamIdentifier); - - Parameter pathParam = new Parameter(); - pathParam.setName(listKey.getLocalName()); - pathParam.setDescription(_dataChildByName.getDescription()); - pathParam.setType("string"); - pathParam.setParamType("path"); - - pathParams.add(pathParam); + + private String createPath(final DataSchemaNode schemaNode, final List pathParams) { + ArrayList pathListParams = new ArrayList(); + StringBuilder path = new StringBuilder(); + QName _qName = schemaNode.getQName(); + String localName = _qName.getLocalName(); + path.append(localName); + + if ((schemaNode instanceof ListSchemaNode)) { + final List listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition(); + for (final QName listKey : listKeys) { + { + DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey); + pathListParams.add(((LeafSchemaNode) _dataChildByName)); + + String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}").toString(); + path.append(pathParamIdentifier); + + Parameter pathParam = new Parameter(); + pathParam.setName(listKey.getLocalName()); + pathParam.setDescription(_dataChildByName.getDescription()); + pathParam.setType("string"); + pathParam.setParamType("path"); + + pathParams.add(pathParam); + } + } } - } + return path.toString(); } - return path.toString(); - } } diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java index b2c258825e..719dd78064 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java @@ -7,492 +7,524 @@ */ package org.opendaylight.controller.sal.rest.doc.impl; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.opendaylight.yangtools.yang.model.api.*; -import org.opendaylight.yangtools.yang.model.api.type.*; +import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.ChoiceNode; +import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; +import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.Module; +import org.opendaylight.yangtools.yang.model.api.RpcDefinition; +import org.opendaylight.yangtools.yang.model.api.TypeDefinition; +import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition; +import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit; import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair; -import org.opendaylight.yangtools.yang.model.util.*; +import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; +import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; +import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; +import org.opendaylight.yangtools.yang.model.util.BooleanType; +import org.opendaylight.yangtools.yang.model.util.Decimal64; +import org.opendaylight.yangtools.yang.model.util.EnumerationType; +import org.opendaylight.yangtools.yang.model.util.ExtendedType; +import org.opendaylight.yangtools.yang.model.util.Int16; +import org.opendaylight.yangtools.yang.model.util.Int32; +import org.opendaylight.yangtools.yang.model.util.Int64; +import org.opendaylight.yangtools.yang.model.util.Int8; +import org.opendaylight.yangtools.yang.model.util.StringType; +import org.opendaylight.yangtools.yang.model.util.Uint16; +import org.opendaylight.yangtools.yang.model.util.Uint32; +import org.opendaylight.yangtools.yang.model.util.Uint64; +import org.opendaylight.yangtools.yang.model.util.Uint8; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.*; - /** * Generates JSON Schema for data defined in Yang */ public class ModelGenerator { - private static Logger _logger = LoggerFactory.getLogger(ModelGenerator.class); - - private static final String BASE_64 = "base64"; - private static final String BINARY_ENCODING_KEY = "binaryEncoding"; - private static final String MEDIA_KEY = "media"; - private static final String ONE_OF_KEY = "oneOf"; - private static final String UNIQUE_ITEMS_KEY = "uniqueItems"; - private static final String MAX_ITEMS = "maxItems"; - private static final String MIN_ITEMS = "minItems"; - private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema"; - private static final String SCHEMA_KEY = "$schema"; - private static final String MAX_LENGTH_KEY = "maxLength"; - private static final String MIN_LENGTH_KEY = "minLength"; - private static final String REQUIRED_KEY = "required"; - private static final String REF_KEY = "$ref"; - private static final String ITEMS_KEY = "items"; - private static final String TYPE_KEY = "type"; - private static final String PROPERTIES_KEY = "properties"; - private static final String DESCRIPTION_KEY = "description"; - private static final String OBJECT_TYPE = "object"; - private static final String ARRAY_TYPE = "array"; - private static final String ENUM = "enum"; - private static final String INTEGER = "integer"; - private static final String NUMBER = "number"; - private static final String BOOLEAN = "boolean"; - private static final String STRING = "string"; - - private static final Map>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING; - - static { - Map>, String> tempMap1 = new HashMap>, String>(10); - tempMap1.put(StringType.class , STRING); - tempMap1.put(BooleanType.class , BOOLEAN); - tempMap1.put(Int8.class , INTEGER); - tempMap1.put(Int16.class , INTEGER); - tempMap1.put(Int32.class , INTEGER); - tempMap1.put(Int64.class , INTEGER); - tempMap1.put(Uint16.class , INTEGER); - tempMap1.put(Uint32.class , INTEGER); - tempMap1.put(Uint64.class , INTEGER); - tempMap1.put(Uint8.class , INTEGER); - tempMap1.put(Decimal64.class , NUMBER); - tempMap1.put(EnumerationType.class , ENUM); - //TODO: Binary type - - YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1); - } - - public ModelGenerator(){ - } - - public JSONObject convertToJsonSchema(Module module) throws IOException, JSONException { - JSONObject models = new JSONObject(); - processContainers(module, models); - processRPCs(module, models); - - return models; - } - - - - private void processContainers(Module module, JSONObject models) throws IOException, JSONException { - - String moduleName = module.getName(); - Set childNodes = module.getChildNodes(); - - for(DataSchemaNode childNode : childNodes){ - JSONObject moduleJSON=null; - String filename = childNode.getQName().getLocalName(); + private static final Logger _logger = LoggerFactory.getLogger(ModelGenerator.class); + + private static final String BASE_64 = "base64"; + private static final String BINARY_ENCODING_KEY = "binaryEncoding"; + private static final String MEDIA_KEY = "media"; + private static final String ONE_OF_KEY = "oneOf"; + private static final String UNIQUE_ITEMS_KEY = "uniqueItems"; + private static final String MAX_ITEMS = "maxItems"; + private static final String MIN_ITEMS = "minItems"; + private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema"; + private static final String SCHEMA_KEY = "$schema"; + private static final String MAX_LENGTH_KEY = "maxLength"; + private static final String MIN_LENGTH_KEY = "minLength"; + private static final String REQUIRED_KEY = "required"; + private static final String REF_KEY = "$ref"; + private static final String ITEMS_KEY = "items"; + private static final String TYPE_KEY = "type"; + private static final String PROPERTIES_KEY = "properties"; + private static final String DESCRIPTION_KEY = "description"; + private static final String OBJECT_TYPE = "object"; + private static final String ARRAY_TYPE = "array"; + private static final String ENUM = "enum"; + private static final String INTEGER = "integer"; + private static final String NUMBER = "number"; + private static final String BOOLEAN = "boolean"; + private static final String STRING = "string"; + + private static final Map>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING; + + static { + Map>, String> tempMap1 = new HashMap>, String>(10); + tempMap1.put(StringType.class , STRING); + tempMap1.put(BooleanType.class , BOOLEAN); + tempMap1.put(Int8.class , INTEGER); + tempMap1.put(Int16.class , INTEGER); + tempMap1.put(Int32.class , INTEGER); + tempMap1.put(Int64.class , INTEGER); + tempMap1.put(Uint16.class , INTEGER); + tempMap1.put(Uint32.class , INTEGER); + tempMap1.put(Uint64.class , INTEGER); + tempMap1.put(Uint8.class , INTEGER); + tempMap1.put(Decimal64.class , NUMBER); + tempMap1.put(EnumerationType.class , ENUM); + //TODO: Binary type + + YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1); + } + + public ModelGenerator(){ + } + + public JSONObject convertToJsonSchema(final Module module) throws IOException, JSONException { + JSONObject models = new JSONObject(); + processContainers(module, models); + processRPCs(module, models); + + return models; + } + + + + private void processContainers(final Module module, final JSONObject models) throws IOException, JSONException { + + String moduleName = module.getName(); + Set childNodes = module.getChildNodes(); + + for(DataSchemaNode childNode : childNodes){ + JSONObject moduleJSON=null; + String filename = childNode.getQName().getLocalName(); /* * For every container in the module */ - if(childNode instanceof ContainerSchemaNode) { - moduleJSON = processContainer((ContainerSchemaNode)childNode, moduleName, true, models); - } - - if(moduleJSON!=null) { - _logger.debug("Adding model for [{}]", filename); - moduleJSON.put("id", filename); - models.put(filename, moduleJSON); - } - } + if(childNode instanceof ContainerSchemaNode) { + moduleJSON = processContainer((ContainerSchemaNode)childNode, moduleName, true, models); + } + + if(moduleJSON!=null) { + _logger.debug("Adding model for [{}]", filename); + moduleJSON.put("id", filename); + models.put(filename, moduleJSON); + } + } - } - - - /** - * Process the RPCs for a Module - * Spits out a file each of the name -input.json - * and -output.json for each RPC that contains - * input & output elements - * - * @param module - * @throws JSONException - * @throws IOException - */ - private void processRPCs(Module module, JSONObject models) throws JSONException, IOException { - - Set rpcs = module.getRpcs(); - String moduleName = module.getName(); - for(RpcDefinition rpc: rpcs) { - - ContainerSchemaNode input = rpc.getInput(); - if(input!=null) { - JSONObject inputJSON = processContainer(input, moduleName, true, models); - String filename = rpc.getQName().getLocalName() + "-input"; - inputJSON.put("id", filename); - //writeToFile(filename, inputJSON.toString(2), moduleName); - models.put(filename, inputJSON); - } - - ContainerSchemaNode output = rpc.getOutput(); - if(output!=null) { - JSONObject outputJSON = processContainer(output, moduleName, true, models); - String filename = rpc.getQName().getLocalName() + "-output"; - outputJSON.put("id", filename); - models.put(filename, outputJSON); - } } - } - - - /** - * Processes the container node and populates the moduleJSON - * - * @param container - * @param moduleName - * @throws JSONException - * @throws IOException - */ - private JSONObject processContainer(ContainerSchemaNode container, String moduleName, boolean addSchemaStmt, JSONObject models) throws JSONException, IOException{ - JSONObject moduleJSON = getSchemaTemplate(); - if(addSchemaStmt) { - moduleJSON = getSchemaTemplate(); - } else { - moduleJSON = new JSONObject(); + + + /** + * Process the RPCs for a Module + * Spits out a file each of the name -input.json + * and -output.json for each RPC that contains + * input & output elements + * + * @param module + * @throws JSONException + * @throws IOException + */ + private void processRPCs(final Module module, final JSONObject models) throws JSONException, IOException { + + Set rpcs = module.getRpcs(); + String moduleName = module.getName(); + for(RpcDefinition rpc: rpcs) { + + ContainerSchemaNode input = rpc.getInput(); + if(input!=null) { + JSONObject inputJSON = processContainer(input, moduleName, true, models); + String filename = rpc.getQName().getLocalName() + "-input"; + inputJSON.put("id", filename); + //writeToFile(filename, inputJSON.toString(2), moduleName); + models.put(filename, inputJSON); + } + + ContainerSchemaNode output = rpc.getOutput(); + if(output!=null) { + JSONObject outputJSON = processContainer(output, moduleName, true, models); + String filename = rpc.getQName().getLocalName() + "-output"; + outputJSON.put("id", filename); + models.put(filename, outputJSON); + } + } } - moduleJSON.put(TYPE_KEY, OBJECT_TYPE); - - String containerDescription = container.getDescription(); - moduleJSON.put(DESCRIPTION_KEY, containerDescription); - - Set containerChildren = ((ContainerSchemaNode)container).getChildNodes(); - JSONObject properties = processChildren(containerChildren, moduleName, models); - moduleJSON.put(PROPERTIES_KEY, properties); - return moduleJSON; - } - - /** - * Processes the nodes - * @param nodes - * @param moduleName - * @return - * @throws JSONException - * @throws IOException - */ - private JSONObject processChildren(Set nodes, String moduleName, JSONObject models) throws JSONException, IOException { - - JSONObject properties = new JSONObject(); - - for(DataSchemaNode node : nodes){ - String name = node.getQName().getLocalName(); - JSONObject property = null; - if(node instanceof LeafSchemaNode) { - property = processLeafNode((LeafSchemaNode)node); - } else if (node instanceof ListSchemaNode) { - property = processListSchemaNode((ListSchemaNode)node, moduleName, models); - - } else if (node instanceof LeafListSchemaNode) { - property = processLeafListNode((LeafListSchemaNode)node); - - } else if (node instanceof ChoiceNode) { - property = processChoiceNode((ChoiceNode)node, moduleName, models); - - } else if (node instanceof AnyXmlSchemaNode) { - property = processAnyXMLNode((AnyXmlSchemaNode)node); - - } else if (node instanceof ContainerSchemaNode) { - property = processContainer((ContainerSchemaNode)node, moduleName, false, models); - - } else { - throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass()); - } - - property.putOpt(DESCRIPTION_KEY, node.getDescription()); - properties.put(name, property); + + + /** + * Processes the container node and populates the moduleJSON + * + * @param container + * @param moduleName + * @throws JSONException + * @throws IOException + */ + private JSONObject processContainer(final ContainerSchemaNode container, final String moduleName, final boolean addSchemaStmt, final JSONObject models) throws JSONException, IOException{ + JSONObject moduleJSON = getSchemaTemplate(); + if(addSchemaStmt) { + moduleJSON = getSchemaTemplate(); + } else { + moduleJSON = new JSONObject(); + } + moduleJSON.put(TYPE_KEY, OBJECT_TYPE); + + String containerDescription = container.getDescription(); + moduleJSON.put(DESCRIPTION_KEY, containerDescription); + + Set containerChildren = container.getChildNodes(); + JSONObject properties = processChildren(containerChildren, moduleName, models); + moduleJSON.put(PROPERTIES_KEY, properties); + return moduleJSON; } - return properties; - } - - /** - * - * @param listNode - * @throws JSONException - */ - private JSONObject processLeafListNode(LeafListSchemaNode listNode) throws JSONException { - JSONObject props = new JSONObject(); - props.put(TYPE_KEY, ARRAY_TYPE); - - JSONObject itemsVal = new JSONObject(); - processTypeDef(listNode.getType(), itemsVal); - props.put(ITEMS_KEY, itemsVal); - - ConstraintDefinition constraints = listNode.getConstraints(); - processConstraints(constraints, props); - - return props; - } - - /** - * - * @param choiceNode - * @param moduleName - * @throws JSONException - * @throws IOException - */ - private JSONObject processChoiceNode(ChoiceNode choiceNode, String moduleName, JSONObject models) throws JSONException, IOException { - - Set cases = choiceNode.getCases(); - - JSONArray choiceProps = new JSONArray(); - for(ChoiceCaseNode choiceCase: cases) { - String choiceName = choiceCase.getQName().getLocalName(); - JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models); - JSONObject choiceObj = new JSONObject(); - choiceObj.put(choiceName, choiceProp); - choiceObj.put(TYPE_KEY, OBJECT_TYPE); - choiceProps.put(choiceObj); + + /** + * Processes the nodes + * @param nodes + * @param moduleName + * @return + * @throws JSONException + * @throws IOException + */ + private JSONObject processChildren(final Set nodes, final String moduleName, final JSONObject models) throws JSONException, IOException { + + JSONObject properties = new JSONObject(); + + for(DataSchemaNode node : nodes){ + String name = node.getQName().getLocalName(); + JSONObject property = null; + if(node instanceof LeafSchemaNode) { + property = processLeafNode((LeafSchemaNode)node); + } else if (node instanceof ListSchemaNode) { + property = processListSchemaNode((ListSchemaNode)node, moduleName, models); + + } else if (node instanceof LeafListSchemaNode) { + property = processLeafListNode((LeafListSchemaNode)node); + + } else if (node instanceof ChoiceNode) { + property = processChoiceNode((ChoiceNode)node, moduleName, models); + + } else if (node instanceof AnyXmlSchemaNode) { + property = processAnyXMLNode((AnyXmlSchemaNode)node); + + } else if (node instanceof ContainerSchemaNode) { + property = processContainer((ContainerSchemaNode)node, moduleName, false, models); + + } else { + throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass()); + } + + property.putOpt(DESCRIPTION_KEY, node.getDescription()); + properties.put(name, property); + } + return properties; } - JSONObject oneOfProps = new JSONObject(); - oneOfProps.put(ONE_OF_KEY, choiceProps); - oneOfProps.put(TYPE_KEY, OBJECT_TYPE); + /** + * + * @param listNode + * @throws JSONException + */ + private JSONObject processLeafListNode(final LeafListSchemaNode listNode) throws JSONException { + JSONObject props = new JSONObject(); + props.put(TYPE_KEY, ARRAY_TYPE); - return oneOfProps; - } + JSONObject itemsVal = new JSONObject(); + processTypeDef(listNode.getType(), itemsVal); + props.put(ITEMS_KEY, itemsVal); + ConstraintDefinition constraints = listNode.getConstraints(); + processConstraints(constraints, props); - /** - * - * @param constraints - * @param props - * @throws JSONException - */ - private void processConstraints(ConstraintDefinition constraints, JSONObject props) throws JSONException { - boolean isMandatory = constraints.isMandatory(); - props.put(REQUIRED_KEY, isMandatory); + return props; + } - Integer minElements = constraints.getMinElements(); - Integer maxElements = constraints.getMaxElements(); - if(minElements !=null) { - props.put(MIN_ITEMS, minElements); + /** + * + * @param choiceNode + * @param moduleName + * @throws JSONException + * @throws IOException + */ + private JSONObject processChoiceNode(final ChoiceNode choiceNode, final String moduleName, final JSONObject models) throws JSONException, IOException { + + Set cases = choiceNode.getCases(); + + JSONArray choiceProps = new JSONArray(); + for(ChoiceCaseNode choiceCase: cases) { + String choiceName = choiceCase.getQName().getLocalName(); + JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models); + JSONObject choiceObj = new JSONObject(); + choiceObj.put(choiceName, choiceProp); + choiceObj.put(TYPE_KEY, OBJECT_TYPE); + choiceProps.put(choiceObj); + } + + JSONObject oneOfProps = new JSONObject(); + oneOfProps.put(ONE_OF_KEY, choiceProps); + oneOfProps.put(TYPE_KEY, OBJECT_TYPE); + + return oneOfProps; } - if(maxElements !=null) { - props.put(MAX_ITEMS, maxElements); + + + /** + * + * @param constraints + * @param props + * @throws JSONException + */ + private void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException { + boolean isMandatory = constraints.isMandatory(); + props.put(REQUIRED_KEY, isMandatory); + + Integer minElements = constraints.getMinElements(); + Integer maxElements = constraints.getMaxElements(); + if(minElements !=null) { + props.put(MIN_ITEMS, minElements); + } + if(maxElements !=null) { + props.put(MAX_ITEMS, maxElements); + } } - } - - /** - * Parses a ListSchema node. - * - * Due to a limitation of the RAML--->JAX-RS tool, sub-properties - * must be in a separate JSON schema file. Hence, we have to write - * some properties to a new file, while continuing to process the rest. - * - * @param listNode - * @param moduleName - * @return - * @throws JSONException - * @throws IOException - */ - private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName, JSONObject models) throws JSONException, IOException { - - Set listChildren = listNode.getChildNodes(); - String fileName = listNode.getQName().getLocalName(); - - JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models); - JSONObject childSchema = getSchemaTemplate(); - childSchema.put(TYPE_KEY, OBJECT_TYPE); - childSchema.put(PROPERTIES_KEY, childSchemaProperties); + + /** + * Parses a ListSchema node. + * + * Due to a limitation of the RAML--->JAX-RS tool, sub-properties + * must be in a separate JSON schema file. Hence, we have to write + * some properties to a new file, while continuing to process the rest. + * + * @param listNode + * @param moduleName + * @return + * @throws JSONException + * @throws IOException + */ + private JSONObject processListSchemaNode(final ListSchemaNode listNode, final String moduleName, final JSONObject models) throws JSONException, IOException { + + Set listChildren = listNode.getChildNodes(); + String fileName = listNode.getQName().getLocalName(); + + JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models); + JSONObject childSchema = getSchemaTemplate(); + childSchema.put(TYPE_KEY, OBJECT_TYPE); + childSchema.put(PROPERTIES_KEY, childSchemaProperties); /* * Due to a limitation of the RAML--->JAX-RS tool, sub-properties * must be in a separate JSON schema file. Hence, we have to write * some properties to a new file, while continuing to process the rest. */ - //writeToFile(fileName, childSchema.toString(2), moduleName); - childSchema.put("id", fileName); - models.put(fileName, childSchema); - - - JSONObject listNodeProperties = new JSONObject(); - listNodeProperties.put(TYPE_KEY, ARRAY_TYPE); - - JSONObject items = new JSONObject(); - items.put(REF_KEY,fileName ); - listNodeProperties.put(ITEMS_KEY, items); - - return listNodeProperties; - - } - - /** - * - * @param leafNode - * @return - * @throws JSONException - */ - private JSONObject processLeafNode(LeafSchemaNode leafNode) throws JSONException { - JSONObject property = new JSONObject(); - - String leafDescription = leafNode.getDescription(); - property.put(DESCRIPTION_KEY, leafDescription); - - processConstraints(leafNode.getConstraints(), property); - processTypeDef(leafNode.getType(), property); - - return property; - } - - /** - * - * @param leafNode - * @return - * @throws JSONException - */ - private JSONObject processAnyXMLNode(AnyXmlSchemaNode leafNode) throws JSONException { - JSONObject property = new JSONObject(); - - String leafDescription = leafNode.getDescription(); - property.put(DESCRIPTION_KEY, leafDescription); - - processConstraints(leafNode.getConstraints(), property); - - return property; - } - - /** - * @param property - * @throws JSONException - */ - private void processTypeDef(TypeDefinition leafTypeDef, JSONObject property) throws JSONException { - - if(leafTypeDef instanceof ExtendedType){ - processExtendedType(leafTypeDef, property); - } else if (leafTypeDef instanceof EnumerationType) { - processEnumType((EnumerationType)leafTypeDef, property); - - } else if (leafTypeDef instanceof BitsTypeDefinition) { - processBitsType((BitsTypeDefinition)leafTypeDef, property); - - } else if (leafTypeDef instanceof UnionTypeDefinition) { - processUnionType((UnionTypeDefinition)leafTypeDef, property); - - } else if (leafTypeDef instanceof IdentityrefTypeDefinition) { - property.putOpt(TYPE_KEY, "object"); - } else if (leafTypeDef instanceof BinaryTypeDefinition) { - processBinaryType((BinaryTypeDefinition)leafTypeDef, property); - } else { - //System.out.println("In else: " + leafTypeDef.getClass()); - String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass()); - if(jsonType==null) { - jsonType = "object"; - } - property.putOpt(TYPE_KEY, jsonType); + //writeToFile(fileName, childSchema.toString(2), moduleName); + childSchema.put("id", fileName); + models.put(fileName, childSchema); + + + JSONObject listNodeProperties = new JSONObject(); + listNodeProperties.put(TYPE_KEY, ARRAY_TYPE); + + JSONObject items = new JSONObject(); + items.put(REF_KEY,fileName ); + listNodeProperties.put(ITEMS_KEY, items); + + return listNodeProperties; + } - } - - /** - * - * @param leafTypeDef - * @param property - * @throws JSONException - */ - private void processExtendedType(TypeDefinition leafTypeDef, JSONObject property) throws JSONException { - Object leafBaseType = leafTypeDef.getBaseType(); - if(leafBaseType instanceof ExtendedType){ - //recursively process an extended type until we hit a base type - processExtendedType((TypeDefinition)leafBaseType, property); - } else { - List lengthConstraints = ((ExtendedType) leafTypeDef).getLengthConstraints(); - for(LengthConstraint lengthConstraint: lengthConstraints) { - Number min = lengthConstraint.getMin(); - Number max = lengthConstraint.getMax(); - property.putOpt(MIN_LENGTH_KEY, min); - property.putOpt(MAX_LENGTH_KEY, max); - } - String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass()); - property.putOpt(TYPE_KEY,jsonType ); + + /** + * + * @param leafNode + * @return + * @throws JSONException + */ + private JSONObject processLeafNode(final LeafSchemaNode leafNode) throws JSONException { + JSONObject property = new JSONObject(); + + String leafDescription = leafNode.getDescription(); + property.put(DESCRIPTION_KEY, leafDescription); + + processConstraints(leafNode.getConstraints(), property); + processTypeDef(leafNode.getType(), property); + + return property; } - } - - /* - * - */ - private void processBinaryType(BinaryTypeDefinition binaryType, JSONObject property) throws JSONException { - property.put(TYPE_KEY, STRING); - JSONObject media = new JSONObject(); - media.put(BINARY_ENCODING_KEY, BASE_64); - property.put(MEDIA_KEY, media); - } - - /** - * - * @param enumLeafType - * @param property - * @throws JSONException - */ - private void processEnumType(EnumerationType enumLeafType, JSONObject property) throws JSONException { - List enumPairs = enumLeafType.getValues(); - List enumNames = new ArrayList(); - for(EnumPair enumPair: enumPairs) { - enumNames.add(enumPair.getName()); + /** + * + * @param leafNode + * @return + * @throws JSONException + */ + private JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException { + JSONObject property = new JSONObject(); + + String leafDescription = leafNode.getDescription(); + property.put(DESCRIPTION_KEY, leafDescription); + + processConstraints(leafNode.getConstraints(), property); + + return property; } - property.putOpt(ENUM, new JSONArray(enumNames)); - } - - /** - * - * @param bitsType - * @param property - * @throws JSONException - */ - private void processBitsType(BitsTypeDefinition bitsType, JSONObject property) throws JSONException{ - property.put(TYPE_KEY, ARRAY_TYPE); - property.put(MIN_ITEMS, 0); - property.put(UNIQUE_ITEMS_KEY, true); - JSONArray enumValues = new JSONArray(); - - List bits = bitsType.getBits(); - for(Bit bit: bits) { - enumValues.put(bit.getName()); + + /** + * @param property + * @throws JSONException + */ + private void processTypeDef(final TypeDefinition leafTypeDef, final JSONObject property) throws JSONException { + + if(leafTypeDef instanceof ExtendedType){ + processExtendedType(leafTypeDef, property); + } else if (leafTypeDef instanceof EnumerationType) { + processEnumType((EnumerationType)leafTypeDef, property); + + } else if (leafTypeDef instanceof BitsTypeDefinition) { + processBitsType((BitsTypeDefinition)leafTypeDef, property); + + } else if (leafTypeDef instanceof UnionTypeDefinition) { + processUnionType((UnionTypeDefinition)leafTypeDef, property); + + } else if (leafTypeDef instanceof IdentityrefTypeDefinition) { + property.putOpt(TYPE_KEY, "object"); + } else if (leafTypeDef instanceof BinaryTypeDefinition) { + processBinaryType((BinaryTypeDefinition)leafTypeDef, property); + } else { + //System.out.println("In else: " + leafTypeDef.getClass()); + String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass()); + if(jsonType==null) { + jsonType = "object"; + } + property.putOpt(TYPE_KEY, jsonType); + } } - JSONObject itemsValue = new JSONObject(); - itemsValue.put(ENUM, enumValues); - property.put(ITEMS_KEY, itemsValue); - } - - - /** - * - * @param unionType - * @param property - * @throws JSONException - */ - private void processUnionType(UnionTypeDefinition unionType, JSONObject property) throws JSONException{ - - List> unionTypes = unionType.getTypes(); - JSONArray unionArray = new JSONArray(); - for(TypeDefinition typeDef: unionTypes) { - unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass())); + + /** + * + * @param leafTypeDef + * @param property + * @throws JSONException + */ + private void processExtendedType(final TypeDefinition leafTypeDef, final JSONObject property) throws JSONException { + Object leafBaseType = leafTypeDef.getBaseType(); + if(leafBaseType instanceof ExtendedType){ + //recursively process an extended type until we hit a base type + processExtendedType((TypeDefinition)leafBaseType, property); + } else { + List lengthConstraints = ((ExtendedType) leafTypeDef).getLengthConstraints(); + for(LengthConstraint lengthConstraint: lengthConstraints) { + Number min = lengthConstraint.getMin(); + Number max = lengthConstraint.getMax(); + property.putOpt(MIN_LENGTH_KEY, min); + property.putOpt(MAX_LENGTH_KEY, max); + } + String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass()); + property.putOpt(TYPE_KEY,jsonType ); + } + + } + + /* + * + */ + private void processBinaryType(final BinaryTypeDefinition binaryType, final JSONObject property) throws JSONException { + property.put(TYPE_KEY, STRING); + JSONObject media = new JSONObject(); + media.put(BINARY_ENCODING_KEY, BASE_64); + property.put(MEDIA_KEY, media); + } + + /** + * + * @param enumLeafType + * @param property + * @throws JSONException + */ + private void processEnumType(final EnumerationType enumLeafType, final JSONObject property) throws JSONException { + List enumPairs = enumLeafType.getValues(); + List enumNames = new ArrayList(); + for(EnumPair enumPair: enumPairs) { + enumNames.add(enumPair.getName()); + } + property.putOpt(ENUM, new JSONArray(enumNames)); + } + + /** + * + * @param bitsType + * @param property + * @throws JSONException + */ + private void processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException{ + property.put(TYPE_KEY, ARRAY_TYPE); + property.put(MIN_ITEMS, 0); + property.put(UNIQUE_ITEMS_KEY, true); + JSONArray enumValues = new JSONArray(); + + List bits = bitsType.getBits(); + for(Bit bit: bits) { + enumValues.put(bit.getName()); + } + JSONObject itemsValue = new JSONObject(); + itemsValue.put(ENUM, enumValues); + property.put(ITEMS_KEY, itemsValue); + } + + + /** + * + * @param unionType + * @param property + * @throws JSONException + */ + private void processUnionType(final UnionTypeDefinition unionType, final JSONObject property) throws JSONException{ + + List> unionTypes = unionType.getTypes(); + JSONArray unionArray = new JSONArray(); + for(TypeDefinition typeDef: unionTypes) { + unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass())); + } + property.put(TYPE_KEY, unionArray); + } + + + /** + * Helper method to generate a pre-filled + * JSON schema object. + * @return + * @throws JSONException + */ + private JSONObject getSchemaTemplate() throws JSONException { + JSONObject schemaJSON = new JSONObject(); + schemaJSON.put(SCHEMA_KEY, SCHEMA_URL); + + return schemaJSON; } - property.put(TYPE_KEY, unionArray); - } - - - /** - * Helper method to generate a pre-filled - * JSON schema object. - * @return - * @throws JSONException - */ - private JSONObject getSchemaTemplate() throws JSONException { - JSONObject schemaJSON = new JSONObject(); - schemaJSON.put(SCHEMA_KEY, SCHEMA_URL); - - return schemaJSON; - } }