From 3b3bfd2cb38628532970c56b52b08d31bec35a18 Mon Sep 17 00:00:00 2001 From: "Kajur, Harish (vk250x)" Date: Wed, 10 Apr 2019 15:24:11 -0400 Subject: Remove the generation code for swagger and xsd The following code has been moved to schema service Issue-ID: AAI-2313 Change-Id: I58911dffef70ab2c32a73de79ac971c3650106e6 Signed-off-by: Kajur, Harish (vk250x) --- .../aai/config/SwaggerGenerationConfiguration.java | 64 -- .../java/org/onap/aai/util/AutoGenerateHtml.java | 80 -- .../main/java/org/onap/aai/util/GenerateXsd.java | 320 ------- .../aai/util/genxsd/ConfigTranslatorForDocs.java | 84 -- .../onap/aai/util/genxsd/DeleteFootnoteSet.java | 57 -- .../org/onap/aai/util/genxsd/DeleteOperation.java | 106 --- .../org/onap/aai/util/genxsd/EdgeDescription.java | 198 ----- .../org/onap/aai/util/genxsd/GetOperation.java | 121 --- .../java/org/onap/aai/util/genxsd/HTMLfromOXM.java | 288 ------- .../org/onap/aai/util/genxsd/NodeGetOperation.java | 168 ---- .../org/onap/aai/util/genxsd/NodesYAMLfromOXM.java | 542 ------------ .../org/onap/aai/util/genxsd/OxmFileProcessor.java | 525 ------------ .../org/onap/aai/util/genxsd/PatchOperation.java | 114 --- .../org/onap/aai/util/genxsd/PutOperation.java | 118 --- .../onap/aai/util/genxsd/PutRelationPathSet.java | 224 ----- .../java/org/onap/aai/util/genxsd/XSDElement.java | 756 ----------------- .../java/org/onap/aai/util/genxsd/XSDJavaType.java | 64 -- .../java/org/onap/aai/util/genxsd/YAMLfromOXM.java | 598 ------------- .../main/java/org/onap/aai/util/swagger/Api.java | 318 ------- .../java/org/onap/aai/util/swagger/Definition.java | 198 ----- .../org/onap/aai/util/swagger/GenerateSwagger.java | 488 ----------- aai-core/src/main/resources/swagger.html.ftl | 241 ------ .../java/org/onap/aai/util/GenerateXsdTest.java | 153 ---- .../aai/util/genxsd/DeleteFootnoteSetTest.java | 90 -- .../onap/aai/util/genxsd/DeleteOperationTest.java | 82 -- .../onap/aai/util/genxsd/EdgeDescriptionTest.java | 353 -------- .../org/onap/aai/util/genxsd/GetOperationTest.java | 107 --- .../org/onap/aai/util/genxsd/HTMLfromOXMTest.java | 384 --------- .../onap/aai/util/genxsd/NodeGetOperationTest.java | 109 --- .../onap/aai/util/genxsd/NodesYAMLfromOXMTest.java | 636 -------------- .../onap/aai/util/genxsd/PatchOperationTest.java | 81 -- .../org/onap/aai/util/genxsd/PutOperationTest.java | 83 -- .../aai/util/genxsd/PutRelationPathSetTest.java | 259 ------ .../org/onap/aai/util/genxsd/XSDElementTest.java | 631 -------------- .../org/onap/aai/util/genxsd/XSDJavaTypeTest.java | 101 --- .../org/onap/aai/util/genxsd/YAMLfromOXMTest.java | 942 --------------------- 36 files changed, 9683 deletions(-) delete mode 100644 aai-core/src/main/java/org/onap/aai/config/SwaggerGenerationConfiguration.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/AutoGenerateHtml.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/ConfigTranslatorForDocs.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/NodeGetOperation.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/NodesYAMLfromOXM.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/Api.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java delete mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java delete mode 100644 aai-core/src/main/resources/swagger.html.ftl delete mode 100644 aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/NodeGetOperationTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/NodesYAMLfromOXMTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java delete mode 100644 aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java (limited to 'aai-core/src') diff --git a/aai-core/src/main/java/org/onap/aai/config/SwaggerGenerationConfiguration.java b/aai-core/src/main/java/org/onap/aai/config/SwaggerGenerationConfiguration.java deleted file mode 100644 index dea284c8..00000000 --- a/aai-core/src/main/java/org/onap/aai/config/SwaggerGenerationConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.config; - - -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.util.genxsd.HTMLfromOXM; -import org.onap.aai.util.genxsd.NodesYAMLfromOXM; -import org.onap.aai.util.genxsd.YAMLfromOXM; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Scope; - -@Configuration -public class SwaggerGenerationConfiguration { - - @Value("${schema.uri.base.path}") - private String basePath; - - @Value("${schema.xsd.maxoccurs:5000}") - private String maxOccurs; - - @Bean - @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public NodesYAMLfromOXM nodesYamlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { - return new NodesYAMLfromOXM(basePath, schemaVersions, nodeIngestor, edgeIngestor); - } - - @Bean - @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public HTMLfromOXM htmlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { - return new HTMLfromOXM(maxOccurs, schemaVersions, nodeIngestor, edgeIngestor); - } - - @Bean - @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public YAMLfromOXM yamlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { - return new YAMLfromOXM(basePath, schemaVersions, nodeIngestor, edgeIngestor); - } - -} diff --git a/aai-core/src/main/java/org/onap/aai/util/AutoGenerateHtml.java b/aai-core/src/main/java/org/onap/aai/util/AutoGenerateHtml.java deleted file mode 100644 index 1745bb04..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/AutoGenerateHtml.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util; - -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; - -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.util.swagger.GenerateSwagger; - -import freemarker.template.TemplateException; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class AutoGenerateHtml { - - private static final String AAI_GENERATE_VERSION = "aai.generate.version"; - public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - //if the program is run from aai-common, use this directory as default" - public static final String ALT_SCHEMA_DIR = "aai-schema"; - //used to check to see if program is run from aai-core - public static final String DEFAULT_RUN_DIR = "aai-core"; - - public static void main(String[] args) throws IOException, TemplateException { - String savedProperty = System.getProperty(AAI_GENERATE_VERSION); - - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( - "org.onap.aai.config", - "org.onap.aai.setup" - ); - - - SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class); - - List versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - ListIterator versionIterator = versionsToGen.listIterator(); - String schemaDir; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { - schemaDir = ALT_SCHEMA_DIR; - } - else { - schemaDir = DEFAULT_SCHEMA_DIR; - } - String release = System.getProperty("aai.release", "onap"); - while (versionIterator.hasNext()) { - System.setProperty(AAI_GENERATE_VERSION, versionIterator.next().toString()); - String yamlFile = schemaDir + "/src/main/resources/" + release + "/aai_swagger_yaml/aai_swagger_" + System.getProperty(AAI_GENERATE_VERSION)+ ".yaml"; - File swaggerYamlFile = new File(yamlFile); - if(swaggerYamlFile.exists()) { - GenerateSwagger.schemaVersions = schemaVersions; - GenerateSwagger.main(args); - } - } - System.setProperty(AAI_GENERATE_VERSION, savedProperty); - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java b/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java deleted file mode 100644 index f44663e0..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java +++ /dev/null @@ -1,320 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util; - - -import org.onap.aai.config.SpringContextAware; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.util.genxsd.HTMLfromOXM; -import org.onap.aai.util.genxsd.NodesYAMLfromOXM; - -import org.onap.aai.util.genxsd.YAMLfromOXM; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.w3c.dom.*; - - -import java.io.*; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class GenerateXsd { - - private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); - protected static String apiVersion = null; - public static AnnotationConfigApplicationContext ctx = null; - static String apiVersionFmt = null; - static boolean useAnnotationsInXsd = false; - static String responsesUrl = null; - static String responsesLabel = null; - static String jsonEdges = null; - static Map generatedJavaType; - static Map appliedPaths; - static String RELEASE = System.getProperty("aai.release", "onap"); - - - static NodeList javaTypeNodes; - static Map javaTypeDefinitions = createJavaTypeDefinitions(); - private static Map createJavaTypeDefinitions() - { - StringBuffer aaiInternal = new StringBuffer(); - Map javaTypeDefinitions = new HashMap(); - aaiInternal.append(" aai-internal:\n"); - aaiInternal.append(" properties:\n"); - aaiInternal.append(" property-name:\n"); - aaiInternal.append(" type: string\n"); - aaiInternal.append(" property-value:\n"); - aaiInternal.append(" type: string\n"); -// javaTypeDefinitions.put("aai-internal", aaiInternal.toString()); - return javaTypeDefinitions; - } - - public static final int VALUE_NONE = 0; - public static final int VALUE_DESCRIPTION = 1; - public static final int VALUE_INDEXED_PROPS = 2; - public static final int VALUE_CONTAINER = 3; - - private static final String generateTypeXSD = "xsd"; - private static final String generateTypeYAML = "yaml"; - - private final static String nodeDir = System.getProperty("nodes.configuration.location"); - private final static String edgeDir = System.getProperty("edges.configuration.location"); - private static final String baseRoot = "aai-schema/"; - private static final String baseAutoGenRoot = "aai-schema/"; - - private static final String root = baseRoot + "src/main/resources"; - private static final String autoGenRoot = baseAutoGenRoot + "src/main/resources"; - - private static final String normalStartDir = "aai-core"; - private static final String xsd_dir = root + "/" + RELEASE +"/aai_schema"; - - private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/" + RELEASE + "/aai_swagger_yaml"; - - /* These three strings are for yaml auto-generation from aai-common class*/ - - private static int swaggerSupportStartsVersion = 1; // minimum version to support swagger documentation - - - private static boolean validVersion(String versionToGen) { - - if ("ALL".equalsIgnoreCase(versionToGen)) { - return true; - } - - SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); - for (SchemaVersion v : schemaVersions.getVersions()) { - if (v.equals(versionToGen)) { - return true; - } - } - - return false; - } - - private static boolean versionSupportsSwagger( String version) { - if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) { - return true; - } - return false; - } - - public static String getAPIVersion() { - return apiVersion; - } - - public static String getYamlDir() { - return yaml_dir; - } - - public static String getResponsesUrl() { - return responsesUrl; - } - public static void main(String[] args) throws IOException { - String versionToGen = System.getProperty("gen_version").toLowerCase(); - String fileTypeToGen = System.getProperty("gen_type").toLowerCase(); - - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( - "org.onap.aai.config", - "org.onap.aai.setup" - ); - - SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class); - - if ( fileTypeToGen == null ) { - fileTypeToGen = generateTypeXSD; - } - - if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) { - System.err.println("Invalid gen_type passed. " + fileTypeToGen); - System.exit(1); - } - - String responsesLabel = System.getProperty("yamlresponses_url"); - responsesUrl = responsesLabel; - - List versionsToGen = new ArrayList<>(); - if ( versionToGen == null ) { - System.err.println("Version is required, ie v or ALL."); - System.exit(1); - } - else if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) { - System.err.println("Invalid version passed. " + versionToGen); - System.exit(1); - } - else if ("ALL".equalsIgnoreCase(versionToGen)) { - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - } else { - versionsToGen.add(new SchemaVersion(versionToGen)); - } - - //process file type System property - fileTypeToGen = (fileTypeToGen == null ? generateTypeXSD : fileTypeToGen.toLowerCase()); - if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) { - System.err.println("Invalid gen_type passed. " + fileTypeToGen); - System.exit(1); - } else if ( fileTypeToGen.equals(generateTypeYAML) ) { - if ( responsesUrl == null || responsesUrl.length() < 1 - || responsesLabel == null || responsesLabel.length() < 1 ) { - System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" ); - System.exit(1); - } else { - responsesUrl = "description: "+ "Response codes found in [response codes]("+responsesLabel+ ").\n"; - } - } - /* - * TODO: Oxm Path is config driveb - */ - String oxmPath; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) { - oxmPath = baseAutoGenRoot + nodeDir; - } - else { - oxmPath = baseRoot + nodeDir; - } - - String outfileName = null; - File outfile; - String nodesfileName = null; - File nodesfile; - String fileContent = null; - String nodesContent = null; - - - for (SchemaVersion v : versionsToGen) { - apiVersion = v.toString(); - logger.debug("YAMLdir = "+yaml_dir); - logger.debug("Generating " + apiVersion + " " + fileTypeToGen); - apiVersionFmt = "." + apiVersion + "."; - generatedJavaType = new HashMap(); - appliedPaths = new HashMap(); - File edgeRuleFile = null; - String fileName = edgeDir + "DbEdgeRules_" + apiVersion + ".json"; - logger.debug("user.dir = "+System.getProperty("user.dir")); - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) { - fileName = baseAutoGenRoot + fileName; - - } - else { - fileName = baseRoot + fileName; - - } - edgeRuleFile = new File( fileName); -// Document doc = ni.getSchema(translateVersion(v)); - - if ( fileTypeToGen.equals(generateTypeXSD) ) { - outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD; - try { - HTMLfromOXM swagger = ctx.getBean(HTMLfromOXM.class); - swagger.setVersion(v); - fileContent = swagger.process(); - if ( fileContent.startsWith("Schema format issue")) { - throw new Exception(fileContent); - } - } catch(Exception e) { - logger.error( "Exception creating output file " + outfileName); - logger.error( e.getMessage()); - e.printStackTrace(); - System.exit(-1); - } - } else if ( versionSupportsSwagger(apiVersion )) { - outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML; - nodesfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + "nodes"+"."+generateTypeYAML; - try { - YAMLfromOXM swagger = (YAMLfromOXM) ctx.getBean(YAMLfromOXM.class); - swagger.setVersion(v); - fileContent = swagger.process(); - Map combinedJavaTypes = swagger.getCombinedJavaTypes(); - NodesYAMLfromOXM nodesSwagger = ctx.getBean(NodesYAMLfromOXM.class); - nodesSwagger.setVersion(v); - nodesSwagger.setCombinedJavaTypes(combinedJavaTypes); - nodesContent = nodesSwagger.process(); - } catch(Exception e) { - logger.error( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - } else { - continue; - } - outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(! parentDir.exists()) - parentDir.mkdirs(); - if(nodesfileName != null) { - BufferedWriter nodesBW = null; - nodesfile = new File(nodesfileName); - parentDir = nodesfile.getParentFile(); - if(! parentDir.exists()) - parentDir.mkdirs(); - try { - nodesfile.createNewFile(); - } catch (IOException e) { - logger.error( "Exception creating output file " + nodesfileName); - e.printStackTrace(); - } - try { - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(nodesfileName); - nodesBW = Files.newBufferedWriter(path, charset); - nodesBW.write(nodesContent); - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName); - e.printStackTrace(); - } finally { - if ( nodesBW != null ) { - nodesBW.close(); - } - } - } - - try { - outfile.createNewFile(); - } catch (IOException e) { - logger.error( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - BufferedWriter bw = null; - try { - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(fileContent); - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName); - e.printStackTrace(); - } finally { - if ( bw != null ) { - bw.close(); - } - } - logger.debug( "GeneratedXSD successful, saved in " + outfileName); - } - - } - -} - diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/ConfigTranslatorForDocs.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/ConfigTranslatorForDocs.java deleted file mode 100644 index 3a42e437..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/ConfigTranslatorForDocs.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.util.genxsd; - -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import org.onap.aai.setup.ConfigTranslator; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaConfigVersions; - -public class ConfigTranslatorForDocs extends ConfigTranslator { - - public ConfigTranslatorForDocs(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) { - super(bean, schemaVersions); - } - - @Override - public Map> getNodeFiles() { - List versionsToGen = new ArrayList<>(); - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - Map> mp = new TreeMap<>(); - for (SchemaVersion v : versionsToGen) { - File dir = new File(bean.getNodeDirectory() + File.separator + v.toString().toLowerCase()); - File [] fileSet = dir.listFiles(); - List files = new ArrayList<>(); - for(File f: fileSet ) { - files.add(f.getAbsolutePath()); - } - - mp.put(v, files); - } - return mp; - } - - @Override - public Map> getEdgeFiles() { - List versionsToGen = new ArrayList<>(); - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - Map> mp = new TreeMap<>(); - for (SchemaVersion v : versionsToGen) { - File dir = new File(bean.getEdgeDirectory()); - File [] fileSet = dir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.contains("_"+v.toString().toLowerCase()); - } - }); - List files = new ArrayList<>(); - for(File f: fileSet ) { - files.add(f.getAbsolutePath()); - } - mp.put(v, files); - } - return mp; - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java deleted file mode 100644 index dca5b7ce..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.Set; -import java.util.TreeSet; - -public class DeleteFootnoteSet { - protected Set footnotes = new TreeSet<>(); - protected String targetNode = ""; - public DeleteFootnoteSet(String targetNode) { - super(); - this.targetNode = targetNode == null ? "" : targetNode; - } - - public void add(String s ) { - String fullnote=null; - if("(1)".equals(s)) { - fullnote = s+" IF this "+targetNode.toUpperCase()+" node is deleted, this FROM node is DELETED also"; - } else if("(2)".equals(s)) { - fullnote = s+" IF this "+targetNode.toUpperCase()+" node is deleted, this TO node is DELETED also"; - } else if("(3)".equals(s)) { - fullnote = s+" IF this FROM node is deleted, this "+targetNode.toUpperCase()+" is DELETED also"; - } else if("(4)".equals(s)) { - fullnote = s+" IF this TO node is deleted, this "+targetNode.toUpperCase()+" is DELETED also"; - } else if(s.contains(targetNode.toUpperCase())) { - fullnote = s; - } else { - return; - } - footnotes.add(fullnote); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - if(footnotes.size() > 0) sb.append("\n -"); - sb.append(String.join("\n -", footnotes)+"\n"); - return sb.toString(); - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java deleted file mode 100644 index 6ee4194d..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.HashMap; -import java.util.StringTokenizer; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.util.GenerateXsd; - -public class DeleteOperation { - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - - public static HashMap deletePaths = new HashMap(); - public DeleteOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams = pathParams; - } - @Override - public String toString() { - StringTokenizer st; - st = new StringTokenizer(path, "/"); - //a valid tag is necessary - if ( StringUtils.isEmpty(tag) ) { - return ""; - } - if ( path.contains("/relationship/") ) { // filter paths with relationship-list - return ""; - } - if ( path.endsWith("/relationship-list")) { - return ""; - } - if ( path.startsWith("/search")) { - return ""; - } - //All Delete operation paths end with "relationship" - //or there is a parameter at the end of the path - //and there is a parameter in the path - - if ( !path.endsWith("/relationship") && !path.endsWith("}") ) { - return ""; - } - StringBuffer pathSb = new StringBuffer(); - pathSb.append(" delete:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" description: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" operationId: delete" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + GenerateXsd.getResponsesUrl()); - pathSb.append(" parameters:\n"); - - pathSb.append(pathParams); // for nesting - if ( !path.endsWith("/relationship") ) { - pathSb.append(" - name: resource-version\n"); - - pathSb.append(" in: query\n"); - pathSb.append(" description: resource-version for concurrency\n"); - pathSb.append(" required: true\n"); - pathSb.append(" type: string\n"); - } - this.objectPathMapEntry(); - return pathSb.toString(); - } - public String objectPathMapEntry() { - if (! path.endsWith("/relationship") ) { - deletePaths.put(path, xmlRootElementName); - } - return (xmlRootElementName+":"+path); - } - } \ No newline at end of file diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java deleted file mode 100644 index ae6b8803..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java +++ /dev/null @@ -1,198 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.enums.AAIDirection; -import org.onap.aai.edges.enums.DirectionNotation; -import org.onap.aai.edges.enums.EdgeField; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class EdgeDescription { - - private static final Logger logger = LoggerFactory.getLogger("EdgeDescription.class"); - EdgeRule ed; - public static enum LineageType { - PARENT, CHILD, UNRELATED; - } - private String ruleKey; -// private String to; -// private String from; - private LineageType lineageType = LineageType.UNRELATED; -// private String direction; -// private String multiplicity; -// private String preventDelete; -// private String deleteOtherV; -// private String label; -// private String description; - - public EdgeDescription(EdgeRule ed) { - super(); - if ( ed.getDirection().toString().equals(ed.getContains()) && - AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { - this.lineageType=LineageType.PARENT; - } else if ( AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) && - ed.getDirection().toString().equals(ed.getContains())) { - this.lineageType=LineageType.CHILD; - } else if ( AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getContains())) && - AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getDirection()))) { - this.lineageType=LineageType.PARENT; - } else if ( AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) && - AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { - this.lineageType=LineageType.PARENT; - } else { - this.lineageType=LineageType.UNRELATED; - } - this.ruleKey = ed.getFrom()+"|"+ed.getTo(); - this.ed=ed; - } - /** - * @return the deleteOtherV - */ - public String getDeleteOtherV() { - return ed.getDeleteOtherV(); - } - /** - * @return the preventDelete - */ - public String getPreventDelete() { - return ed.getPreventDelete(); - } - public String getAlsoDeleteFootnote(String targetNode) { - String returnVal = ""; - if(ed.getDeleteOtherV().equals("IN") && ed.getTo().equals(targetNode) ) { - logger.debug("Edge: "+this.ruleKey); - logger.debug("IF this "+targetNode+" node is deleted, this FROM node is DELETED also"); - returnVal = "(1)"; - } - if(ed.getDeleteOtherV().equals("OUT") && ed.getFrom().equals(targetNode) ) { - logger.debug("Edge: "+this.ruleKey); - logger.debug("IF this "+targetNode+" is deleted, this TO node is DELETED also"); - returnVal = "(2)"; - } - if(ed.getDeleteOtherV().equals("OUT") && ed.getTo().equals(targetNode) ) { - logger.debug("Edge: "+this.ruleKey); - logger.debug("IF this FROM node is deleted, this "+targetNode+" is DELETED also"); - returnVal = "(3)"; - } - if(ed.getDeleteOtherV().equals("IN") && ed.getFrom().equals(targetNode) ) { - logger.debug("Edge: "+this.ruleKey); - logger.debug("IF this TO node is deleted, this "+targetNode+" node is DELETED also"); - returnVal = "(4)"; - } - return returnVal; - } - /** - * @return the to - */ - public String getTo() { - return ed.getTo(); - } - /** - * @return the from - */ - public String getFrom() { - return ed.getFrom(); - } - public String getRuleKey() { - return ruleKey; - } - public String getMultiplicity() { - return ed.getMultiplicityRule().toString(); - } - public AAIDirection getDirection() { - return AAIDirection.getValue(ed.getDirection()); - } - public String getDescription() { - return ed.getDescription(); - } - public String getRelationshipDescription(String fromTo, String otherNodeName) { - - String result = ""; - - if ("FROM".equals(fromTo)) { - if (AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { - if (LineageType.PARENT == lineageType) { - result = " (PARENT of "+otherNodeName; - result = String.join(" ", result+",", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - } - else { - if (LineageType.CHILD == lineageType) { - result = " (CHILD of "+otherNodeName; - result = String.join(" ", result+",", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - else if (LineageType.PARENT == lineageType) { - result = " (PARENT of "+otherNodeName; - result = String.join(" ", result+",", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - } - if (result.length() == 0) result = String.join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } else { - //if ("TO".equals(fromTo) - if (AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { - if (LineageType.PARENT == lineageType) { - result = " (PARENT of "+otherNodeName; - result = String.join(" ", result+",", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - } else { - if (LineageType.PARENT == lineageType) { - result = " (PARENT of "+otherNodeName; - result = String.join(" ", result+",", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - } - if (result.length() == 0) result = String.join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo()+",", this.getMultiplicity()); - } - - if (result.length() > 0) result = result + ")"; - - if (ed.getDescription() != null && ed.getDescription().length() > 0) result = result + "\n "+ ed.getDescription(); // 6 spaces is important for yaml - - return result; - } - - /** - * @return the hasDelTarget - */ - - public boolean hasDelTarget() { - return StringUtils.isNotEmpty(ed.getDeleteOtherV()) && (! "NONE".equalsIgnoreCase(ed.getDeleteOtherV())); - } - - /** - * @return the type - */ - public LineageType getType() { - - return lineageType; - } - /** - * @return the label - */ - public String getLabel() { - return ed.getLabel(); - } - public String getShortLabel() { - String[] pieces = this.getLabel().split("[.]"); - return pieces[pieces.length-1]; - } -} \ No newline at end of file diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java deleted file mode 100644 index ad1e2dc7..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.Vector; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.util.GenerateXsd; - -public class GetOperation { - static Map> containers = new HashMap>(); - public static void addContainerProps(String container, Vector containerProps) { - containers.put(container, containerProps);; - } - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String queryParams; - - public GetOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams = pathParams; -// StringBuilder p = new StringBuilder(); - - if(containers.get(xmlRootElementName) == null) { - this.queryParams = ""; - } else { - this.queryParams= String.join("", containers.get(xmlRootElementName)); -// for(String param : containers.get(xmlRootElementName)) { -// p.append(param); -// } -// this.queryParams = p.toString(); - } - } - @Override - public String toString() { - StringTokenizer st; - st = new StringTokenizer(path, "/"); - //Path has to be longer than one element - /* - if ( st.countTokens() <= 1) { - return ""; - } - */ - //a valid tag is necessary - if ( StringUtils.isEmpty(tag) ) { - return ""; - } - if ( path.endsWith("/relationship") ) { - return ""; - } - if ( path.contains("/relationship/") ) { // filter paths with relationship-list - return ""; - } - if ( path.endsWith("/relationship-list")) { - return ""; - } - if ( path.startsWith("/search")) { - return ""; - } - StringBuffer pathSb = new StringBuffer(); - pathSb.append(" " + path + ":\n" ); - pathSb.append(" get:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: returns " + xmlRootElementName + "\n"); - - pathSb.append(" description: returns " + xmlRootElementName + "\n"); - pathSb.append(" operationId: get" + useOpId + "\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/getDefinitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + GenerateXsd.getResponsesUrl()); - if ( StringUtils.isNotEmpty(pathParams) || StringUtils.isNotEmpty(queryParams)) { - pathSb.append(" parameters:\n"); - } - if ( StringUtils.isNotEmpty(pathParams)) { - pathSb.append(pathParams); - } -// if ( StringUtils.isNotEmpty(pathParams) && StringUtils.isNotEmpty(queryParams)) { -// pathSb.append("\n"); -// } - if ( StringUtils.isNotEmpty(queryParams)) { - pathSb.append(queryParams); - } - return pathSb.toString(); - } - } diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java deleted file mode 100644 index 7d3b37d1..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java +++ /dev/null @@ -1,288 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.xml.parsers.ParserConfigurationException; - - -import org.onap.aai.config.SpringContextAware; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -public class HTMLfromOXM extends OxmFileProcessor { - - private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXM.class"); - - private String maxOccurs; - - public HTMLfromOXM(String maxOccurs, SchemaVersions schemaVersions, NodeIngestor ni, EdgeIngestor ei ){ - super(schemaVersions, ni,ei); - this.maxOccurs = maxOccurs; - } - public void setOxmVersion(File oxmFile, SchemaVersion v) { - super.setOxmVersion(oxmFile, v); - this.v = v; - } - public void setXmlVersion(String xml, SchemaVersion v) { - super.setXmlVersion(xml, v); - this.v = v; - } - public void setVersion(SchemaVersion v) { - super.setVersion(v); - this.v = v; - } - - - @Override - public String getDocumentHeader() { - StringBuffer sb = new StringBuffer(); - logger.trace("processing starts"); - sb.append("" + LINE_SEPARATOR); - String namespace = "org.onap"; - if (v.compareTo(getSchemaVersions().getNamespaceChangeVersion()) < 0 ) { - namespace = "org.openecomp"; - } - if ( versionUsesAnnotations(v.toString()) ) { - sb.append("" + DOUBLE_LINE_SEPARATOR); - } else { - sb.append("" + DOUBLE_LINE_SEPARATOR); - } - return sb.toString(); - } - - @Override - public String process() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException { - StringBuilder sb = new StringBuilder(); - - try { - init(); - } catch(Exception e) { - logger.error( "Error initializing " + this.getClass()); - throw e; - } - sb.append(getDocumentHeader()); - StringBuilder sbInventory = new StringBuilder(); - Element elem; - String javaTypeName; - combinedJavaTypes = new HashMap(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - elem = (Element)javaTypeNodes.item(i); - javaTypeName = elem.getAttribute("name"); - if ( !"Inventory".equals(javaTypeName ) ) { - if ( generatedJavaType.containsKey(javaTypeName) ) { - continue; - } - // will combine all matching java-types - elem = getJavaTypeElement(javaTypeName,false ); - } - XSDElement javaTypeElement = new XSDElement(elem, maxOccurs); - //javaTypeName = javaTypeElement.name(); - if ( javaTypeName == null ) { - String msg = "Invalid OXM file: has no name attribute in " + oxmFile; - logger.error(msg); - throw new AAIException(msg); - } - if ("Nodes".equals(javaTypeName)) { - logger.debug("skipping Nodes entry (temporary feature)"); - continue; - } - logger.debug(getXmlRootElementName(javaTypeName)+" vs "+ javaTypeName+":"+generatedJavaType.containsKey(getXmlRootElementName(javaTypeName))); - - if ( !"Inventory".equals(javaTypeName)) { - generatedJavaType.put(javaTypeName, null); - } - sb.append(processJavaTypeElement( javaTypeName, javaTypeElement, sbInventory )); - } - sb.append(sbInventory); - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - sb.append("" + LINE_SEPARATOR); - return sb.toString(); - } - - protected boolean isValidName( String name ) { - if ( name == null || name.length() == 0 ) { - return false; - } - String pattern = "^[a-z0-9-]*$"; - return name.matches(pattern); - } - - protected boolean skipCheck( String javaAttribute ) { - if ( javaAttribute.equals("model") - || javaAttribute.equals("eventHeader") ) { - return true; - } - return false; - } - - public String processJavaTypeElement( String javaTypeName, Element javaType_Element, StringBuilder sbInventory) { - String xmlRootElementName = getXMLRootElementName(javaType_Element); - - NodeList parentNodes = javaType_Element.getElementsByTagName("java-attributes"); - StringBuffer sb = new StringBuffer(); - if ( parentNodes.getLength() == 0 ) { - logger.trace( "no java-attributes for java-type " + javaTypeName); - return ""; - } - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - // support for multiple inventory elements across oxm files - boolean processingInventory = false; - boolean hasPreviousInventory = false; - if ( "inventory".equals(xmlRootElementName) && sbInventory != null ) { - processingInventory = true; - if ( sbInventory.toString().contains("xs:complexType") ) { - hasPreviousInventory = true; - } - } - - StringBuffer sb1 = new StringBuffer(); - if ( xmlElementNodes.getLength() > 0 ) { - - if ( !processingInventory || !hasPreviousInventory ) { - sb1.append(" " + LINE_SEPARATOR); - sb1.append(" " + LINE_SEPARATOR); - - XSDElement javaTypeElement = new XSDElement(javaType_Element, maxOccurs); - logger.debug("XSDElement name: "+javaTypeElement.name()); - if(versionUsesAnnotations(v.toString())) { - sb1.append(javaTypeElement.getHTMLAnnotation("class", " ")); - } - sb1.append(" " + LINE_SEPARATOR); - } - Element javatypeElement; - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - - XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(i), maxOccurs); - -// String elementName = xmlElementElement.getAttribute("name"); - String elementType = xmlElementElement.getAttribute("type"); - //No simple types; only AAI custom types - String addType = elementType.contains("." + v.toString() + ".") ? elementType.substring(elementType.lastIndexOf('.')+1) : null; - if ( elementType.contains("." + v.toString() + ".") && !generatedJavaType.containsKey(addType) ) { - generatedJavaType.put(addType, elementType); - javatypeElement = getJavaTypeElement(addType, processingInventory); - sb.append(processJavaTypeElement( addType, javatypeElement, null )); - } - if ("Nodes".equals(addType)) { - logger.trace("Skipping nodes, temporary testing"); - continue; - } - //assembles the basic - sb1.append(xmlElementElement.getHTMLElement(v, versionUsesAnnotations(v.toString()), this)); - } - if ( !processingInventory ) { - sb1.append(" " + LINE_SEPARATOR); - sb1.append(" " + LINE_SEPARATOR); - sb1.append(" " + LINE_SEPARATOR); - } - } - - if ( xmlElementNodes.getLength() < 1 ) { - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - sb.append(" " + LINE_SEPARATOR); - generatedJavaType.put(javaTypeName, null); - return sb.toString(); - } - if ( processingInventory && sbInventory != null ) { - sbInventory.append(sb1); - } else { - sb.append( sb1 ); - } - return sb.toString(); - } - - private Element getJavaTypeElement( String javaTypeName, boolean processingInventory ) - { - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - - List combineElementList = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { - if ( processingInventory ) { - return javaTypeElement; - } else { - combineElementList.add(javaTypeElement); - } - } - } - } - if ( combineElementList.size() == 0 ) { - logger.error( "oxm file format error, missing java-type " + javaTypeName); - return (Element) null; - } else if ( combineElementList.size() > 1 ) { - // need to combine java-attributes - return combineElements( javaTypeName, combineElementList); - } - return combineElementList.get(0); - - } - - private boolean versionUsesAnnotations( String version) { - int ver = new Integer(version.substring(1)).intValue(); - if ( ver >= HTMLfromOXM.annotationsStartVersion ) { - return true; - } - if ( ver <= HTMLfromOXM.annotationsMinVersion ) { - return true; - } - return false; - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/NodeGetOperation.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/NodeGetOperation.java deleted file mode 100644 index 7ffdf407..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/NodeGetOperation.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.Vector; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.util.GenerateXsd; - -public class NodeGetOperation { - static Map> containers = new HashMap>(); - static ArrayList checklist = createChecklist(); - private static ArrayList createChecklist() - { - ArrayList list = new ArrayList(); - return list; - } - public static void addContainerProps(String container, Vector containerProps) { - containers.put(container, containerProps); - } - public static void resetContainers() { - containers = new HashMap>(); - checklist = createChecklist(); - } - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String CRUDpath; - private String pathParams; - private String queryParams; - - public NodeGetOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.CRUDpath = path; - this.path = nodePath(); - this.pathParams = pathParams; - StringBuilder p = new StringBuilder(); - - if(containers.get(xmlRootElementName) == null) { - this.queryParams = ""; - } else { - this.queryParams= String.join("", containers.get(xmlRootElementName)); - for(String param : containers.get(xmlRootElementName)) { - p.append(param); - } - this.queryParams = p.toString(); - } - } - String nodePath() { - String path = null; - int loc = CRUDpath.indexOf(xmlRootElementName); - if(loc > 0) { - path = "/nodes/"+CRUDpath.substring(loc); - } - return path; - } - @Override - public String toString() { - StringTokenizer st; - st = new StringTokenizer(CRUDpath, "/"); - //Path has to be longer than one element - /* - if ( st.countTokens() <= 1) { - return ""; - } - */ - //a valid tag is necessary - if ( StringUtils.isEmpty(tag) ) { - return ""; - } - if ( CRUDpath.endsWith("/relationship") ) { - return ""; - } - if ( CRUDpath.contains("/relationship/") ) { // filter paths with relationship-list - return ""; - } - if ( CRUDpath.endsWith("/relationship-list")) { - return ""; - } - if ( CRUDpath.startsWith("/search")) { - return ""; - } - if ( CRUDpath.startsWith("/actions")) { - return ""; - } - if ( CRUDpath.startsWith("/nodes")) { - return ""; - } - if (checklist.contains(xmlRootElementName)) { - return ""; - } - StringBuffer pathSb = new StringBuffer(); - //Drop out the operations with multiple path parameters - if(CRUDpath.lastIndexOf('{') > CRUDpath.indexOf('{') && StringUtils.isNotEmpty(pathParams)) { - return ""; - } - if(path.lastIndexOf('{') > path.indexOf('{') ) { - return ""; - } - //trim leading path elements before the current node type -// int loc = path.indexOf(xmlRootElementName); -// if(loc > 0) { -// path = "/nodes/"+path.substring(loc); -// } - //append generic parameter syntax to all plural queries - if(path.indexOf('{') == -1) { - path += "?parameter=value[¶meter2=value2]"; - } - pathSb.append(" " + path + ":\n" ); - pathSb.append(" get:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - Operations" + "\n"); - pathSb.append(" summary: returns " + xmlRootElementName + "\n"); - - pathSb.append(" description: returns " + xmlRootElementName + "\n"); - pathSb.append(" operationId: get" + useOpId + "\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + GenerateXsd.getResponsesUrl()); - if ( StringUtils.isNotEmpty(pathParams) || StringUtils.isNotEmpty(queryParams)) { - pathSb.append("\n parameters:\n"); - } - if ( StringUtils.isNotEmpty(pathParams)) { - pathSb.append(pathParams); - } - if ( StringUtils.isNotEmpty(pathParams) && StringUtils.isNotEmpty(queryParams)) { - pathSb.append("\n"); - } - if ( StringUtils.isNotEmpty(queryParams)) { - pathSb.append(queryParams); - } - checklist.add(xmlRootElementName); - return pathSb.toString(); - } - } diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/NodesYAMLfromOXM.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/NodesYAMLfromOXM.java deleted file mode 100644 index 5abd8f48..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/NodesYAMLfromOXM.java +++ /dev/null @@ -1,542 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.StringTokenizer; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.Vector; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.EdgeRuleQuery; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.nodes.NodeIngestor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import com.google.common.collect.Multimap; - -public class NodesYAMLfromOXM extends OxmFileProcessor { - private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); - private static final String root = "../aai-schema/src/main/resources"; - private static final String autoGenRoot = "aai-schema/src/main/resources"; - private static final String generateTypeYAML = "yaml"; - private static final String normalStartDir = "aai-core"; - private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/aai_swagger_yaml"; - private StringBuilder inventoryDefSb = null; - private Map operationDefinitions = new HashMap<>(); - - private String basePath; - - public NodesYAMLfromOXM(String basePath, SchemaVersions schemaVersions, NodeIngestor ni, EdgeIngestor ei){ - super(schemaVersions, ni,ei); - this.basePath = basePath; - } - public void setOxmVersion(File oxmFile, SchemaVersion v) { - super.setOxmVersion(oxmFile, v); - } - public void setXmlVersion(String xml, SchemaVersion v){ - super.setXmlVersion(xml, v); - } - - public void setVersion(SchemaVersion v) { - super.setVersion(v); - } - - @Override - public String getDocumentHeader() { - StringBuffer sb = new StringBuffer(); - sb.append("swagger: \"2.0\"\ninfo:\n "); - sb.append("description: |"); - if ( versionSupportsSwaggerDiff(v.toString())) { - sb.append("\n\n [Differences versus the previous schema version]("+"apidocs/aai_swagger_" + v.toString() + ".diff)"); - } - sb.append("\n\n Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n\n You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)\n\n Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n version: \"" + v.toString() +"\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n name: Apache 2.0\n url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n name:\n url:\n email:\n"); - sb.append("host:\nbasePath: " + basePath + "/" + v.toString() + "\n"); - sb.append("schemes:\n - https\npaths:\n"); - return sb.toString(); - } - - protected void init() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException { - super.init(); - } - - @Override - public String process() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException { - StringBuffer sb = new StringBuffer(); - StringBuffer pathSb = new StringBuffer(); - NodeGetOperation.resetContainers(); - try { - init(); - } catch(Exception e) { - logger.error( "Error initializing " + this.getClass()); - throw e; - } - pathSb.append(getDocumentHeader()); - StringBuffer definitionsSb = new StringBuffer(); - Element elem; - String javaTypeName; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - elem = (Element)javaTypeNodes.item(i); - javaTypeName = elem.getAttribute("name"); - if ( !"Inventory".equals(javaTypeName ) ) { - if ( generatedJavaType.containsKey(javaTypeName) ) { - continue; - } - // will combine all matching java-types - elem = getJavaTypeElementSwagger(javaTypeName ); - } - - XSDElement javaTypeElement = new XSDElement(elem); - - logger.debug("External: "+javaTypeElement.getAttribute("name")+"/"+getXmlRootElementName(javaTypeName)); - if ( javaTypeName == null ) { - String msg = "Invalid OXM file: has no name attribute in " + oxmFile; - logger.error(msg); - throw new AAIException(msg); - } - namespaceFilter.add(getXmlRootElementName(javaTypeName)); - processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb, - definitionsSb, null, null, null, null, null, null); - } - sb.append(pathSb); -// sb.append(getDocumentHeader()); -// sb.append(totalPathSbAccumulator); - sb.append(appendOperations()); - sb.append(appendDefinitions()); - PutRelationPathSet prp = new PutRelationPathSet(v); - prp.generateRelations(ei); - return sb.toString(); - } - - public String appendDefinitions() { - return appendDefinitions(null); - } - - public String appendDefinitions(Set namespaceFilter) { - if ( inventoryDefSb != null ) { - javaTypeDefinitions.put("inventory", inventoryDefSb.toString()); - } - StringBuffer sb = new StringBuffer("definitions:\n"); - Map sortedJavaTypeDefinitions = new TreeMap<>(javaTypeDefinitions); - - for (Map.Entry entry : sortedJavaTypeDefinitions.entrySet()) { - if(namespaceFilter != null && (! namespaceFilter.contains(entry.getKey()))) { - continue; - } - sb.append(entry.getValue()); - } - return sb.toString(); - } - - private String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement, - StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId, - String getItemName, StringBuffer pathParams, String validEdges) { - - String xmlRootElementName = getXMLRootElementName(javaTypeElement); - StringBuilder definitionsLocalSb = new StringBuilder(256); - - String useTag = null; - String useOpId = null; - logger.debug("tag="+tag); - - if(tag != null && (! validTag(tag))) { - logger.debug("tag="+tag+"; javaTypeName="+javaTypeName); - return null; - } - if ( !javaTypeName.equals("Inventory") ) { - if ( javaTypeName.equals("AaiInternal")) - return null; - if ( opId == null ) - useOpId = javaTypeName; - else - useOpId = opId + javaTypeName; - if ( tag == null ) - useTag = javaTypeName; - } - - path = xmlRootElementName.equals("inventory") ? "" : (path == null) ? "/" + xmlRootElementName : path + "/" + xmlRootElementName; - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - if ( getItemName != null) { - if ( getItemName.equals("array") ) - return javaType.getArrayType(); - else - return javaType.getItemName(); - } - - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - if ( parentNodes.getLength() == 0 ) { - logger.debug( "no java-attributes for java-type " + javaTypeName); - return ""; - } - - String pathDescriptionProperty = javaType.getPathDescriptionProperty(); - String container = javaType.getContainerProperty(); - Vector indexedProps = javaType.getIndexedProps(); - Vector containerProps = new Vector(); - if(container != null) { - logger.debug("javaTypeName " + javaTypeName + " container:" + container +" indexedProps:"+indexedProps); - } - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - - StringBuffer sbParameters = new StringBuffer(); - StringBuffer sbRequired = new StringBuffer(); - int requiredCnt = 0; - int propertyCnt = 0; - StringBuffer sbProperties = new StringBuffer(); - - if ( appliedPaths.containsKey(path)) - return null; - - StringTokenizer st = new StringTokenizer(path, "/"); - logger.debug("path: " + path + " st? " + st.toString()); - if ( st.countTokens() > 1 && getItemName == null ) { - logger.debug("appliedPaths: " + appliedPaths + " containsKey? " + appliedPaths.containsKey(path)); - appliedPaths.put(path, xmlRootElementName); - } - Vector addTypeV = null; - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(i)); - if ( !xmlElementElement.getParentNode().isSameNode(parentElement)) - continue; - String elementDescription=xmlElementElement.getPathDescriptionProperty(); - if(getItemName == null) { - addTypeV = xmlElementElement.getAddTypes(v.toString()); - } - if ( "true".equals(xmlElementElement.getAttribute("xml-key"))) { - path += "/{" + xmlElementElement.getAttribute("name") + "}"; - } - logger.debug("path: " + path); - logger.debug( "xmlElementElement.getAttribute(required):"+xmlElementElement.getAttribute("required") ); - - if ( ("true").equals(xmlElementElement.getAttribute("required"))) { - if ( requiredCnt == 0 ) - sbRequired.append(" required:\n"); - ++requiredCnt; - if ( addTypeV == null || addTypeV.isEmpty()) { - sbRequired.append(" - " + xmlElementElement.getAttribute("name") + "\n"); - } else { - for ( int k = 0; k < addTypeV.size(); ++k ) { - sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n"); - } - } - } - - if ( "true".equals(xmlElementElement.getAttribute("xml-key")) ) { - sbParameters.append(xmlElementElement.getPathParamYAML(elementDescription)); - } - if ( indexedProps != null - && indexedProps.contains(xmlElementElement.getAttribute("name") ) ) { - containerProps.add(xmlElementElement.getQueryParamYAML(elementDescription)); - NodeGetOperation.addContainerProps(container, containerProps); - } else if ( indexedProps == null || indexedProps.isEmpty() && "true".equals(xmlElementElement.getAttribute("required")) ){ - // no indexedProps and element is required, also considered using xml-key in this case - containerProps.add(xmlElementElement.getPathParamYAMLRqd(elementDescription, false)); - NodeGetOperation.addContainerProps(container, containerProps); - } - if ( xmlElementElement.isStandardType()) { - sbProperties.append(xmlElementElement.getTypePropertyYAML()); - ++propertyCnt; - } - -// StringBuffer newPathParams = new StringBuffer((pathParams == null ? "" : pathParams.toString())+sbParameters.toString()); //cp8128 don't append the pathParams to sbParameters so that child nodes don't contain the parameters from parent - StringBuffer newPathParams = new StringBuffer(sbParameters.toString()); - for ( int k = 0; addTypeV != null && k < addTypeV.size(); ++k ) { - String addType = addTypeV.elementAt(k); - namespaceFilter.add(getXmlRootElementName(addType)); - if ( opId == null || !opId.contains(addType)) { - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null, - newPathParams, validEdges); - } - // need item name of array - String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - "array", null, null); - - if ( itemName != null ) { - if ( addType.equals("AaiInternal") ) { - logger.debug( "addType AaiInternal, skip properties"); - - } else if ( getItemName == null) { - ++propertyCnt; - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items:\n"); - sbProperties.append(" $ref: \"#/definitions/" + (itemName == "" ? "aai-internal" : itemName) + "\"\n"); - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - } - } else { - if ( ("java.util.ArrayList").equals(xmlElementElement.getAttribute("container-type"))) { - // need properties for getXmlRootElementName(addType) - namespaceFilter.add(getXmlRootElementName(addType)); - if(getXmlRootElementName(addType).equals("service-capabilities")) - { - logger.info("arrays: "+ getXmlRootElementName(addType)); - } -// newPathParams = new StringBuffer((pathParams == null ? "" : pathParams.toString())+sbParameters.toString()); //cp8128 - change this to not append pathParameters. Just use sbParameters - newPathParams = new StringBuffer(sbParameters.toString()); - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - null, newPathParams, validEdges); - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items: \n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - - } else { - //Make sure certain types added to the filter don't appear - if (nodeFilter.contains(getXmlRootElementName(addType))) { - ; - } else { - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: object\n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } - } - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - ++propertyCnt; - } - } - } - - if ( sbParameters.toString().length() > 0 ) { - if ( pathParams == null ) - pathParams = new StringBuffer(); - pathParams.append(sbParameters); - } - if (indexedProps.isEmpty() && containerProps.isEmpty()){ - NodeGetOperation get = new NodeGetOperation(useOpId, xmlRootElementName, tag, path, null); - String operation = get.toString(); - if(StringUtils.isNotEmpty(operation)) { - operationDefinitions.put(xmlRootElementName, operation); - } - } else { - NodeGetOperation get = new NodeGetOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString()); - String operation = get.toString(); - if(StringUtils.isNotEmpty(operation)) { - operationDefinitions.put(xmlRootElementName, operation); - } - } - logger.debug("opId vs useOpId:"+opId+" vs "+useOpId+" PathParams="+pathParams); - // add PUT - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - logger.debug("xmlRootElementName(1)="+xmlRootElementName); - return null; - } - boolean processingInventoryDef = false; - if ( xmlRootElementName.equals("inventory")) { - // inventory properties for each oxm to be concatenated - processingInventoryDef = true; - if ( inventoryDefSb == null ) { - inventoryDefSb = new StringBuilder(); - definitionsSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" properties:\n"); - } - - } else { - definitionsSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" " + xmlRootElementName + ":\n"); - } - DeleteFootnoteSet footnotes = new DeleteFootnoteSet(xmlRootElementName); - StringBuffer sbEdge = new StringBuffer(); - LinkedHashSet preventDelete = new LinkedHashSet(); - String prevent=null; - String nodeCaption = new String(" ###### Related Nodes\n"); - try { - EdgeRuleQuery q = new EdgeRuleQuery.Builder(xmlRootElementName).version(v).fromOnly().build(); - Multimap results = ei.getRules(q); - SortedSet ss=new TreeSet<>(results.keySet()); - sbEdge.append(nodeCaption); - nodeCaption=""; - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ logger.info(new String(new StringBuffer(" - TO ").append(i.getTo()).append(i.getDirection().toString()).append(i.getContains())));} ); - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ sbEdge.append(" - TO "+i.getTo()); EdgeDescription ed = new EdgeDescription(i); String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName); sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)+footnote+"\n"); if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);} ); - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge() && i.getPreventDelete().equals("OUT")))).forEach((i) ->{ preventDelete.add(i.getTo().toUpperCase());} ); - } - } catch(Exception e) { - logger.debug("xmlRootElementName: "+xmlRootElementName+"\n"+e); - } - try { - EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(xmlRootElementName).version(v).toOnly().build(); - Multimap results = ei.getRules(q1); - SortedSet ss=new TreeSet(results.keySet()); - sbEdge.append(nodeCaption); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ sbEdge.append(" - FROM "+i.getFrom()); EdgeDescription ed = new EdgeDescription(i); String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName); sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)+footnote+"\n"); if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);} ); - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ logger.info(new String(new StringBuffer(" - FROM ").append(i.getFrom()).append(i.getDirection().toString()).append(i.getContains())));} ); - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge() && i.getPreventDelete().equals("IN")))).forEach((i) ->{ preventDelete.add(i.getFrom().toUpperCase());} ); - } - } catch(Exception e) { - logger.debug("xmlRootElementName: "+xmlRootElementName+"\n"+e); - } - if(preventDelete.size() > 0) { - prevent = xmlRootElementName.toUpperCase()+" cannot be deleted if related to "+String.join(",",preventDelete); - logger.debug(prevent); - } - - if(StringUtils.isNotEmpty(prevent)) { - footnotes.add(prevent); - } - if(footnotes.footnotes.size() > 0) { - sbEdge.append(footnotes.toString()); - } - validEdges = sbEdge.toString(); - - // Handle description property. Might have a description OR valid edges OR both OR neither. - // Only put a description: tag if there is at least one. - if (StringUtils.isNotEmpty(pathDescriptionProperty) || StringUtils.isNotEmpty(validEdges) ) { - definitionsSb.append(" description: |\n"); - definitionsLocalSb.append(" description: |\n"); - - if ( pathDescriptionProperty != null ) { - definitionsSb.append(" " + pathDescriptionProperty + "\n" ); - definitionsLocalSb.append(" " + pathDescriptionProperty + "\n" ); - } - definitionsSb.append(validEdges); - definitionsLocalSb.append(validEdges); - } - - if ( requiredCnt > 0 ) { - definitionsSb.append(sbRequired); - definitionsLocalSb.append(sbRequired); - } - - if ( propertyCnt > 0 ) { - definitionsSb.append(" properties:\n"); - definitionsSb.append(sbProperties); - if ( !processingInventoryDef) { - definitionsLocalSb.append(" properties:\n"); - } - definitionsLocalSb.append(sbProperties); - } - try { - namespaceFilter.add(xmlRootElementName); - if ( xmlRootElementName.equals("inventory") ) { - //will add to javaTypeDefinitions at end - inventoryDefSb.append(definitionsLocalSb.toString()); - } else { - javaTypeDefinitions.put(xmlRootElementName, definitionsLocalSb.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - if ( xmlRootElementName.equals("inventory") ) { - logger.trace("skip xmlRootElementName(2)="+xmlRootElementName); - return null; - } - generatedJavaType.put(xmlRootElementName, null); - //Write operations by Namespace(tagName) -/* - if( validTag(javaTypeName) && javaTypeName == useTag && tag == null) { - writeYAMLfile("nodes_"+javaTypeName, getDocumentHeader()+pathSb.toString()+appendDefinitions(namespaceFilter)); - totalPathSbAccumulator.append(pathSb); - pathSb.delete(0, pathSb.length()); - namespaceFilter.clear(); - } -*/ - logger.debug("xmlRootElementName(2)="+xmlRootElementName); - return null; - } - - private void writeYAMLfile(String outfileName, String fileContent) { - outfileName = (StringUtils.isEmpty(outfileName)) ? "aai_swagger" : outfileName; - outfileName = (outfileName.lastIndexOf(File.separator) == -1) ? yaml_dir + File.separator +outfileName+"_" + v.toString() + "." + generateTypeYAML : outfileName; - File outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(parentDir != null && ! parentDir.exists()) - parentDir.mkdirs(); - try { - outfile.createNewFile(); - } catch (IOException e) { - logger.error( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - Path path = Paths.get(outfileName); - Charset charset = Charset.forName("UTF-8"); - try(BufferedWriter bw = Files.newBufferedWriter(path, charset);) { - bw.write(fileContent); - if ( bw != null ) { - bw.close(); - } - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName); - e.printStackTrace(); - } - } - - public boolean validTag(String tag) { - if(tag != null) { - switch ( tag ) { - case "Network": - case "Search": - case "Actions": - case "ServiceDesignAndCreation": - case "Business": - case "LicenseManagement": - case "CloudInfrastructure": - return true; - } - } - return false; - } - - public String appendOperations() { - //append definitions - StringBuffer sb = new StringBuffer(); - Map sortedOperationDefinitions = new TreeMap(operationDefinitions); - for (Map.Entry entry : sortedOperationDefinitions.entrySet()) { - sb.append(entry.getValue()); - } - return sb.toString(); - } -} - diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java deleted file mode 100644 index 8edab757..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java +++ /dev/null @@ -1,525 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.exceptions.AAIException; - -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.nodes.NodeIngestor; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import org.xml.sax.InputSource; - -public abstract class OxmFileProcessor { - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final String DOUBLE_LINE_SEPARATOR = System.getProperty("line.separator") + System.getProperty("line.separator"); - - EdgeIngestor ei; - NodeIngestor ni; - protected Set namespaceFilter; - protected File oxmFile; - protected String xml; - protected SchemaVersion v; - protected Document doc = null; - protected String apiVersion = null; - protected SchemaVersions schemaVersions; - - - protected static int annotationsStartVersion = 9; // minimum version to support annotations in xsd - protected static int annotationsMinVersion = 6; // lower versions support annotations in xsd - protected static int swaggerSupportStartsVersion = 1; // minimum version to support swagger documentation - protected static int swaggerDiffStartVersion = 1; // minimum version to support difference - protected static int swaggerMinBasepath = 6; // minimum version to support difference - - protected Map combinedJavaTypes; - - - protected String apiVersionFmt = null; - protected HashMap generatedJavaType = new HashMap(); - protected HashMap appliedPaths = new HashMap(); - protected NodeList javaTypeNodes = null; - - protected Map javaTypeDefinitions = createJavaTypeDefinitions(); - private Map createJavaTypeDefinitions() - { - StringBuffer aaiInternal = new StringBuffer(); - StringBuffer nodes = new StringBuffer(); - Map javaTypeDefinitions = new HashMap(); - aaiInternal.append(" aai-internal:\n"); - aaiInternal.append(" properties:\n"); - aaiInternal.append(" property-name:\n"); - aaiInternal.append(" type: string\n"); - aaiInternal.append(" property-value:\n"); - aaiInternal.append(" type: string\n"); -// javaTypeDefinitions.put("aai-internal", aaiInternal.toString()); - nodes.append(" nodes:\n"); - nodes.append(" properties:\n"); - nodes.append(" inventory-item-data:\n"); - nodes.append(" type: array\n"); - nodes.append(" items:\n"); - nodes.append(" $ref: \"#/definitions/inventory-item-data\"\n"); - javaTypeDefinitions.put("nodes", nodes.toString()); - return javaTypeDefinitions; - } - static List nodeFilter = createNodeFilter(); - private static List createNodeFilter() - { - List list = Arrays.asList("search", "actions", "aai-internal", "nodes"); - return list; - } - - public OxmFileProcessor(SchemaVersions schemaVersions, NodeIngestor ni, EdgeIngestor ei){ - this.schemaVersions = schemaVersions; - this.ni = ni; - this.ei = ei; - } - - - - public void setOxmVersion(File oxmFile, SchemaVersion v) { - this.oxmFile = oxmFile; - this.v = v; - } - - public void setXmlVersion(String xml, SchemaVersion v) { - this.xml = xml; - this.v = v; - } - - public void setVersion(SchemaVersion v) { - this.oxmFile = null; - this.v = v; - } - - public void setNodeIngestor(NodeIngestor ni) { - this.ni = ni; - } - - public void setEdgeIngestor(EdgeIngestor ei) { - this.ei = ei; - } - - public SchemaVersions getSchemaVersions() { - return schemaVersions; - } - - public void setSchemaVersions(SchemaVersions schemaVersions) { - this.schemaVersions = schemaVersions; - } - - protected void init() throws ParserConfigurationException, SAXException, IOException, AAIException, EdgeRuleNotFoundException { - if(this.xml != null || this.oxmFile != null ) { - createDocument(); - } - if(this.doc == null) { - this.doc = ni.getSchema(v); - } - namespaceFilter = new HashSet<>(); - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - throw new AAIException("OXM file error: missing in " + oxmFile); - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - throw new AAIException("OXM file error: missing in " + oxmFile); - } - javaTypesElement = (Element) javaTypesNodes.item(0); - - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - throw new AAIException("OXM file error: missing in " + oxmFile ); - } - } - - private void createDocument() throws ParserConfigurationException, SAXException, IOException, AAIException { - DocumentBuilder dBuilder = null; - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - dBuilder = dbFactory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw e; - } - try { - if ( xml == null ) { - doc = dBuilder.parse(oxmFile); - } else { - InputSource isInput = new InputSource(new StringReader(xml)); - doc = dBuilder.parse(isInput); - } - } catch (SAXException e) { - throw e; - } catch (IOException e) { - throw e; - } - return; - } - public abstract String getDocumentHeader(); - public abstract String process() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException ; - - public String getXMLRootElementName(Element javaTypeElement) { - String xmlRootElementName=null; - NamedNodeMap attributes; - - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - xmlRootElementName = attrValue; - } - return xmlRootElementName; - } - - public String getXmlRootElementName( String javaTypeName ) - { - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - attr = (Attr) attributes.item(k); - attrName = attr.getNodeName(); - - attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - return (attrValue); - } - } - } - } - return null; - } - - public Map getCombinedJavaTypes() { - return combinedJavaTypes; - } - - public void setCombinedJavaTypes(Map combinedJavaTypes) { - this.combinedJavaTypes = combinedJavaTypes; - } - - public Element getJavaTypeElementSwagger( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - - List combineElementList = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { - combineElementList.add(javaTypeElement); - } - } - } - if ( combineElementList.size() == 0 ) { - return (Element) null; - } else if ( combineElementList.size() > 1 ) { - return combineElements( javaTypeName, combineElementList); - } - return combineElementList.get(0); - } - - public boolean versionSupportsSwaggerDiff( String version) { - int ver = new Integer(version.substring(1)).intValue(); - if ( ver >= HTMLfromOXM.swaggerDiffStartVersion ) { - return true; - } - return false; - } - - public boolean versionSupportsBasePathProperty( String version) { - int ver = new Integer(version.substring(1)).intValue(); - if ( ver <= HTMLfromOXM.swaggerMinBasepath ) { - return true; - } - return false; - } - - protected void updateParentXmlElements(Element parentElement, NodeList moreXmlElementNodes) { - Element xmlElement; - NodeList childNodes; - Node childNode; - - Node refChild = null; - // find childNode with attributes and no children, insert children before that node - childNodes = parentElement.getChildNodes(); - if ( childNodes == null || childNodes.getLength() == 0 ) { - // should not happen since the base parent was chosen if it had children - return; - } - - for ( int i = 0; i < childNodes.getLength(); ++i ) { - refChild = childNodes.item(i); - if ( refChild.hasAttributes() && !refChild.hasChildNodes()) { - break; - } - - } - - for ( int i = 0; i < moreXmlElementNodes.getLength(); ++i ) { - xmlElement = (Element)moreXmlElementNodes.item(i); - childNode = xmlElement.cloneNode(true); - parentElement.insertBefore(childNode, refChild); - } - } - - protected Node getXmlPropertiesNode(Element javaTypeElement ) { - NodeList nl = javaTypeElement.getChildNodes(); - Node child; - for ( int i = 0; i < nl.getLength(); ++i ) { - child = nl.item(i); - if ( "xml-properties".equals(child.getNodeName())) { - return child; - } - } - return null; - } - - protected Node merge( NodeList nl, Node mergeNode ) { - NamedNodeMap nnm = mergeNode.getAttributes(); - Node childNode; - NamedNodeMap childNnm; - - String mergeName = nnm.getNamedItem("name").getNodeValue(); - String mergeValue = nnm.getNamedItem("value").getNodeValue(); - String childName; - String childValue; - for ( int j = 0; j < nl.getLength(); ++j ) { - childNode = nl.item(j); - if ( "xml-property".equals(childNode.getNodeName())) { - childNnm = childNode.getAttributes(); - childName = childNnm.getNamedItem("name").getNodeValue(); - childValue = childNnm.getNamedItem("value").getNodeValue(); - if ( childName.equals(mergeName)) { - // attribute exists - // keep, replace or update - if ( childValue.contains(mergeValue) ) { - return null; - } - if ( mergeValue.contains(childValue) ) { - childNnm.getNamedItem("value").setTextContent(mergeValue); - return null; - } - childNnm.getNamedItem("value").setTextContent(mergeValue + "," + childValue); - return null; - } - } - } - childNode = mergeNode.cloneNode(true); - return childNode; - } - - protected void mergeXmlProperties(Node useChildProperties, NodeList propertiesToMerge ) { - NodeList nl = useChildProperties.getChildNodes(); - Node childNode; - Node newNode; - for ( int i = 0; i < propertiesToMerge.getLength(); ++i ) { - childNode = propertiesToMerge.item(i); - if ( "xml-property".equals(childNode.getNodeName()) ) { - newNode = merge(nl, childNode); - if ( newNode != null ) { - useChildProperties.appendChild(newNode); - } - } - - } - } - - protected void combineXmlProperties(int useElement, List combineElementList) { - // add or update xml-properties to the referenced element from the combined list - Element javaTypeElement = combineElementList.get(useElement); - NodeList nl = javaTypeElement.getChildNodes(); - Node useChildProperties = getXmlPropertiesNode( javaTypeElement); - int cloneChild = -1; - Node childProperties; - if ( useChildProperties == null ) { - // find xml-properties to clone - for ( int i = 0; i < combineElementList.size(); ++i ) { - if ( i == useElement ) { - continue; - } - childProperties = getXmlPropertiesNode(combineElementList.get(i)); - if ( childProperties != null ) { - useChildProperties = childProperties.cloneNode(true); - javaTypeElement.appendChild(useChildProperties); - cloneChild = i; - } - } - } - NodeList cnl; - // find other xml-properties - for ( int i = 0; i < combineElementList.size(); ++i ) { - if ( i == useElement|| ( cloneChild >= 0 && i <= cloneChild )) { - continue; - } - childProperties = getXmlPropertiesNode(combineElementList.get(i)); - if ( childProperties == null ) { - continue; - } - cnl = childProperties.getChildNodes(); - mergeXmlProperties( useChildProperties, cnl); - } - - } - - protected Element combineElements( String javaTypeName, List combineElementList ) { - Element javaTypeElement; - NodeList parentNodes; - Element parentElement = null; - NodeList xmlElementNodes; - - int useElement = -1; - if ( combinedJavaTypes.containsKey( javaTypeName) ) { - return combineElementList.get((int)combinedJavaTypes.get(javaTypeName)); - } - for ( int i = 0; i < combineElementList.size(); ++i ) { - javaTypeElement = combineElementList.get(i); - parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - if ( parentNodes.getLength() == 0 ) { - continue; - } - parentElement = (Element)parentNodes.item(0); - xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - if ( xmlElementNodes.getLength() <= 0 ) { - continue; - } - useElement = i; - break; - } - boolean doCombineElements = true; - if ( useElement < 0 ) { - useElement = 0; - doCombineElements = false; - } else if ( useElement == combineElementList.size() - 1) { - doCombineElements = false; - } - if ( doCombineElements ) { - // get xml-element from other javaTypeElements - Element otherParentElement = null; - for ( int i = 0; i < combineElementList.size(); ++i ) { - if ( i == useElement ) { - continue; - } - javaTypeElement = combineElementList.get(i); - parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - if ( parentNodes.getLength() == 0 ) { - continue; - } - otherParentElement = (Element)parentNodes.item(0); - xmlElementNodes = otherParentElement.getElementsByTagName("xml-element"); - if ( xmlElementNodes.getLength() <= 0 ) { - continue; - } - // xml-element that are not present - updateParentXmlElements( parentElement, xmlElementNodes); - - } - } - // need to combine xml-properties - combineXmlProperties(useElement, combineElementList ); - combinedJavaTypes.put( javaTypeName, useElement); - return combineElementList.get(useElement); - } - - - private static void prettyPrint(Node node, String tab) - { - // for debugging - try { - // Set up the output transformer - TransformerFactory transfac = TransformerFactory.newInstance(); - Transformer trans = transfac.newTransformer(); - trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - StringWriter sw = new StringWriter(); - StreamResult result = new StreamResult(sw); - DOMSource source = new DOMSource(node); - trans.transform(source, result); - String xmlString = sw.toString(); - System.out.println(xmlString); - } - catch (TransformerException e) { - e.printStackTrace(); - } - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java deleted file mode 100644 index 37b2d1b1..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.StringTokenizer; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.util.GenerateXsd; - -public class PatchOperation { - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - - public PatchOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams = pathParams; - } - - public String toString() { - StringTokenizer st; - st = new StringTokenizer(path, "/"); - //a valid tag is necessary - if ( StringUtils.isEmpty(tag) ) { - return ""; - } - if ( path.contains("/relationship/") ) { // filter paths with relationship-list - return ""; - } - if ( path.endsWith("/relationship-list")) { - return ""; - } - if ( path.startsWith("/search")) { - return ""; - } - //No Patch operation paths end with "relationship" - - if (path.endsWith("/relationship") ) { - return ""; - } - if (!path.endsWith("}")) { - return ""; - } - - StringBuffer pathSb = new StringBuffer(); - StringBuffer relationshipExamplesSb = new StringBuffer(); - if ( path.endsWith("/relationship") ) { - pathSb.append(" " + path + ":\n" ); - } - pathSb.append(" patch:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - - if ( path.endsWith("/relationship") ) { - pathSb.append(" summary: see node definition for valid relationships\n"); - relationshipExamplesSb.append("[See Examples](apidocs/relations/"+GenerateXsd.getAPIVersion()+"/"+useOpId+".json)"); - } else { - pathSb.append(" summary: update an existing " + xmlRootElementName + "\n"); - pathSb.append(" description: |\n"); - pathSb.append(" Update an existing " + xmlRootElementName + "\n"); - pathSb.append(" #\n"); - pathSb.append(" Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); - pathSb.append(" The PUT operation will entirely replace an existing object.\n"); - pathSb.append(" The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); - pathSb.append(" #\n"); - pathSb.append(" Other differences between PUT and PATCH are:\n"); - pathSb.append(" #\n"); - pathSb.append(" - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); - pathSb.append(" - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); - pathSb.append(" - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); - } - pathSb.append(" operationId: Update" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + GenerateXsd.getResponsesUrl()); - pathSb.append(" parameters:\n"); - pathSb.append(pathParams); // for nesting - pathSb.append(" - name: body\n"); - pathSb.append(" in: body\n"); - pathSb.append(" description: " + xmlRootElementName + " object that needs to be updated."+relationshipExamplesSb.toString()+"\n"); - pathSb.append(" required: true\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/patchDefinitions/" + xmlRootElementName + "\"\n"); - return pathSb.toString(); - } - } - \ No newline at end of file diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java deleted file mode 100644 index 6597d034..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.util.GenerateXsd; - -public class PutOperation { - public static final String RELATIONSHIP = "relationship"; - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private SchemaVersion version; - - public PutOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, SchemaVersion v) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams = pathParams; - this.version = v; - } - - @Override - public String toString() { - //a valid tag is necessary - if ( StringUtils.isEmpty(tag) ) { - return ""; - } - //All Put operation paths end with "relationship" - //or there is a parameter at the end of the path - //and there is a parameter in the path - if ( path.contains("/"+RELATIONSHIP+"/") ) { // filter paths with relationship-list - return ""; - } - if ( path.endsWith("/"+RELATIONSHIP+"-list")) { - return ""; - } - if ( !path.endsWith("/"+RELATIONSHIP) && !path.endsWith("}") ) { - return ""; - } - if ( path.startsWith("/search")) { - return ""; - } - StringBuffer pathSb = new StringBuffer(); - StringBuffer relationshipExamplesSb = new StringBuffer(); - if ( path.endsWith("/"+RELATIONSHIP) ) { - pathSb.append(" " + path + ":\n" ); - } - pathSb.append(" put:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - - if ( path.endsWith("/"+RELATIONSHIP) ) { - pathSb.append(" summary: see node definition for valid relationships\n"); - } else { - pathSb.append(" summary: create or update an existing " + xmlRootElementName + "\n"); - pathSb.append(" description: |\n Create or update an existing " + xmlRootElementName + ".\n #\n Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); - } - relationshipExamplesSb.append("[Valid relationship examples shown here](apidocs/relations/"+version.toString()+"/"+useOpId.replace("RelationshipListRelationship", "")+".json)"); - pathSb.append(" operationId: createOrUpdate" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + GenerateXsd.getResponsesUrl()); - - pathSb.append(" parameters:\n"); - pathSb.append(pathParams); // for nesting - pathSb.append(" - name: body\n"); - pathSb.append(" in: body\n"); - pathSb.append(" description: " + xmlRootElementName + " object that needs to be created or updated. "+relationshipExamplesSb.toString()+"\n"); - pathSb.append(" required: true\n"); - pathSb.append(" schema:\n"); - String useElement = xmlRootElementName; - if ( xmlRootElementName.equals("relationship")) { - useElement += "-dict"; - } - pathSb.append(" $ref: \"#/definitions/" + useElement + "\"\n"); - this.tagRelationshipPathMapEntry(); - return pathSb.toString(); - } - - public String tagRelationshipPathMapEntry() { - if ( path.endsWith("/"+RELATIONSHIP) ) { - PutRelationPathSet.add(useOpId, path); - } - return ""; - } - - } diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java deleted file mode 100644 index 3d055b81..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java +++ /dev/null @@ -1,224 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.commons.text.similarity.LevenshteinDistance; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.config.SpringContextAware; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.EdgeRuleQuery; -import org.onap.aai.util.GenerateXsd; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Multimap; - -public class PutRelationPathSet { - EdgeIngestor ei; - private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class"); - protected static HashMap putRelationPaths = new HashMap(); - public static void add(String useOpId, String path) { - putRelationPaths.put(useOpId, path); - } - - String apiPath; - String opId; - SchemaVersion version; - protected ArrayList relations = new ArrayList(); - String objectName = ""; - - public PutRelationPathSet(SchemaVersion v) { - this.version = v; - } - - public PutRelationPathSet(String opId, String path, SchemaVersion v) { - this.apiPath = path.replace("/relationship-list/relationship", ""); - this.opId = opId; - this.version = v; - objectName = DeleteOperation.deletePaths.get(apiPath); - logger.debug("II-apiPath: "+apiPath+"\nPath: "+path+"\nopId="+opId+"\nobjectName="+objectName); - } - private void process(EdgeIngestor edgeIngestor) { - this.ei = edgeIngestor; - this.toRelations(); - this.fromRelations(); - this.writeRelationsFile(); - - } - private void toRelations() { - logger.debug("{“comment”: “Valid TO Relations that can be added”},"); - logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName); - try { - - EdgeRuleQuery q1 = new EdgeRuleQuery.Builder("ToOnly",objectName).version(version).build(); - Multimap results = ei.getRules(q1); - relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n"); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } ); - } - } catch(Exception e) { - logger.debug("objectName: "+objectName+"\n"+e); - } - } - private String selectedRelation(EdgeRule rule) { - String selectedRelation = ""; - EdgeDescription ed = new EdgeDescription(rule); - logger.debug(ed.getRuleKey()+"Type="+ed.getType()); - String obj = ed.getRuleKey().replace(objectName,"").replace("|",""); - - if(ed.getType() == EdgeDescription.LineageType.UNRELATED) { - String selectObj = getUnrelatedObjectPaths(obj, apiPath); - logger.debug("SelectedObj"+selectObj); - selectedRelation = formatObjectRelationSet(obj,selectObj); - logger.trace("ObjectRelationSet"+selectedRelation); - } else { - String selectObj = getKinObjectPath(obj, apiPath); - logger.debug("SelectedObj"+selectObj); - selectedRelation = formatObjectRelation(obj,selectObj); - logger.trace("ObjectRelationSet"+selectedRelation); - } - return selectedRelation; - } - - private void fromRelations() { - logger.debug("“comment”: “Valid FROM Relations that can be added”"); - try { - - EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(objectName,"FromOnly").version(version).build(); - Multimap results = ei.getRules(q1); - relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n"); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } ); - } - } catch(Exception e) { - logger.debug("objectName: "+objectName+"\n"+e); - } - } - private void writeRelationsFile() { - File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json"); - - logger.debug(String.join("exampleFilePath: ", examplefilePath.toString())); - FileOutputStream fop = null; - try { - if (!examplefilePath.exists()) { - examplefilePath.getParentFile().mkdirs(); - examplefilePath.createNewFile(); - } - fop = new FileOutputStream(examplefilePath); - } catch(Exception e) { - e.printStackTrace(); - return; - } - try { - if(relations.size() > 0) {fop.write("[\n".getBytes());} - fop.write(String.join(",\n", relations).getBytes()); - if(relations.size() > 0) {fop.write("\n]\n".getBytes());} - fop.flush(); - fop.close(); - } catch (Exception e) { - e.printStackTrace(); - return; - } - finally{ - try { - fop.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - logger.debug(String.join(",\n", relations)); - return; - } - - private static String formatObjectRelationSet(String obj, String selectObj) { - StringBuffer pathSb = new StringBuffer(); - String[] paths = selectObj.split("[|]"); - for (String s: paths) { - logger.trace("SelectOBJ"+s); - pathSb.append(formatObjectRelation(obj, s)+",\n"); - } - pathSb.deleteCharAt(pathSb.length()-2); - return pathSb.toString(); - } - - private static String formatObjectRelation(String obj, String selectObj) { - StringBuffer pathSb = new StringBuffer(); - pathSb.append("{\n"); - pathSb.append("\"related-to\" : \""+obj+"\",\n"); - pathSb.append("\"related-link\" : \""+selectObj+"\"\n"); - pathSb.append("}"); - return pathSb.toString(); - } - - private static String getKinObjectPath(String obj, String apiPath) { - LevenshteinDistance proximity = new LevenshteinDistance(); - String targetPath = ""; - int targetScore = Integer.MAX_VALUE; - int targetMaxScore = 0; - for (Map.Entry p : DeleteOperation.deletePaths.entrySet()) { - if(p.getValue().equals(obj)) { - targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore; - targetPath = (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath; - targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore; - logger.trace(proximity.apply(apiPath, p.getKey())+":"+p.getKey()); - logger.trace(proximity.apply(apiPath, p.getKey())+":"+apiPath); - } - } - return targetPath; - } - - private static String getUnrelatedObjectPaths(String obj, String apiPath) { - String targetPath = ""; - logger.trace("Obj:"+obj +"\n" + apiPath); - for (Map.Entry p : DeleteOperation.deletePaths.entrySet()) { - if(p.getValue().equals(obj)) { - logger.trace("p.getvalue:"+p.getValue()+"p.getkey:"+p.getKey()); - targetPath += ((targetPath.length() == 0 ? "" : "|") + p.getKey()); - logger.trace("Match:"+apiPath +"\n" + targetPath); - } - } - return targetPath; - } - - public void generateRelations(EdgeIngestor edgeIngestor) { - putRelationPaths.forEach((k,v)->{ - logger.trace("k="+k+"\n"+"v="+v+v.equals("/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}/allotted-resources/allotted-resource/{id}/relationship-list/relationship")); - logger.debug("apiPath(Operation): "+v); - logger.debug("Target object: "+v.replace("/relationship-list/relationship", "")); - logger.debug("Relations: "); - PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version); - prp.process(edgeIngestor); - }); - } - -} - diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java deleted file mode 100644 index db7c54c3..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java +++ /dev/null @@ -1,756 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; -import java.util.Vector; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.setup.SchemaVersion; -import org.w3c.dom.Attr; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.TypeInfo; -import org.w3c.dom.UserDataHandler; - -import com.google.common.base.Joiner; - -public class XSDElement implements Element { - Element xmlElementElement; - String maxOccurs; - private static final int VALUE_NONE = 0; - private static final int VALUE_DESCRIPTION = 1; - private static final int VALUE_INDEXED_PROPS = 2; - private static final int VALUE_CONTAINER = 3; - private static final int VALUE_REQUIRES = 4; - - public XSDElement(Element xmlElementElement, String maxOccurs) { - super(); - this.xmlElementElement = xmlElementElement; - this.maxOccurs = maxOccurs; - } - - public XSDElement(Element xmlElementElement) { - super(); - this.xmlElementElement = xmlElementElement; - this.maxOccurs = null; - } - - public String name() { - return this.getAttribute("name"); - } - - public Vector getAddTypes(String version) { - String apiVersionFmt = "." + version + "."; - NamedNodeMap attributes = this.getAttributes(); - Vector addTypeV = new Vector(); // vector of 1 - String addType = null; - - for ( int j = 0; j < attributes.getLength(); ++j ) { - Attr attr = (Attr) attributes.item(j); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - if ( attrName.equals("type")) { - if ( attrValue.contains(apiVersionFmt) ) { - addType = attrValue.substring(attrValue.lastIndexOf('.')+1); - if ( addTypeV == null ) - addTypeV = new Vector(); - addTypeV.add(addType); - } - - } - } - return addTypeV; - } - - public String getRequiresProperty() { - String elementAlsoRequiresProperty = null; - NodeList xmlPropNodes = this.getElementsByTagName("xml-properties"); - - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - Element xmlPropElement = (Element)xmlPropNodes.item(i); - if (! xmlPropElement.getParentNode().getAttributes().getNamedItem("name").getNodeValue().equals(this.xmlElementElement.getAttribute("name"))){ - continue; - } - NodeList childNodes = xmlPropElement.getElementsByTagName("xml-property"); - - for ( int j = 0; j < childNodes.getLength(); ++j ) { - Element childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - NamedNodeMap attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( attrName.equals("name") && attrValue.equals("requires")) { - useValue = VALUE_REQUIRES; - } - if ( useValue == VALUE_REQUIRES && attrName.equals("value")) { - elementAlsoRequiresProperty = attrValue; - } - } - } - } - return elementAlsoRequiresProperty; - } - - public String getPathDescriptionProperty() { - String pathDescriptionProperty = null; - NodeList xmlPropNodes = this.getElementsByTagName("xml-properties"); - - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - Element xmlPropElement = (Element)xmlPropNodes.item(i); - if (! xmlPropElement.getParentNode().getAttributes().getNamedItem("name").getNodeValue().equals(this.xmlElementElement.getAttribute("name"))){ - continue; - } -// This stopped working, replaced with above - should figure out why... -// if ( !xmlPropElement.getParentNode().isSameNode(this.xmlElementElement)) -// continue; - NodeList childNodes = xmlPropElement.getElementsByTagName("xml-property"); - - for ( int j = 0; j < childNodes.getLength(); ++j ) { - Element childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - NamedNodeMap attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( attrName.equals("name") && attrValue.equals("description")) { - useValue = VALUE_DESCRIPTION; - } - if ( useValue == VALUE_DESCRIPTION && attrName.equals("value")) { - pathDescriptionProperty = attrValue; - } - } - } - } - return pathDescriptionProperty; - } - public Vector getIndexedProps() { - Vector indexedProps = new Vector(); - NodeList xmlPropNodes = this.getElementsByTagName("xml-properties"); - - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - Element xmlPropElement = (Element)xmlPropNodes.item(i); - if ( !xmlPropElement.getParentNode().isSameNode(this.xmlElementElement)) - continue; - NodeList childNodes = xmlPropElement.getElementsByTagName("xml-property"); - for ( int j = 0; j < childNodes.getLength(); ++j ) { - Element childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - NamedNodeMap attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( attrValue.equals("indexedProps")) { - useValue = VALUE_INDEXED_PROPS; - } - if ( useValue == VALUE_INDEXED_PROPS && attrName.equals("value")) { - indexedProps = getIndexedProps( attrValue ); - } - } - } - } - return indexedProps; - } - - private static Vector getIndexedProps( String attrValue ) - { - if ( attrValue == null ) - return null; - StringTokenizer st = new StringTokenizer( attrValue, ","); - if ( st.countTokens() == 0 ) - return null; - Vector result = new Vector(); - while ( st.hasMoreTokens()) { - result.add(st.nextToken()); - } - return result; - } - - public String getContainerProperty() { - NodeList xmlPropNodes = this.getElementsByTagName("xml-properties"); - String container = null; - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - Element xmlPropElement = (Element)xmlPropNodes.item(i); - if ( !xmlPropElement.getParentNode().isSameNode(this.xmlElementElement)) - continue; - NodeList childNodes = xmlPropElement.getElementsByTagName("xml-property"); - for ( int j = 0; j < childNodes.getLength(); ++j ) { - Element childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - NamedNodeMap attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( useValue == VALUE_CONTAINER && attrName.equals("value")) { - container = attrValue; - } - if ( attrValue.equals("container")) { - useValue = VALUE_CONTAINER; - } - } - } - } - return container; - } - - public String getQueryParamYAML() { - return getQueryParamYAML(null); - } - - public String getQueryParamYAML(String elementDescription ) { - // when elementDescription is not null, return parameters with description and example - StringBuffer sbParameter = new StringBuffer(); - sbParameter.append((" - name: " + this.getAttribute("name") + "\n")); - sbParameter.append((" in: query\n")); - String useDescription = elementDescription; - if ( elementDescription == null ) { - useDescription = this.getAttribute("description"); - } - if ( useDescription != null && useDescription.length() > 0 ) { - sbParameter.append((" description: " + useDescription + "\n")); - } else { - sbParameter.append((" description:\n")); - } - sbParameter.append((" required: false\n")); - if ( ("java.lang.String").equals(this.getAttribute("type"))) - sbParameter.append(" type: string\n"); - if ( ("java.lang.Long").equals(this.getAttribute("type"))) { - sbParameter.append(" type: integer\n"); - sbParameter.append(" format: int64\n"); - } - if ( ("java.lang.Integer").equals(this.getAttribute("type"))) { - sbParameter.append(" type: integer\n"); - sbParameter.append(" format: int32\n"); - } - if ( ("java.lang.Boolean").equals(this.getAttribute("type"))) { - sbParameter.append(" type: boolean\n"); - } - if ( elementDescription != null && StringUtils.isNotBlank(this.getAttribute("name"))) { - sbParameter.append(" example: "+"__"+this.getAttribute("name").toUpperCase()+"__"+"\n"); - } - return sbParameter.toString(); - } - - public String getPathParamYAML(String elementDescription) { - return getPathParamYAMLRqd( elementDescription, true); - } - - public String getPathParamYAMLRqd(String elementDescription, boolean isRqd) { - StringBuffer sbParameter = new StringBuffer(); - sbParameter.append((" - name: " + this.getAttribute("name") + "\n")); - sbParameter.append((" in: path\n")); - if ( elementDescription != null && elementDescription.length() > 0 ) - sbParameter.append((" description: " + elementDescription + "\n")); - if ( isRqd ) { - sbParameter.append((" required: true\n")); - } else { - // used by Nodes API for query params - sbParameter.append((" required: false\n")); - } - if ( ("java.lang.String").equals(this.getAttribute("type"))) - sbParameter.append(" type: string\n"); - if ( ("java.lang.Long").equals(this.getAttribute("type"))) { - sbParameter.append(" type: integer\n"); - sbParameter.append(" format: int64\n"); - } - if ( ("java.lang.Integer").equals(this.getAttribute("type"))) { - sbParameter.append(" type: integer\n"); - sbParameter.append(" format: int32\n"); - } - if ( ("java.lang.Boolean").equals(this.getAttribute("type"))) { - sbParameter.append(" type: boolean\n"); - } - if(StringUtils.isNotBlank(this.getAttribute("name"))) { - sbParameter.append(" example: "+"__"+this.getAttribute("name").toUpperCase()+"__"+"\n"); - } - return sbParameter.toString(); - } - - public String getHTMLElement(SchemaVersion v, boolean useAnnotation, HTMLfromOXM driver) { - StringBuffer sbElement = new StringBuffer(); - String elementName = this.getAttribute("name"); - String elementType = this.getAttribute("type"); - String elementContainerType = this.getAttribute("container-type"); - String elementIsRequired = this.getAttribute("required"); - String addType = elementType.contains("." + v.toString() + ".") ? elementType.substring(elementType.lastIndexOf('.')+1) : null; - - if ( addType != null ) { - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR : ""); - sbElement.append(annotation); - sbElement.append(StringUtils.isNotEmpty(annotation) ? " " + OxmFileProcessor.LINE_SEPARATOR : "/>" + OxmFileProcessor.LINE_SEPARATOR ); - } else { - sbElement.append("/>" + OxmFileProcessor.LINE_SEPARATOR); - } - return this.getHTMLElementWrapper(sbElement.toString(), v, useAnnotation); -// return sbElement.toString(); - } - - public String getHTMLElementWrapper(String unwrappedElement, SchemaVersion v, boolean useAnnotation) { - - NodeList childNodes = this.getElementsByTagName("xml-element-wrapper"); - - String xmlElementWrapper = null; - if ( childNodes.getLength() > 0 ) { - Element childElement = (Element)childNodes.item(0); - // get name - xmlElementWrapper = childElement == null ? null : childElement.getAttribute("name"); - } - if(xmlElementWrapper == null) - return unwrappedElement; - - StringBuffer sbElement = new StringBuffer(); - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - if(useAnnotation) { - XSDElement javaTypeElement = new XSDElement((Element)this.getParentNode(), maxOccurs); - sbElement.append(javaTypeElement.getHTMLAnnotation("class", " ")); - } - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sbElement.append(" "); - sbElement.append(unwrappedElement); - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR); - return sbElement.toString(); - } - - public String getHTMLAnnotation(String target, String indentation) { - StringBuffer sb = new StringBuffer(); - List metadata = new ArrayList<>(); - if("true".equals(this.getAttribute("xml-key")) ) { - metadata.add("isKey=true"); - } - - NodeList xmlPropTags = this.getElementsByTagName("xml-properties"); - Element xmlPropElement = null; - for ( int i = 0; i < xmlPropTags.getLength(); ++i ) { - xmlPropElement = (Element)xmlPropTags.item(i); - if (! xmlPropElement.getParentNode().getAttributes().getNamedItem("name").getNodeValue().equals(this.xmlElementElement.getAttribute("name"))) - continue; - else - break; - } - if(xmlPropElement != null) { - NodeList xmlProperties = xmlPropElement.getElementsByTagName("xml-property"); - for (int i = 0; i < xmlProperties.getLength(); i++) { - Element item = (Element)xmlProperties.item(i); - String name = item.getAttribute("name"); - String value = item.getAttribute("value"); - if (name.equals("abstract")) { - name = "isAbstract"; - } else if (name.equals("extends")) { - name = "extendsFrom"; - } - metadata.add(name + "=\"" + value.replaceAll("&", "&") + "\""); - } - } - if(metadata.size() == 0) { - return ""; - } - sb.append(indentation +"" + OxmFileProcessor.LINE_SEPARATOR); - sb.append( - indentation + " " + OxmFileProcessor.LINE_SEPARATOR + - indentation + " @org.onap.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")" + OxmFileProcessor.LINE_SEPARATOR + - indentation + " " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(indentation +"" + OxmFileProcessor.LINE_SEPARATOR); - return sb.toString(); - } - - public String getTypePropertyYAML() { - StringBuffer sbProperties = new StringBuffer(); - sbProperties.append(" " + this.getAttribute("name") + ":\n"); - sbProperties.append(" type: "); - - if ( ("java.lang.String").equals(this.getAttribute("type"))) - sbProperties.append("string\n"); - else if ( ("java.lang.Long").equals(this.getAttribute("type"))) { - sbProperties.append("integer\n"); - sbProperties.append(" format: int64\n"); - } - else if ( ("java.lang.Integer").equals(this.getAttribute("type"))){ - sbProperties.append("integer\n"); - sbProperties.append(" format: int32\n"); - } - else if ( ("java.lang.Boolean").equals(this.getAttribute("type"))) - sbProperties.append("boolean\n"); - String attrDescription = this.getPathDescriptionProperty(); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - String elementAlsoRequiresProperty=this.getRequiresProperty(); - if ( StringUtils.isNotEmpty(elementAlsoRequiresProperty) ) - sbProperties.append(" also requires: " + elementAlsoRequiresProperty + "\n"); - return sbProperties.toString(); - } - - public boolean isStandardType() - { - switch ( this.getAttribute("type") ) { - case "java.lang.String": - case "java.lang.Long": - case "java.lang.Integer": - case"java.lang.Boolean": - return true; - } - return false; - } - - @Override - public String getNodeName() { - return xmlElementElement.getNodeName(); - } - - @Override - public String getNodeValue() throws DOMException { - return xmlElementElement.getNodeValue(); - } - - @Override - public void setNodeValue(String nodeValue) throws DOMException { - xmlElementElement.setNodeValue(nodeValue); - } - - @Override - public short getNodeType() { - return xmlElementElement.getNodeType(); - } - - @Override - public Node getParentNode() { - return xmlElementElement.getParentNode(); - } - - @Override - public NodeList getChildNodes() { - return xmlElementElement.getChildNodes(); - } - - @Override - public Node getFirstChild() { - return xmlElementElement.getFirstChild(); - } - - @Override - public Node getLastChild() { - return xmlElementElement.getLastChild(); - } - - @Override - public Node getPreviousSibling() { - return xmlElementElement.getPreviousSibling(); - } - - @Override - public Node getNextSibling() { - return xmlElementElement.getNextSibling(); - } - - @Override - public NamedNodeMap getAttributes() { - return xmlElementElement.getAttributes(); - } - - @Override - public Document getOwnerDocument() { - return xmlElementElement.getOwnerDocument(); - } - - @Override - public Node insertBefore(Node newChild, Node refChild) throws DOMException { - return xmlElementElement.insertBefore(newChild, refChild); - } - - @Override - public Node replaceChild(Node newChild, Node oldChild) throws DOMException { - return xmlElementElement.replaceChild(newChild, oldChild); - } - - @Override - public Node removeChild(Node oldChild) throws DOMException { - return xmlElementElement.removeChild(oldChild); - } - - @Override - public Node appendChild(Node newChild) throws DOMException { - return xmlElementElement.appendChild(newChild); - } - - @Override - public boolean hasChildNodes() { - return xmlElementElement.hasChildNodes(); - } - - @Override - public Node cloneNode(boolean deep) { - return xmlElementElement.cloneNode(deep); - } - - @Override - public void normalize() { - xmlElementElement.normalize(); - } - - @Override - public boolean isSupported(String feature, String version) { - return xmlElementElement.isSupported(feature, version); - } - - @Override - public String getNamespaceURI() { - return xmlElementElement.getNamespaceURI(); - } - - @Override - public String getPrefix() { - return xmlElementElement.getPrefix(); - } - - @Override - public void setPrefix(String prefix) throws DOMException { - xmlElementElement.setPrefix(prefix); - } - - @Override - public String getLocalName() { - - return xmlElementElement.getLocalName(); - } - - @Override - public boolean hasAttributes() { - return xmlElementElement.hasAttributes(); - } - - @Override - public String getBaseURI() { - return xmlElementElement.getBaseURI(); - } - - @Override - public short compareDocumentPosition(Node other) throws DOMException { - return xmlElementElement.compareDocumentPosition(other); - } - - @Override - public String getTextContent() throws DOMException { - return xmlElementElement.getTextContent(); - } - - @Override - public void setTextContent(String textContent) throws DOMException { - xmlElementElement.setTextContent(textContent); - } - - @Override - public boolean isSameNode(Node other) { - return xmlElementElement.isSameNode(other); - } - - @Override - public String lookupPrefix(String namespaceURI) { - return xmlElementElement.lookupPrefix(namespaceURI); - } - - @Override - public boolean isDefaultNamespace(String namespaceURI) { - return xmlElementElement.isDefaultNamespace(namespaceURI); - } - - @Override - public String lookupNamespaceURI(String prefix) { - return xmlElementElement.lookupNamespaceURI(prefix); - } - - @Override - public boolean isEqualNode(Node arg) { - return xmlElementElement.isEqualNode(arg); - } - - @Override - public Object getFeature(String feature, String version) { - return xmlElementElement.getFeature(feature, version); - } - - @Override - public Object setUserData(String key, Object data, UserDataHandler handler) { - return xmlElementElement.setUserData(key, data, handler); - } - - @Override - public Object getUserData(String key) { - return xmlElementElement.getUserData(key); - } - - @Override - public String getTagName() { - return xmlElementElement.getTagName(); - } - - @Override - public String getAttribute(String name) { - return xmlElementElement.getAttribute(name); - } - - @Override - public void setAttribute(String name, String value) throws DOMException { - xmlElementElement.setAttribute(name, value); - } - - @Override - public void removeAttribute(String name) throws DOMException { - xmlElementElement.removeAttribute(name); - } - - @Override - public Attr getAttributeNode(String name) { - return xmlElementElement.getAttributeNode(name); - } - - @Override - public Attr setAttributeNode(Attr newAttr) throws DOMException { - return xmlElementElement.setAttributeNode(newAttr); - } - - @Override - public Attr removeAttributeNode(Attr oldAttr) throws DOMException { - return xmlElementElement.removeAttributeNode(oldAttr); - } - - @Override - public NodeList getElementsByTagName(String name) { - return xmlElementElement.getElementsByTagName(name); - } - - @Override - public String getAttributeNS(String namespaceURI, String localName) throws DOMException { - return xmlElementElement.getAttributeNS(namespaceURI, localName); - } - - @Override - public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { - xmlElementElement.setAttributeNS(namespaceURI, qualifiedName, value); - return; - } - - @Override - public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { - xmlElementElement.removeAttributeNS(namespaceURI, localName); - } - - @Override - public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException { - return xmlElementElement.getAttributeNodeNS(namespaceURI, localName); - } - - @Override - public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { - return xmlElementElement.setAttributeNodeNS(newAttr); - } - - @Override - public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException { - return xmlElementElement.getElementsByTagNameNS(namespaceURI, localName); - } - - @Override - public boolean hasAttribute(String name) { - return xmlElementElement.hasAttribute(name); - } - - @Override - public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException { - return xmlElementElement.hasAttributeNS(namespaceURI, localName); - } - - @Override - public TypeInfo getSchemaTypeInfo() { - return xmlElementElement.getSchemaTypeInfo(); - } - - @Override - public void setIdAttribute(String name, boolean isId) throws DOMException { - xmlElementElement.setIdAttribute(name, isId); - - } - - @Override - public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { - xmlElementElement.setIdAttributeNS(namespaceURI, localName, isId); - } - - @Override - public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException { - xmlElementElement.setIdAttributeNode(idAttr, isId); - return; - } - - -} \ No newline at end of file diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java deleted file mode 100644 index 6315ddff..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class XSDJavaType extends XSDElement { - StringBuffer pathSb; - StringBuffer definitionsSb; - StringBuffer pathParams; - - public XSDJavaType(Element javaTypeElement) { - super(javaTypeElement); - } -/* - public XSDJavaType(XSDElement javaTypeElement, StringBuffer pathSb, StringBuffer definitionsSb, - StringBuffer pathParams) { - super(javaTypeElement); - this.pathSb = pathSb; - this.definitionsSb = definitionsSb; - this.pathParams = pathParams; - } -*/ - public String getItemName() { - NodeList parentNodes = this.getElementsByTagName("java-attributes"); - if(parentNodes.getLength() == 0) - return null; - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(0)); - return xmlElementElement.getAttribute("name"); - } - - public String getArrayType() { - NodeList parentNodes = this.getElementsByTagName("java-attributes"); - if(parentNodes.getLength() == 0) - return null; - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(0)); - if ( xmlElementElement.hasAttribute("container-type") && xmlElementElement.getAttribute("container-type").equals("java.util.ArrayList")) { - return xmlElementElement.getAttribute("name"); - } - return null; - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java deleted file mode 100644 index f807bcb1..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java +++ /dev/null @@ -1,598 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.StringTokenizer; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.Vector; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.lang3.StringUtils; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.EdgeRuleQuery; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.nodes.NodeIngestor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; -import com.google.common.collect.Multimap; - - -public class YAMLfromOXM extends OxmFileProcessor { - private static final Logger logger = LoggerFactory.getLogger("YAMLfromOXM.class"); -// private static StringBuffer totalPathSbAccumulator = new StringBuffer(); - private static final String root = "../aai-schema/src/main/resources"; - private static final String autoGenRoot = "aai-schema/src/main/resources"; - private static final String generateTypeYAML = "yaml"; - private static final String normalStartDir = "aai-core"; - private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/aai_swagger_yaml"; - private StringBuilder inventoryDefSb = null; - - - private String basePath; - - public YAMLfromOXM(String basePath, SchemaVersions schemaVersions, NodeIngestor ni, EdgeIngestor ei){ - super(schemaVersions, ni,ei); - this.basePath = basePath; - } - public void setOxmVersion(File oxmFile, SchemaVersion v) { - super.setOxmVersion(oxmFile, v); - } - public void setXmlVersion(String xml, SchemaVersion v){ - super.setXmlVersion(xml, v); - } - - public void setVersion(SchemaVersion v) { - super.setVersion(v); - } - - @Override - public String getDocumentHeader() { - StringBuffer sb = new StringBuffer(); - sb.append("swagger: \"2.0\"\ninfo:\n "); - sb.append("description: |"); - if ( versionSupportsSwaggerDiff(v.toString())) { - sb.append("\n\n [Differences versus the previous schema version](" + "apidocs/aai_swagger_" + v.toString() + ".diff)"); - } - sb.append("\n\n Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n\n You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)\n\n Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n version: \"" + v.toString() +"\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n name: Apache 2.0\n url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n name:\n url:\n email:\n"); - sb.append("host:\nbasePath: " + basePath + "/" + v.toString() + "\n"); - sb.append("schemes:\n - https\npaths:\n"); - return sb.toString(); - } - - protected void init() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException { - super.init(); - } - - @Override - public String process() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException, EdgeRuleNotFoundException { - StringBuffer sb = new StringBuffer(); - StringBuffer pathSb = new StringBuffer(); - try { - init(); - } catch(Exception e) { - logger.error( "Error initializing " + this.getClass(),e); - throw e; - } - pathSb.append(getDocumentHeader()); - StringBuffer definitionsSb = new StringBuffer(); - Element elem; - String javaTypeName; - combinedJavaTypes = new HashMap(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - elem = (Element)javaTypeNodes.item(i); - javaTypeName = elem.getAttribute("name"); - if ( !"Inventory".equals(javaTypeName ) ) { - if ( generatedJavaType.containsKey(getXmlRootElementName(javaTypeName) ) ) { - continue; - } - // will combine all matching java-types - elem = getJavaTypeElementSwagger(javaTypeName ); - } - - XSDElement javaTypeElement = new XSDElement(elem); - if ( javaTypeName == null ) { - String msg = "Invalid OXM file: has no name attribute in " + oxmFile; - logger.error(msg); - throw new AAIException(msg); - } - namespaceFilter.add(getXmlRootElementName(javaTypeName)); - processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb, - definitionsSb, null, null, null, null, null, null); - } - sb.append(pathSb); - - sb.append(appendDefinitions()); - PutRelationPathSet prp = new PutRelationPathSet(v); - prp.generateRelations(ei); - return sb.toString(); - } - - public String appendDefinitions() { - return appendDefinitions(null); - } - - public String appendDefinitions(Set namespaceFilter) { - //append definitions - if ( inventoryDefSb != null ) { - javaTypeDefinitions.put("inventory", inventoryDefSb.toString()); - } - StringBuffer sb = new StringBuffer("definitions:\n"); - Map sortedJavaTypeDefinitions = new TreeMap(javaTypeDefinitions); - for (Map.Entry entry : sortedJavaTypeDefinitions.entrySet()) { -// logger.info("Key: "+entry.getKey()+"Value: "+ entry.getValue()); - if(namespaceFilter != null && entry.getKey().matches("service-capabilities")) { - for(String tally : namespaceFilter) { logger.debug("Marker: "+tally);} - } - if(namespaceFilter != null && (! namespaceFilter.contains(entry.getKey()))) { - continue; - } - logger.debug("Key: "+entry.getKey()+"Test: "+ (entry.getKey() == "relationship-dict")); - if(entry.getKey().matches("relationship-dict")) { - String jb=entry.getValue(); - logger.debug("Value: "+jb); - int ndx=jb.indexOf("related-to-property:"); - if(ndx > 0) { - jb=jb.substring(0, ndx); - jb=jb.replaceAll(" +$", ""); - } - logger.debug("Value-after: "+jb); - sb.append(jb); - continue; - } - sb.append(entry.getValue()); - } - - sb.append("patchDefinitions:\n"); - for (Map.Entry entry : sortedJavaTypeDefinitions.entrySet()) { - if(namespaceFilter != null && (! namespaceFilter.contains(entry.getKey()))) { - continue; - } - String jb=entry.getValue().replaceAll("/definitions/", "/patchDefinitions/"); - int ndx=jb.indexOf("relationship-list:"); - if(ndx > 0) { - jb=jb.substring(0, ndx); - jb=jb.replaceAll(" +$", ""); - } - int ndx1=jb.indexOf("resource-version:"); - logger.debug("Key: "+entry.getKey()+" index: " + ndx1); - logger.debug("Value: "+jb); - if(ndx1 > 0) { - jb=jb.substring(0, ndx1); - jb=jb.replaceAll(" +$", ""); - } - logger.debug("Value-after: "+jb); - sb.append(jb); - } - - sb.append("getDefinitions:\n"); - for (Map.Entry entry : sortedJavaTypeDefinitions.entrySet()) { - if(namespaceFilter != null && (! namespaceFilter.contains(entry.getKey()))) { - continue; - } - String jb=entry.getValue().replaceAll("/definitions/", "/getDefinitions/"); - sb.append(jb); - } - return sb.toString(); - } - - private String getDictionary(String resource ) { - StringBuffer dictSb = new StringBuffer(); - dictSb.append(" " + resource + ":\n"); - dictSb.append(" description: |\n"); - dictSb.append(" dictionary of " + resource + "\n" ); - dictSb.append(" type: object\n"); - dictSb.append(" properties:\n"); - dictSb.append(" " + resource + ":\n"); - dictSb.append(" type: array\n"); - dictSb.append(" items:\n"); - dictSb.append(" $ref: \"#/definitions/" + resource + "-dict\"\n"); - return dictSb.toString(); - } - - private String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement, - StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId, - String getItemName, StringBuffer pathParams, String validEdges) { - - String xmlRootElementName = getXMLRootElementName(javaTypeElement); - StringBuilder definitionsLocalSb = new StringBuilder(256); - - String useTag = null; - String useOpId = null; - logger.debug("tag="+tag); - if ( tag != null ) { - switch ( tag ) { - case "Network": - case "ServiceDesignAndCreation": - case "Business": - case "LicenseManagement": - case "CloudInfrastructure": - case "Common": - break; - default: - logger.debug("javaTypeName="+javaTypeName); - return null; - } - } - - if ( !javaTypeName.equals("Inventory") ) { - if ( javaTypeName.equals("AaiInternal")) - return null; - if ( opId == null ) - useOpId = javaTypeName; - else - useOpId = opId + javaTypeName; - if ( tag == null ) - useTag = javaTypeName; - } - path = xmlRootElementName.equals("inventory") ? "" : (path == null) ? "/" + xmlRootElementName : path + "/" + xmlRootElementName; - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - if ( getItemName != null) { - if ( getItemName.equals("array") ) - return javaType.getArrayType(); - else - return javaType.getItemName(); - } - - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - if ( parentNodes.getLength() == 0 ) { - logger.debug( "no java-attributes for java-type " + javaTypeName); - return ""; - } - - String pathDescriptionProperty = javaType.getPathDescriptionProperty(); - String container = javaType.getContainerProperty(); - Vector indexedProps = javaType.getIndexedProps(); - Vector containerProps = new Vector(); - if(container != null) { - logger.debug("javaTypeName " + javaTypeName + " container:" + container +" indexedProps:"+indexedProps); - } - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - - StringBuffer sbParameters = new StringBuffer(); - StringBuffer sbRequired = new StringBuffer(); - int requiredCnt = 0; - int propertyCnt = 0; - StringBuffer sbProperties = new StringBuffer(); - - if ( appliedPaths.containsKey(path)) - return null; - - StringTokenizer st = new StringTokenizer(path, "/"); - logger.debug("path: " + path + " st? " + st.toString()); - if ( st.countTokens() > 1 && getItemName == null ) { - logger.debug("appliedPaths: " + appliedPaths + " containsKey? " + appliedPaths.containsKey(path)); - appliedPaths.put(path, xmlRootElementName); - } - - Vector addTypeV = null; - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(i)); - if ( !xmlElementElement.getParentNode().isSameNode(parentElement)) - continue; - String elementDescription=xmlElementElement.getPathDescriptionProperty(); - if(getItemName == null) { - addTypeV = xmlElementElement.getAddTypes(v.toString()); - } - if ( "true".equals(xmlElementElement.getAttribute("xml-key"))) { - path += "/{" + xmlElementElement.getAttribute("name") + "}"; - } - logger.debug("path: " + path); - logger.debug( "xmlElementElement.getAttribute(required):"+xmlElementElement.getAttribute("required") ); - - if ( ("true").equals(xmlElementElement.getAttribute("required"))) { - if ( requiredCnt == 0 ) - sbRequired.append(" required:\n"); - ++requiredCnt; - if ( addTypeV == null || addTypeV.isEmpty()) { - sbRequired.append(" - " + xmlElementElement.getAttribute("name") + "\n"); - } else { - for ( int k = 0; k < addTypeV.size(); ++k ) { - sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n"); - } - } - } - - if ( "true".equals(xmlElementElement.getAttribute("xml-key")) ) { - sbParameters.append(xmlElementElement.getPathParamYAML(elementDescription)); - } - if ( indexedProps != null - && indexedProps.contains(xmlElementElement.getAttribute("name") ) ) { - containerProps.add(xmlElementElement.getQueryParamYAML()); - GetOperation.addContainerProps(container, containerProps); - } - if ( xmlElementElement.isStandardType()) { - sbProperties.append(xmlElementElement.getTypePropertyYAML()); - ++propertyCnt; - } - - StringBuffer newPathParams = new StringBuffer((pathParams == null ? "" : pathParams.toString())+sbParameters.toString()); - for ( int k = 0; addTypeV != null && k < addTypeV.size(); ++k ) { - String addType = addTypeV.elementAt(k); - namespaceFilter.add(getXmlRootElementName(addType)); - logger.debug("addType: "+ addType); - - if ( opId == null || !opId.contains(addType)) { - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null, - newPathParams, validEdges); - } - // need item name of array - String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - "array", null, null ); - - if ( itemName != null ) { - if ( addType.equals("AaiInternal") ) { - logger.debug( "addType AaiInternal, skip properties"); - - } else if ( getItemName == null) { - ++propertyCnt; - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items:\n"); - sbProperties.append(" $ref: \"#/definitions/" + (itemName == "" ? "inventory-item-data" : itemName) + "\"\n"); - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - } - } else { - if ( ("java.util.ArrayList").equals(xmlElementElement.getAttribute("container-type"))) { - // need properties for getXmlRootElementName(addType) - namespaceFilter.add(getXmlRootElementName(addType)); - newPathParams = new StringBuffer((pathParams == null ? "" : pathParams.toString())+sbParameters.toString()); - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - null, newPathParams, validEdges ); - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items: \n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - - } else { - //Make sure certain types added to the filter don't appear - if(nodeFilter.contains(getXmlRootElementName(addType))) { - ; - } else { - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: object\n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } - } - if ( StringUtils.isNotEmpty(elementDescription) ) - sbProperties.append(" description: " + elementDescription + "\n"); - ++propertyCnt; - } - } - } - - if ( sbParameters.toString().length() > 0 ) { - if ( pathParams == null ) - pathParams = new StringBuffer(); - pathParams.append(sbParameters); - } - GetOperation get = new GetOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString()); - pathSb.append(get.toString()); - logger.debug("opId vs useOpId:"+opId+" vs "+useOpId+" PathParams="+pathParams); - // add PUT - PutOperation put = new PutOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString(), this.v); - pathSb.append(put.toString()); - // add PATCH - PatchOperation patch = new PatchOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString()); - pathSb.append(patch.toString()); - // add DELETE - DeleteOperation del = new DeleteOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString()); - pathSb.append(del.toString()); - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - logger.debug("xmlRootElementName(1)="+xmlRootElementName); - return null; - } - - boolean processingInventoryDef = false; - String dict = null; - if ( xmlRootElementName.equals("inventory")) { - // inventory properties for each oxm to be concatenated - processingInventoryDef = true; - if ( inventoryDefSb == null ) { - inventoryDefSb = new StringBuilder(); - definitionsSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" properties:\n"); - } - } else if ( xmlRootElementName.equals("relationship")) { - definitionsSb.append(" " + "relationship-dict" + ":\n"); - definitionsLocalSb.append(" " + "relationship-dict" + ":\n"); - dict = getDictionary(xmlRootElementName); - } else { - definitionsSb.append(" " + xmlRootElementName + ":\n"); - definitionsLocalSb.append(" " + xmlRootElementName + ":\n"); - } -// Collection edges = edgeRuleSet.getEdgeRules(xmlRootElementName ); - DeleteFootnoteSet footnotes = new DeleteFootnoteSet(xmlRootElementName); - StringBuffer sbEdge = new StringBuffer(); - LinkedHashSet preventDelete = new LinkedHashSet(); - String prevent=null; - String nodeCaption = new String(" ###### Related Nodes\n"); - try { - EdgeRuleQuery q = new EdgeRuleQuery.Builder(xmlRootElementName).version(v).fromOnly().build(); - Multimap results = ei.getRules(q); - SortedSet ss=new TreeSet(results.keySet()); - sbEdge.append(nodeCaption); - nodeCaption=""; - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ logger.info(new String(new StringBuffer(" - TO ").append(i.getTo()).append(i.getDirection().toString()).append(i.getContains())));} ); - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ sbEdge.append(" - TO "+i.getTo()); EdgeDescription ed = new EdgeDescription(i); String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName); sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)+footnote+"\n"); if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);} ); - results.get(key).stream().filter((i) -> (i.getFrom().equals(xmlRootElementName) && (! i.isPrivateEdge() && i.getPreventDelete().equals("OUT")))).forEach((i) ->{ preventDelete.add(i.getTo().toUpperCase());} ); - } - } catch(Exception e) { - logger.debug("xmlRootElementName: "+xmlRootElementName+" from edge exception\n", e); - } - try { - EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(xmlRootElementName).version(v).toOnly().build(); - Multimap results = ei.getRules(q1); - SortedSet ss=new TreeSet(results.keySet()); - sbEdge.append(nodeCaption); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ sbEdge.append(" - FROM "+i.getFrom()); EdgeDescription ed = new EdgeDescription(i); String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName); sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)+footnote+"\n"); if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);} ); - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge()))).forEach((i) ->{ logger.info(new String(new StringBuffer(" - FROM ").append(i.getFrom()).append(i.getDirection().toString()).append(i.getContains())));} ); - results.get(key).stream().filter((i) -> (i.getTo().equals(xmlRootElementName) && (! i.isPrivateEdge() && i.getPreventDelete().equals("IN")))).forEach((i) ->{ preventDelete.add(i.getFrom().toUpperCase());} ); - } - } catch(Exception e) { - logger.debug("xmlRootElementName: "+xmlRootElementName+" to edge exception\n", e); - } - if(preventDelete.size() > 0) { - prevent = xmlRootElementName.toUpperCase()+" cannot be deleted if related to "+String.join(",",preventDelete); - logger.debug(prevent); - } - - if(StringUtils.isNotEmpty(prevent)) { - footnotes.add(prevent); - } - if(footnotes.footnotes.size() > 0) { - sbEdge.append(footnotes.toString()); - } - validEdges = sbEdge.toString(); - - // Handle description property. Might have a description OR valid edges OR both OR neither. - // Only put a description: tag if there is at least one. - if (StringUtils.isNotEmpty(pathDescriptionProperty) || StringUtils.isNotEmpty(validEdges) ) { - definitionsSb.append(" description: |\n"); - definitionsLocalSb.append(" description: |\n"); - - if ( pathDescriptionProperty != null ) { - definitionsSb.append(" " + pathDescriptionProperty + "\n" ); - definitionsLocalSb.append(" " + pathDescriptionProperty + "\n" ); - } - definitionsSb.append(validEdges); - definitionsLocalSb.append(validEdges); - } - - if ( requiredCnt > 0 ) { - definitionsSb.append(sbRequired); - definitionsLocalSb.append(sbRequired); - } - - if ( propertyCnt > 0 ) { - definitionsSb.append(" properties:\n"); - definitionsSb.append(sbProperties); - if ( !processingInventoryDef) { - definitionsLocalSb.append(" properties:\n"); - } - definitionsLocalSb.append(sbProperties); - } - try { - namespaceFilter.add(xmlRootElementName); - if ( xmlRootElementName.equals("inventory") ) { - //will add to javaTypeDefinitions at end - inventoryDefSb.append(definitionsLocalSb.toString()); - } else if ( xmlRootElementName.equals("relationship") ){ - javaTypeDefinitions.put(xmlRootElementName, dict); - javaTypeDefinitions.put(xmlRootElementName+ "-dict", definitionsLocalSb.toString()); - } else { - javaTypeDefinitions.put(xmlRootElementName, definitionsLocalSb.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - logger.error("Exception adding in javaTypeDefinitions",e); - } - if ( xmlRootElementName.equals("inventory") ) { - logger.trace("skip xmlRootElementName(2)="+xmlRootElementName); - return null; - } - generatedJavaType.put(xmlRootElementName, null); -/* - if( validTag(javaTypeName) && javaTypeName == useTag && tag == null) { - String nameSpaceResult = getDocumentHeader()+pathSb.toString()+appendDefinitions(namespaceFilter); - writeYAMLfile(javaTypeName, nameSpaceResult); - totalPathSbAccumulator.append(pathSb); - pathSb.delete(0, pathSb.length()); - namespaceFilter.clear(); - } -*/ - logger.trace("xmlRootElementName(2)="+xmlRootElementName); - return null; - } - - private void writeYAMLfile(String outfileName, String fileContent) { - outfileName = (StringUtils.isEmpty(outfileName)) ? "aai_swagger" : outfileName; - outfileName = (outfileName.lastIndexOf(File.separator) == -1) ? yaml_dir + File.separator +outfileName+"_" + v.toString() + "." + generateTypeYAML : outfileName; - File outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(parentDir != null && ! parentDir.exists()) - parentDir.mkdirs(); - try { - outfile.createNewFile(); - } catch (IOException e) { - logger.error( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - try(BufferedWriter bw = Files.newBufferedWriter(path, charset)){ - bw.write(fileContent); - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName); - e.printStackTrace(); - } - } - - public boolean validTag(String tag) { - if(tag != null) { - switch ( tag ) { - case "Network": -// case "Search": -// case "Actions": - case "ServiceDesignAndCreation": - case "Business": - case "LicenseManagement": - case "CloudInfrastructure": - case "Common": - return true; - } - } - return false; - } - -} diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java b/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java deleted file mode 100644 index cc422d95..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java +++ /dev/null @@ -1,318 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.swagger; - -import java.util.List; -import java.util.Map; - -public class Api { - - private String path; - - private List httpMethods; - - private String tag; - - public List getHttpMethods() { - return httpMethods; - } - - public void setHttpMethods(List httpMethods) { - this.httpMethods = httpMethods; - } - - public String getTag(){ - - if(this.tag != null){ - return this.tag; - } - - if(this.httpMethods != null){ - if(this.httpMethods.size() != 0){ - if(this.httpMethods.get(0).getTags() != null){ - if(this.httpMethods.get(0).getTags().size() != 0){ - this.tag = this.httpMethods.get(0).getTags().get(0); - } - } - } - } - - if(this.tag == null){ - this.tag = ""; - } - - return this.tag; - } - - @Override - public String toString() { - return "Api{" + - "path='" + path + '\'' + - ", httpMethods=" + httpMethods + - '}'; - } - - public void setPath(String path) { - this.path = path; - } - - public String getPath() { - return this.path; - } - - public String getOperation(){ - - if(this.path != null){ - return this.path.replaceAll("[^a-zA-Z0-9\\-]", "-") + "-"; - } - - return ""; - } - - public static class HttpVerb { - - private List tags; - - private String type; - - private String summary; - - private String operationId; - - private List consumes; - - private boolean consumerEnabled; - - private List produces; - - private List responses; - - private List> parameters; - - private Map bodyParameters; - - private boolean bodyParametersEnabled; - - private boolean parametersEnabled; - - private String schemaLink; - - private String schemaType; - - private boolean hasReturnSchema; - - private String returnSchemaLink; - - private String returnSchemaObject; - - public void setConsumerEnabled(boolean consumerEnabled){ - this.consumerEnabled = consumerEnabled; - } - - public boolean isConsumerEnabled() { - return consumerEnabled; - } - - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getSummary() { - return summary; - } - - public void setSummary(String summary) { - this.summary = summary; - } - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public List getConsumes() { - return consumes; - } - - public void setConsumes(List consumes) { - this.consumes = consumes; - } - - public List getProduces() { - return produces; - } - - public void setProduces(List produces) { - this.produces = produces; - } - - public List getResponses() { - return responses; - } - - public void setResponses(List responses) { - this.responses = responses; - } - - public List> getParameters() { - return parameters; - } - - public void setParameters(List> parameters) { - this.parameters = parameters; - } - - @Override - public String toString() { - return "HttpVerb{" + - "tags=" + tags + - ", type='" + type + '\'' + - ", summary='" + summary + '\'' + - ", operationId='" + operationId + '\'' + - ", consumes=" + consumes + - ", produces=" + produces + - ", responses=" + responses + - ", parameters=" + parameters + - '}'; - } - - public void setParametersEnabled(boolean b) { - this.parametersEnabled = b; - } - - public boolean isParametersEnabled() { - return parametersEnabled; - } - - public boolean isBodyParametersEnabled() { - return bodyParametersEnabled; - } - public boolean isOpNotPatch() { - return type.equalsIgnoreCase("patch") ? false : true; - } - - public void setBodyParametersEnabled(boolean bodyParametersEnabled) { - this.bodyParametersEnabled = bodyParametersEnabled; - } - - public Map getBodyParameters() { - return bodyParameters; - } - - public void setBodyParameters(Map bodyParameters) { - this.bodyParameters = bodyParameters; - } - - public String getSchemaLink() { - return schemaLink; - } - - public void setSchemaLink(String schemaLink) { - this.schemaLink = schemaLink; - } - - public String getSchemaType() { - return schemaType; - } - - public void setSchemaType(String schemaType) { - this.schemaType = schemaType; - } - - public boolean isHasReturnSchema() { - return hasReturnSchema; - } - - public void setHasReturnSchema(boolean hasReturnSchema) { - this.hasReturnSchema = hasReturnSchema; - } - - public String getReturnSchemaLink() { - return returnSchemaLink; - } - - public void setReturnSchemaLink(String returnSchemaLink) { - this.returnSchemaLink = returnSchemaLink; - } - - public String getReturnSchemaObject() { - return returnSchemaObject; - } - - public void setReturnSchemaObject(String returnSchemaObject) { - this.returnSchemaObject = returnSchemaObject; - } - - public static class Response { - - private String responseCode; - - private String description; - - private String version; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "Response{" + - "responseCode='" + responseCode + '\'' + - ", description='" + description + '\'' + - '}'; - } - - public void setVersion(String version) { - this.version = version; - } - } - - } - -} diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java b/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java deleted file mode 100644 index 5e8a5ec6..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java +++ /dev/null @@ -1,198 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.swagger; - -import java.util.List; - -public class Definition { - - private String definitionName; - - private String definitionDescription; - - private List propertyList; - - private List schemaPropertyList; - - private List regularPropertyList; - - private boolean hasDescription; - - public String getDefinitionName() { - return definitionName; - } - - public void setDefinitionName(String definitionName) { - this.definitionName = definitionName; - } - - public List getPropertyList() { - return propertyList; - } - - public void setPropertyList(List propertyList) { - this.propertyList = propertyList; - } - - public String getDefinitionDescription() { - return definitionDescription; - } - - public void setDefinitionDescription(String definitionDescription) { - this.definitionDescription = definitionDescription; - } - - @Override - public String toString() { - return "Definition{" + - "definitionName='" + definitionName + '\'' + - ", definitionDescription='" + definitionDescription + '\'' + - ", propertyList=" + propertyList + - '}'; - } - - public boolean isHasDescription() { - return hasDescription; - } - - public void setHasDescription(boolean hasDescription) { - this.hasDescription = hasDescription; - } - - public List getSchemaPropertyList() { - return schemaPropertyList; - } - - public void setSchemaPropertyList(List schemaPropertyList) { - this.schemaPropertyList = schemaPropertyList; - } - - public List getRegularPropertyList() { - return regularPropertyList; - } - - public void setRegularPropertyList(List regularPropertyList) { - this.regularPropertyList = regularPropertyList; - } - - public static class Property { - - private String propertyName; - - private String propertyDescription; - - private boolean hasPropertyDescription; - - private String propertyType; - - private boolean hasType; - - private String propertyReference; - - private String propertyReferenceObjectName; - - private boolean isRequired; - - private boolean hasPropertyReference; - - public Property(){} - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public String getPropertyType() { - return propertyType; - } - - public void setPropertyType(String propertyType) { - this.propertyType = propertyType; - } - - public String getPropertyReference() { - return propertyReference; - } - - public void setPropertyReference(String propertyReference) { - this.propertyReference = propertyReference; - } - - @Override - public String toString() { - return "Property{" + - "propertyName='" + propertyName + '\'' + - ", propertyType='" + propertyType + '\'' + - ", propertyReference='" + propertyReference + '\'' + - '}'; - } - - public boolean isHasType() { - return hasType; - } - - public void setHasType(boolean hasType) { - this.hasType = hasType; - } - - public boolean isRequired() { - return isRequired; - } - - public void setRequired(boolean required) { - isRequired = required; - } - - public boolean isHasPropertyReference() { - return hasPropertyReference; - } - - public void setHasPropertyReference(boolean hasPropertyReference) { - this.hasPropertyReference = hasPropertyReference; - } - - public String getPropertyReferenceObjectName() { - return propertyReferenceObjectName; - } - - public void setPropertyReferenceObjectName(String propertyReferenceObjectName) { - this.propertyReferenceObjectName = propertyReferenceObjectName; - } - - public String getPropertyDescription() { - return propertyDescription; - } - - public void setPropertyDescription(String propertyDescription) { - this.propertyDescription = propertyDescription; - } - - public boolean isHasPropertyDescription() { - return hasPropertyDescription; - } - - public void setHasPropertyDescription(boolean hasPropertyDescription) { - this.hasPropertyDescription = hasPropertyDescription; - } - } -} diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java b/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java deleted file mode 100644 index 21e264a1..00000000 --- a/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java +++ /dev/null @@ -1,488 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.swagger; - -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import org.onap.aai.setup.SchemaVersions; - -import java.io.*; -import java.util.*; -import java.util.stream.Collectors; - -public class GenerateSwagger { - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final String DEFAULT_WIKI = ""; - - public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - //if the program is run from aai-common, use this directory as default" - public static final String ALT_SCHEMA_DIR = "aai-schema"; - //used to check to see if program is run from aai-core - public static final String DEFAULT_RUN_DIR = "aai-core"; - - public static SchemaVersions schemaVersions; - - public SchemaVersions getSchemaVersions() { - return schemaVersions; - } - - - - public static void main(String[] args) throws IOException, TemplateException { - - - - - // SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class); - String CURRENT_VERSION = schemaVersions.getDefaultVersion().toString(); - String schemaDir = System.getProperty("aai.schema.dir"); - String versionToGenerate = System.getProperty("aai.generate.version"); - String wikiLink = System.getProperty("aai.wiki.link"); - String release = System.getProperty("aai.release", "onap"); - - if(schemaDir == null){ - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { - System.out.println("Warning: Schema directory is not set so using default schema dir: " + ALT_SCHEMA_DIR); - schemaDir = ALT_SCHEMA_DIR; - } - else { - System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR); - schemaDir = DEFAULT_SCHEMA_DIR; - } - } - - if(versionToGenerate == null){ - System.out.println("Warning: Version to generate is not set so using default versionToGenerate " + CURRENT_VERSION); - versionToGenerate = CURRENT_VERSION; - } - - if(wikiLink == null){ - System.out.println("Warning: aai.wiki.link property is not set so using default"); - wikiLink = DEFAULT_WIKI; - } - - String yamlFile = schemaDir + "/src/main/resources/" + release + "/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; - File swaggerYamlFile = new File(yamlFile); - - if(!swaggerYamlFile.exists()){ - System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile); - System.exit(1); - } - - Yaml yaml = new Yaml(new SafeConstructor()); - Map swaggerMap = null; - - try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){ - swaggerMap = (Map) yaml.load(reader); - } catch(Exception ex){ - ex.printStackTrace(); - } - - if(null == swaggerMap) { - throw new IOException(); - } - - Map map = (Map) swaggerMap.get("paths"); - Map schemaDefinitionmap = (Map) swaggerMap.get("definitions"); - Map infoMap = (Map) swaggerMap.get("info"); - Map> tagMap = new LinkedHashMap<>(); - - List apis = convertToApi(map); - apis.forEach((api) -> { - if(!tagMap.containsKey(api.getTag())){ - List newApis = new ArrayList<>(); - newApis.add(api); - tagMap.put(api.getTag(), newApis); - } else { - tagMap.get(api.getTag()).add(api); - } - }); - - Map> sortedTagMap = new TreeMap<>(tagMap); - sortedTagMap.forEach((key, value) -> { - value.sort(Comparator.comparing(Api::getPath)); - }); - - Map resultMap = new HashMap<>(); - - List definitionList = convertToDefinition(schemaDefinitionmap); - - definitionList = definitionList - .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList()); - - resultMap.put("aaiApis", tagMap); - resultMap.put("sortedAaiApis", sortedTagMap); - resultMap.put("wikiLink", wikiLink); - resultMap.put("definitions", definitionList); - resultMap.put("version", versionToGenerate); - if (infoMap.containsKey("description")) { - String infoDescription = infoMap.get("description").toString(); - - infoDescription = Arrays.stream(infoDescription.split("\n")) - .map(line -> { - line = line.trim(); - String hyperLink = ""; - if(line.trim().contains("Differences versus")) { - return String.format(""); - } - if(line.trim().contains("https://")){ - int startIndex = line.indexOf("https://"); - int endIndex = line.lastIndexOf("/"); - hyperLink = line.substring(startIndex, endIndex); - return String.format("%s
", hyperLink, line); - } - return String.format("%s
", line); - }) - - .collect(Collectors.joining(LINE_SEPARATOR)); - - resultMap.put("description", infoDescription); - } - - Configuration configuration = new Configuration(); - configuration.setClassForTemplateLoading(Api.class, "/"); - String resourcePath = "src/main/resources"; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { - configuration.setDirectoryForTemplateLoading(new File(DEFAULT_RUN_DIR + "/" + resourcePath)); - } - else { - configuration.setDirectoryForTemplateLoading(new File(resourcePath)); - } - Template template = configuration.getTemplate("swagger.html.ftl"); - - String outputDirStr = schemaDir + "/src/main/resources/" + release + "/aai_swagger_html"; - - File outputDir = new File(outputDirStr); - - if(!outputDir.exists()){ - boolean resp = outputDir.mkdir(); - if(!resp){ - System.err.println("Unable to create the directory: " + outputDirStr); - System.exit(1); - } - } else if(outputDir.isFile()){ - System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists"); - System.exit(1); - } - - Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); - template.process(resultMap, file); - } - - public static List convertToApi(Map pathMap){ - - if(pathMap == null) - throw new IllegalArgumentException(); - - List apis = new ArrayList<>(); - - pathMap.forEach( (pathKey, pathValue) -> { - - Api api = new Api(); - Map httpVerbMap = (Map) pathValue; - List httpVerbs = new ArrayList<>(); - - api.setPath(pathKey); - - httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> { - - Api.HttpVerb httpVerb = new Api.HttpVerb(); - - Map httpVerbValueMap = (Map)httpVerbValue; - - httpVerb.setType(httpVerbKey); - - if(httpVerbValueMap.containsKey("tags")){ - httpVerb.setTags((List)httpVerbValueMap.get("tags")); - } - - if(httpVerbValueMap.containsKey("summary")){ - httpVerb.setSummary((String)httpVerbValueMap.get("summary")); - } - - if(httpVerbValueMap.containsKey("operationId")){ - httpVerb.setOperationId((String)httpVerbValueMap.get("operationId")); - } - - if(httpVerbValueMap.containsKey("consumes")){ - httpVerb.setConsumes((List)httpVerbValueMap.get("consumes")); - if(httpVerb.getConsumes() != null){ - httpVerb.setConsumerEnabled(true); - } - } - - if(httpVerbValueMap.containsKey("produces")){ - httpVerb.setProduces((List)httpVerbValueMap.get("produces")); - } - - if(httpVerbValueMap.containsKey("parameters")){ - List> parameters = (List>) httpVerbValueMap.get("parameters"); - List> requestParameters = parameters - .stream() - .filter((parameter) -> !parameter.get("name").equals("body")) - .collect(Collectors.toList()); - httpVerb.setParameters(requestParameters); - if(httpVerb.getParameters() != null){ - httpVerb.setParametersEnabled(true); - } - - List> requestBodyList = parameters - .stream() - .filter((parameter) -> parameter.get("name").equals("body")) - .collect(Collectors.toList()); - - Map requestBody = null; - - if(requestBodyList != null && requestBodyList.size() == 1){ - requestBody = requestBodyList.get(0); - for(String key : requestBody.keySet()) { - //Filter out all the relationship links that appear in the YAML - if(key.equals("description")) { - String reqBody=(String)requestBody.get(key); - if(reqBody.replaceAll("\\[.*.json\\)", "") != reqBody) { - requestBody.put(key, reqBody.replaceAll("\\[.*.json\\)", "")); - } - } - //Filter out all the patchDefinition links that appear in the YAML - if(key.equals("schema")) { - LinkedHashMap reqBody = (LinkedHashMap)requestBody.get(key); - String schema=reqBody.get("$ref"); - String schemaNopatch = schema.replace("patchDefinitions", "definitions"); - - if(! schema.equals(schemaNopatch)) { - reqBody.put("$ref", schemaNopatch); - requestBody.put(key, reqBody); - } - } - } - httpVerb.setBodyParametersEnabled(true); - httpVerb.setBodyParameters(requestBody); - - if(requestBody != null && requestBody.containsKey("schema")){ - Map schemaMap = (Map)requestBody.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setSchemaLink(schemaLink); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setSchemaType(schemaLink.substring(retCode)); - } - } - } - } - } - - if(httpVerbValueMap.containsKey("responses")){ - - List responses = new ArrayList(); - - Map responsesMap = (Map) httpVerbValueMap.get("responses"); - - responsesMap - .entrySet() - .stream() - .filter((res) -> !"default".equalsIgnoreCase(res.getKey())) - .forEach((responseMap) -> { - - Map responseValueMap = (Map)responseMap.getValue(); - - Api.HttpVerb.Response response = new Api.HttpVerb.Response(); - - response.setResponseCode(responseMap.getKey()); - response.setDescription((String) responseValueMap.get("description")); - response.setVersion((String) responseValueMap.get("version")); - - if(responseValueMap != null && responseValueMap.containsKey("schema")){ - Map schemaMap = (Map)responseValueMap.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setHasReturnSchema(true); - //Filter out all the getDefinition links that appear in the YAML - httpVerb.setReturnSchemaLink(schemaLink.replace("getDefinitions", "definitions")); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setReturnSchemaObject(schemaLink.substring(retCode)); - } - } - } - - responses.add(response); - } - ); - - httpVerb.setResponses(responses); - } - - httpVerbs.add(httpVerb); - }); - - api.setHttpMethods(httpVerbs); - apis.add(api); - }); - - return apis; - } - - public static List convertToDefinition(Map definitionMap) { - - if(definitionMap == null) - throw new IllegalArgumentException(); - - List defintionsList = new ArrayList<>(); - - definitionMap - .entrySet() - .forEach((entry) -> { - - Definition definition = new Definition(); - String key = entry.getKey(); - Map valueMap = (Map) entry.getValue(); - - definition.setDefinitionName(key); - - if(valueMap.containsKey("description")){ - String description = valueMap.get("description").toString(); - description = formatDescription(description); - definition.setDefinitionDescription(description); - definition.setHasDescription(true); - } - - List definitionProperties = new ArrayList<>(); - - List requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List) valueMap.get("required"); - - Set requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet()); - - valueMap - .entrySet() - .stream() - .filter( (e) -> "properties".equals(e.getKey())) - .forEach((propertyEntries) -> { - Map propertyRealEntries = (Map) propertyEntries.getValue(); - propertyRealEntries - .entrySet() - .forEach((propertyEntry) -> { - Definition.Property definitionProperty = new Definition.Property(); - String propertyKey = propertyEntry.getKey(); - if(requiredPropsSet.contains(propertyKey)){ - definitionProperty.setRequired(true); - } - definitionProperty.setPropertyName(propertyKey); - Map definitionPropertyMap = (Map) propertyEntry.getValue(); - - if(definitionPropertyMap.containsKey("description")){ - definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString()); - definitionProperty.setHasPropertyDescription(true); - } - if(definitionPropertyMap.containsKey("type")){ - String type = definitionPropertyMap.get("type").toString(); - definitionProperty.setPropertyType(type); - definitionProperty.setHasType(true); - if ("array".equals(type)) { - definitionProperty.setPropertyType("object[]"); - if(!definitionPropertyMap.containsKey("items")){ - throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey()); - } else { - Map itemMap = (Map) definitionPropertyMap.get("items"); - if(itemMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = itemMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } else { - if(definitionPropertyMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = definitionPropertyMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } - definitionProperties.add(definitionProperty); - }); - }); - - definition.setPropertyList(definitionProperties); - - List schemaProperties = definitionProperties. - stream() - .filter((o) -> o.isHasPropertyReference()) - .collect(Collectors.toList()); - - List regularProperties = definitionProperties. - stream() - .filter((o) -> !o.isHasPropertyReference()) - .collect(Collectors.toList()); - - definition.setRegularPropertyList(regularProperties); - definition.setSchemaPropertyList(schemaProperties); - - defintionsList.add(definition); - }); - return defintionsList; - } - - public static String formatDescription(String description){ - - description = Arrays.stream(description.split("\n")) - .map((line) -> { - line = line.trim(); - if(line.contains("######")){ - line = line.replaceAll("#", ""); - line = line.trim(); - String headerId = line.toLowerCase().replaceAll("\\s", "-"); - - if(line.contains("Related Nodes")){ - return String.format("
%s
%s
    ", headerId, line, LINE_SEPARATOR); - } else { - return String.format("
    %s
    ", headerId, line); - } - } else if(line.startsWith("-")){ - line = line.replaceFirst("-", ""); - line = line.trim(); - return String.format("
  • %s
  • ", line); - } else { - return String.format("

    %s

    ", line); - } - }) - .collect(Collectors.joining(LINE_SEPARATOR)); - - if(description.contains("
      ")){ - description = description + "
    "; - } - - return description; - } - -} - diff --git a/aai-core/src/main/resources/swagger.html.ftl b/aai-core/src/main/resources/swagger.html.ftl deleted file mode 100644 index 1a2827f8..00000000 --- a/aai-core/src/main/resources/swagger.html.ftl +++ /dev/null @@ -1,241 +0,0 @@ -<#-- - - ============LICENSE_START======================================================= - org.onap.aai - ================================================================================ - Copyright © 2017-18 AT&T Intellectual Property. All rights reserved. - Copyright © 2018 Huawei Technologies (Australia) Pty Ltd. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - - ECOMP is a trademark and service mark of AT&T Intellectual Property. - ---> - - - - - - - Active and Available Inventory REST API. - - -
    -

    Active and Available Inventory REST API.

    -

    Version: ${version}

    -

    ${description}

    -

    - -
    - Schemes: - https -
    - -

    Summary

    -
      - <#list aaiApis?keys as key> -
    1. Tag: ${key} - -
    2. Paths -
    3. Schema definitions -
    - - <#list aaiApis?keys as key> -

    Tag: ${key}

    - - - - - - <#list aaiApis[key] as api> - <#list api.getHttpMethods() as httpVerb> - - - - - - -
    OperationDescription
    - ${httpVerb.getType()?upper_case} ${api.getPath()}

    ${httpVerb.getSummary()}

    - - -

    Paths

    - <#list sortedAaiApis?keys as key> - <#list sortedAaiApis[key] as api> - <#list api.getHttpMethods() as httpVerb> - -
    -
    -
    ${httpVerb.getSummary()}
    -

    ${httpVerb.getType()?upper_case} - ${api.getPath()}

    - Tags: ${api.getTag()} -
    -
    -
    -

    ${httpVerb.getSummary()}

    -
    - <#if httpVerb.isConsumerEnabled()> -
    -

    application/json application/xml

    - <#if httpVerb.isBodyParametersEnabled()> -
    -
    -

    ${httpVerb.getBodyParameters()["description"]}

    -
    -
    - -
    - - <#if httpVerb.isParametersEnabled()> -
    - - - - - - - - - - <#list httpVerb.getParameters() as param> - - - - - - - - -
    ${param["name"]} - <#if param['description']??> -

    ${param["description"]}

    - -
    ${param["in"]} - <#if param['type']??> - ${param["type"]} - - - - <#if param['required']> - - -
    - - -
    -

    application/json application/xml

    -
    - <#list httpVerb.getResponses() as response> -
    - ${response.getResponseCode()} OK -
    -
    -
    -

    successful operation

    -
    -
    - <#if httpVerb.isHasReturnSchema()> - - -
    -
    - -
    default
    -
    -
    -

    Response codes found in response codes.

    -
    -
    -
    -
    -
    -
    -
    - - - - - -

    Schema definitions

    - <#list definitions as definition> -
    -

    - ${definition.getDefinitionName()}: - object - -

    -
    - <#if definition.isHasDescription()> -
    - ${definition.getDefinitionDescription()} -
    - -
    - <#list definition.getRegularPropertyList() as definitionProperty> -
    - ${definitionProperty.getPropertyName()}: - <#if definitionProperty.isHasType()> - ${definitionProperty.getPropertyType()} - - - <#if definitionProperty.isRequired()> - - -
    -
    - <#if definitionProperty.isHasPropertyDescription()> -

    ${definitionProperty.getPropertyDescription()}

    - -
    -
    - - <#list definition.getSchemaPropertyList() as definitionProperty> -
    - ${definitionProperty.getPropertyName()}: - <#if definitionProperty.isHasType()> - ${definitionProperty.getPropertyType()} - - - <#if definitionProperty.isRequired()> - - -
    -
    - -
    -
    - - -
    - - diff --git a/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java b/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java deleted file mode 100644 index 00bbae49..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -import java.io.BufferedWriter; -import java.io.FileWriter; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.SwaggerGenerationConfiguration; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.testutils.TestUtilConfigTranslatorforBusiness; - -import org.onap.aai.AAISetup; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.util.genxsd.HTMLfromOXM; -import org.onap.aai.util.genxsd.HTMLfromOXMTest; -import org.onap.aai.util.genxsd.XSDElementTest; -import org.onap.aai.util.genxsd.YAMLfromOXM; -import org.onap.aai.util.genxsd.YAMLfromOXMTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - ConfigConfiguration.class, - TestUtilConfigTranslatorforBusiness.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai" -}) -public class GenerateXsdTest { - private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - - @Autowired - YAMLfromOXM yamlFromOxm; - - @Autowired - HTMLfromOXM htmlFromOxm; - - @Autowired - SchemaVersions schemaVersions; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.getTestXML(); - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(YAMLfromOXMTest.EdgeDefs()); - bw1.close(); - - } - - @Before - public void setUp() throws Exception { - //PowerMockito.mockStatic(GenerateXsd.class); - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.getTestXML(); -// logger.info(testXML); - } - - @Test - public void test_generateSwaggerFromOxmFile( ) { - - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat(fileContent, is(new YAMLfromOXMTest().YAMLresult())); - } - - @Test - public void test_generateXSDFromOxmFile( ) { - - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } -// logger.debug(fileContent); - assertThat(fileContent, is(new HTMLfromOXMTest().HTMLresult())); - } - - @Test - public void testGetAPIVersion() { - GenerateXsd.apiVersion = schemaVersions.getAppRootVersion().toString(); - assertThat(GenerateXsd.getAPIVersion(),is("v11")); - } - - @Test - public void testGetYamlDir() { - assertThat(GenerateXsd.getYamlDir(),is("aai-schema/src/main/resources/onap/aai_swagger_yaml")); - } - - @Test - public void testGetResponsesUrl() { - assertNull(GenerateXsd.getResponsesUrl()); - } -} - diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java deleted file mode 100644 index 633d7891..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import java.util.Arrays; -import java.util.Collection; - -import org.mockito.runners.MockitoJUnitRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.CoreMatchers.is; -import org.mockito.BDDMockito; -import org.mockito.InjectMocks; -import org.hamcrest.Matcher; -import org.junit.runners.*; -import org.junit.runners.Parameterized.Parameters; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWith(Parameterized.class) -public class DeleteFootnoteSetTest { - String targetNode; - String flavor; - String result; - DeleteFootnoteSet footnotes = null; - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"vserver","(1)", "\n -(1) IF this VSERVER node is deleted, this FROM node is DELETED also\n"}, - {"ctag-pool","(2)", "\n -(2) IF this CTAG-POOL node is deleted, this TO node is DELETED also\n"}, - {"pserver","(3)", "\n -(3) IF this FROM node is deleted, this PSERVER is DELETED also\n"}, - {"oam-network","(4)", "\n -(4) IF this TO node is deleted, this OAM-NETWORK is DELETED also\n"}, - {"dvs-switch","(1)", "\n -(1) IF this DVS-SWITCH node is deleted, this FROM node is DELETED also\n"}, - {"availability-zone","(3)", "\n -(3) IF this FROM node is deleted, this AVAILABILITY-ZONE is DELETED also\n"} - }; - return (Arrays.asList(inputs)); - } - - public DeleteFootnoteSetTest(String targetNode, String flavor, String result) { - super(); - this.targetNode = targetNode; - this.flavor = flavor; - this.result=result; - } - - @Before - public void setUp() throws Exception { - footnotes = new DeleteFootnoteSet(this.targetNode); - } - - @Test - public void testDeleteFootnoteSet() { - assertThat(footnotes.targetNode, is(this.targetNode)); - } - - @Test - public void testAdd() { - footnotes.add(this.flavor); - assertThat(footnotes.footnotes.size(), is(1)); - } - - @Test - public void testToString() { - footnotes.add(this.flavor); - assertThat(footnotes.toString(), is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java deleted file mode 100644 index 812cd087..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import static org.hamcrest.CoreMatchers.is; - -@RunWith(Parameterized.class) -public class DeleteOperationTest { - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n"," delete:\n tags:\n - Network\n summary: delete an existing generic-vnf\n description: delete an existing generic-vnf\n operationId: deleteNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n - name: resource-version\n in: query\n description: resource-version for concurrency\n required: true\n type: string\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, -// {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } - - public DeleteOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - } - - @Test - public void testToString() { - DeleteOperation delete = new DeleteOperation(useOpId, xmlRootElementName, tag, path, pathParams); - String modResult = delete.toString(); - assertThat(modResult, is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java deleted file mode 100644 index f6684f43..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.setup.ConfigTranslator; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.testutils.TestUtilConfigTranslatorforEdges; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.common.collect.Multimap; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {ConfigConfiguration.class, TestUtilConfigTranslatorforEdges.class, EdgeIngestor.class}) -@TestPropertySource(properties = {"schemaIngestPropLoc = src/test/resources/schemaIngest/schemaIngestTest.properties"}) - - -public class EdgeDescriptionTest { - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - @Autowired - ConfigTranslator ct; - @Autowired - EdgeIngestor edgeIngestor; - String nodeName = "availability-zone"; - String toNode = "complex"; - SchemaVersion v10 = new SchemaVersion("v10"); - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String json = "{" - + " \"rules\": [" - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"complex\"," - + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"this description\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"service-capability\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"cloud-region\"," - + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"!${direction}\"," - + " \"delete-other-v\": \"!${direction}\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"NONE\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"ctag-pool\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"${direction}\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"dvs-switch\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"generic-vnf\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"pserver\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vce\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " ]}"; - BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw.write(json); - bw.close(); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - File edges = new File(EDGEFILENAME); - edges.delete(); - } - @Before - public void setUp() throws Exception { - - } - @Test - public void test() { - - Map> edges = ct.getEdgeFiles(); - assertTrue(edges.containsKey(v10)); - assertTrue(1 == edges.get(v10).size()); - assertTrue("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json".equals(edges.get(v10).get(0))); - } - @Test - public void testGetDeleteOtherV() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"NONE"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDeleteOtherV(), is(target)); } ); - } - } - - @Test - public void testGetPreventDelete() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"IN"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getPreventDelete(), is(target)); } ); - } - } - - @Test - public void testGetAlsoDeleteFootnote() throws EdgeRuleNotFoundException { -// String toNode="cloud-region"; -// String target = "availability-zone"+"|"+toNode+"-"+"(4)"; - List notedTypes = Arrays.asList("cloud-region", "ctag-pool"); - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals("availability-zone") && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); String target = ed.getRuleKey()+"-"+(notedTypes.contains(ed.getTo()) ? "(4)" : ""); assertThat(ed.getRuleKey()+"-"+ed.getAlsoDeleteFootnote(ed.getFrom()), is(target)); } ); - } -/* - for (EdgeDescription ed : edges) { - String modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); - assertThat(modResult, is(target)); - ed.setDeleteOtherV("IN"); - target = "availability-zone"+"|"+"complex"+"-"+"(4)"; - modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); - assertThat(modResult, is(target)); - target = "availability-zone"+"|"+"complex"+"-"+"(1)"; - modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getTo()); - assertThat(modResult, is(target)); - ed.setDeleteOtherV("OUT"); - target = "availability-zone"+"|"+"complex"+"-"+"(2)"; - modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); - assertThat(modResult, is(target)); - target = "availability-zone"+"|"+"complex"+"-"+"(3)"; - modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getTo()); - assertThat(modResult, is(target)); - } -*/ - } - - @Test - public void testGetTo() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+toNode; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getTo(), is(target)); } ); - } - } - - @Test - public void testGetFrom() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"availability-zone"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getFrom(), is(target)); } ); - } - } - - @Test - public void testGetRuleKey() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey(), is(target)); } ); - } - } - - @Test - public void testGetMultiplicity() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"MANY2ONE"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getMultiplicity(), is(target)); } ); - } - } - - @Test - public void testGetDirection() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"OUT"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDirection(), is(target)); } ); - } - } - - @Test - public void testGetDescription() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"this description"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDescription(), is(target)); } ); - } - } - - @Test - public void testGetRelationshipDescription() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"this description"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDescription(), is(target)); } ); - } - } - - @Test - public void testGetType() throws EdgeRuleNotFoundException { - String toNode = "cloud-region"; - String target = "availability-zone"+"|"+toNode+"-"+"PARENT"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getType(), is(target)); } ); - } - } - - @Test - public void testGetLabel() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"org.onap.relationships.inventory.LocatedIn"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getLabel(), is(target)); } ); - } - } - - @Test - public void testGetShortLabel() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"LocatedIn"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getShortLabel(), is(target)); } ); - } - } -} - - diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java deleted file mode 100644 index bd4c5f95..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.hamcrest.CoreMatchers.is; - -@RunWith(Parameterized.class) -public class GetOperationTest { - private static final Logger logger = LoggerFactory.getLogger("GetOperationTest.class"); - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," /network/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Network\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/getDefinitions/generic-vnf\"\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__"," /cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces:\n get:\n tags:\n - CloudInfrastructure\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/getDefinitions/p-interfaces\"\n \"default\":\n null parameters:\n - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__ - name: interface-name\n in: query\n description:\n required: false\n type: string - name: prov-status\n in: query\n description:\n required: false\n type: string"}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } - - public GetOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String container = "p-interfaces"; - String queryProps[] = { - " - name: interface-name\n in: query\n description:\n required: false\n type: string", - " - name: prov-status\n in: query\n description:\n required: false\n type: string" - }; - Vector containerProps = new Vector(); - for(String prop : queryProps) { - containerProps.add(prop); - } - GetOperation.addContainerProps(container, containerProps); - } - - @Test - public void testAddContainerProps() { - String container = this.xmlRootElementName; - String prop = " - name: "+container+"\n in: query\n description:\n required: false\n type: string"; - Vector queryProps = new Vector(); - queryProps.add(prop); - for(String p : queryProps) { - logger.debug("qProp="+p); - } - logger.debug("Done="+this.xmlRootElementName); - GetOperation.addContainerProps(container, queryProps); - assertThat(GetOperation.containers.get(container).get(0), is(prop)); - } - - @Test - public void testToString() { - GetOperation get = new GetOperation(useOpId, xmlRootElementName, tag, path, pathParams); - String modResult = get.toString(); - assertThat(modResult, is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java deleted file mode 100644 index ca63244e..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java +++ /dev/null @@ -1,384 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.SwaggerGenerationConfiguration; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.junit.runner.RunWith; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.testutils.TestUtilConfigTranslatorforBusiness; -import org.onap.aai.util.AAIConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.w3c.dom.Element; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - ConfigConfiguration.class, - TestUtilConfigTranslatorforBusiness.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class - -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) -public class HTMLfromOXMTest { - private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - protected static final String SERVICE_NAME = "JUNIT"; - - - @Autowired - HTMLfromOXM htmlFromOxm; - - @Autowired - SchemaVersions schemaVersions; - - @BeforeClass - public static void setUpContext() throws Exception { - - } - @BeforeClass - public static void setupBundleconfig() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - System.setProperty("aai.service.name", SERVICE_NAME); - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); - } - - @Before - public void setUp() throws Exception { - setUp(0); - } - - public void setUp(int sbopt) throws Exception - { - XSDElementTest x = new XSDElementTest(); - x.setUp(sbopt); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - } - - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String header = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - htmlFromOxm.setSchemaVersions(schemaVersions); - header = htmlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); - } - logger.debug("Header:"); - logger.debug(header); - assertThat(header, is(HTMLheader())); - } - - @Test - public void testProcess() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - - @Test - public void testProcessWithCombiningJavaTypes() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - setUp(1); - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(1))); - } - - @Test - public void testHTMLfromOXMFileVersion() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - XMLfile.delete(); - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - - @Test - public void testHTMLfromOXMStringVersion() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - logger.debug("FileContent-II:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - - @Test - public void testProcessJavaTypeElement() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - Element customer = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - htmlFromOxm.process(); - customer = htmlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); - } - logger.debug("Element:"); - logger.debug("Element="+customer.getNodeName()+"/"+customer.getAttribute("name")); - assertThat("Element="+customer.getNodeName()+"/"+customer.getAttribute("name"), is(target)); } - - public String HTMLresult() { - return HTMLresult(0); - } - - public String HTMLresult(int sbopt) { - StringBuilder sb = new StringBuilder(32368); - sb.append(HTMLheader()); - sb.append(HTMLdefs(sbopt)); - return sb.toString(); - } - - public String HTMLheader() { - StringBuilder sb = new StringBuilder(1500); - sb.append("" + OxmFileProcessor.LINE_SEPARATOR); - sb.append("" + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - return sb.toString(); - } - - public String HTMLdefs() { - return HTMLdefs(0); - } - public String HTMLdefs(int sbopt) { - StringBuilder sb = new StringBuilder(1500); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(isKey=true,description=\"Value defined by orchestration to identify this service.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"This property will be deleted from A&AI in the near future. Only stop gap solution.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - if ( sbopt == 0 ) { - sb.append(" @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR); - } else { - sb.append(" @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-type,subscriber-name,global-customer-id\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR); - } - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(isKey=true,description=\"Global customer id used across to uniquely identify customer.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber name, an alternate way to retrieve a customer.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - if ( sbopt == 0 ) { - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - } else { - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - - } - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append("" + OxmFileProcessor.LINE_SEPARATOR); - return sb.toString(); - } -} - diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/NodeGetOperationTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/NodeGetOperationTest.java deleted file mode 100644 index 54013b7c..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/NodeGetOperationTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.hamcrest.CoreMatchers.is; - -@RunWith(Parameterized.class) -public class NodeGetOperationTest { - private static final Logger logger = LoggerFactory.getLogger("NodeGetOperationTest.class"); - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," /nodes/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Operations\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/generic-vnf\"\n \"default\":\n null\n parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, - {"GenericVnf","generic-vnf","","/Network/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__"," /nodes/p-interfaces?parameter=value[¶meter2=value2]:\n get:\n tags:\n - Operations\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/p-interfaces\"\n \"default\":\n null\n parameters:\n - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__\n - name: interface-name\n in: query\n description:\n required: false\n type: string - name: prov-status\n in: query\n description:\n required: false\n type: string"}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } - - public NodeGetOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String container = "p-interfaces"; - String queryProps[] = { - " - name: interface-name\n in: query\n description:\n required: false\n type: string", - " - name: prov-status\n in: query\n description:\n required: false\n type: string" - }; - Vector containerProps = new Vector(); - for(String prop : queryProps) { - containerProps.add(prop); - } - NodeGetOperation.addContainerProps(container, containerProps); - } - - @Test - public void testAddContainerProps() { - String container = this.xmlRootElementName; - String prop = " - name: "+container+"\n in: query\n description:\n required: false\n type: string"; - Vector queryProps = new Vector(); - queryProps.add(prop); - String props=null; - for(String p : queryProps) { - props += "qProp="+p+"\n"; -// logger.debug("qProp="+p); - } -// logger.debug("Done="+this.xmlRootElementName); - NodeGetOperation.addContainerProps(container, queryProps); - assertThat(props+"Done="+this.xmlRootElementName,NodeGetOperation.containers.get(container).get(0), is(prop)); - } - - @Test - public void testToString() { - NodeGetOperation get = new NodeGetOperation(useOpId, xmlRootElementName, tag, path, pathParams); - String modResult = get.toString(); - assertThat(modResult, is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/NodesYAMLfromOXMTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/NodesYAMLfromOXMTest.java deleted file mode 100644 index b08ddcee..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/NodesYAMLfromOXMTest.java +++ /dev/null @@ -1,636 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.hamcrest.CoreMatchers.is; - -import static org.junit.Assert.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.apache.commons.lang.StringUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.aai.AAISetup; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.SwaggerGenerationConfiguration; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.junit.runner.RunWith; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.testutils.TestUtilConfigTranslatorforEdges; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.w3c.dom.Element; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - ConfigConfiguration.class, - TestUtilConfigTranslatorforEdges.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class - -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) -public class NodesYAMLfromOXMTest { -//public class NodesYAMLfromOXMTest extends AAISetup { - private static final Logger logger = LoggerFactory.getLogger("NodesYAMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - - @Autowired - NodesYAMLfromOXM nodesYamlFromOxm; - @Autowired - SchemaVersions schemaVersions; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(YAMLfromOXMTest.EdgeDefs()); - bw1.close(); - - - } - - @Before - public void setUp() throws Exception { - - NodeGetOperation.checklist.clear(); - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; - - logger.debug(testXML); - } - - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String header = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - header = nodesYamlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Header:\n"+header,header, is(YAMLheader())); - } - - @Test - public void testProcess() { - - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("FileContent-I:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testNodesYAMLfromOXMFileVersionFile() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - XMLfile.delete(); - assertThat("FileContent:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testNodesYAMLfromOXMStringVersionFile() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("FileContent-II:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testAppendDefinitions() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String definitions = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - definitions = nodesYamlFromOxm.appendDefinitions(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Definitions:\n"+definitions,definitions, is(YAMLgetDefs())); - } - - @Test - public void testGetXMLRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - String root = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); - root = nodesYamlFromOxm.getXMLRootElementName(customer); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetXmlRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String root = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - root = nodesYamlFromOxm.getXmlRootElementName("Customer"); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetJavaTypeElementSwagger() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Element="+customer.getNodeName()+"/"+customer.getAttribute("name"), is(target)); - } - - public String YAMLresult() { - StringBuilder sb = new StringBuilder(32368); - sb.append(YAMLheader()); - sb.append(YAMLops()); -// sb.append(YAMLdefs()); -// sb.append(YAMLpatchDefs()); - sb.append(YAMLgetDefs()); - return sb.toString(); - } - public String YAMLheader() { - StringBuilder sb = new StringBuilder(1500); - sb.append("swagger: \"2.0\"\n"); - sb.append("info:\n"); - sb.append(" description: |\n"); - sb.append("\n"); - sb.append(" [Differences versus the previous schema version](apidocs/aai_swagger_v11.diff)\n"); - sb.append("\n"); - sb.append(" Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.\n"); - sb.append("\n"); - sb.append(" Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n"); - sb.append("\n"); - sb.append(" You may obtain a copy of the License at\n"); - sb.append("\n"); - sb.append(" (https://creativecommons.org/licenses/by/4.0/)\n"); - sb.append("\n"); - sb.append(" Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n"); - sb.append("\n"); - sb.append(" This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n"); - sb.append(" version: \"v11\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n"); - sb.append(" name: Apache 2.0\n"); - sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n"); - sb.append(" name:\n"); - sb.append(" url:\n"); - sb.append(" email:\n"); - sb.append("host:\n"); - sb.append("basePath: /aai/v11\n"); - sb.append("schemes:\n"); - sb.append(" - https\n"); - sb.append("paths:\n"); - return sb.toString(); - } - - public String YAMLops() { - StringBuilder sb = new StringBuilder(16384); - sb.append(" /nodes/customers/customer/{global-customer-id}:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns customer\n"); - sb.append(" description: returns customer\n"); - sb.append(" operationId: getBusinessCustomersCustomer\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" /nodes/customers?parameter=value[¶meter2=value2]:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns customers\n"); - sb.append(" description: returns customers\n"); - sb.append(" operationId: getBusinessCustomers\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customers\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: query\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: subscriber-name\n"); - sb.append(" in: query\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" example: __SUBSCRIBER-NAME__\n"); - sb.append(" - name: subscriber-type\n"); - sb.append(" in: query\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" example: __SUBSCRIBER-TYPE__\n"); - sb.append(" /nodes/service-subscriptions?parameter=value[¶meter2=value2]:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns service-subscriptions\n"); - sb.append(" description: returns service-subscriptions\n"); - sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/service-subscriptions\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: query\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - return sb.toString(); - } - public String YAMLdefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("definitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - return sb.toString(); - } - public String YAMLpatchDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("patchDefinitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/patchDefinitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/patchDefinitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/patchDefinitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/patchDefinitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/patchDefinitions/service-subscription\"\n"); - return sb.toString(); - } - public String YAMLgetDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("definitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - return sb.toString(); - } -} - diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java deleted file mode 100644 index 7706e09c..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import static org.hamcrest.CoreMatchers.is; - -@RunWith(Parameterized.class) -public class PatchOperationTest { - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," patch:\n tags:\n - Network\n summary: update an existing generic-vnf\n description: |\n Update an existing generic-vnf\n #\n Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n The PUT operation will entirely replace an existing object.\n The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n #\n Other differences between PUT and PATCH are:\n #\n - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n operationId: UpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n produces:\n - application/json\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be updated.\n required: true\n schema:\n $ref: \"#/patchDefinitions/generic-vnf\"\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } - - public PatchOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - } - - @Test - public void testToString() { - PatchOperation patch = new PatchOperation(useOpId, xmlRootElementName, tag, path, pathParams); - String modResult = patch.toString(); - assertThat(modResult, is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java deleted file mode 100644 index 23eb469a..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.onap.aai.setup.SchemaVersion; - -import static org.hamcrest.CoreMatchers.is; - -@RunWith(Parameterized.class) -public class PutOperationTest { - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; - private static SchemaVersion v = new SchemaVersion("v14"); - - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," put:\n tags:\n - Network\n summary: create or update an existing generic-vnf\n description: |\n Create or update an existing generic-vnf.\n #\n Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n operationId: createOrUpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be created or updated. [Valid relationship examples shown here](apidocs/relations/"+v.toString()+"/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } - - public PutOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - } - - @Test - public void testToString() { - PutOperation put = new PutOperation(useOpId, xmlRootElementName, tag, path, pathParams, v); - String modResult = put.toString(); - assertThat(modResult, is(this.result)); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java deleted file mode 100644 index c39479f5..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.util.GenerateXsd; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaVersions.class, - EdgeIngestor.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai" -}) -@Ignore("This test needs to get major rework done as it is written very poorly") -public class PutRelationPathSetTest { - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - - private static String json; - private SchemaVersion v ; - private File relationsFile ; - private String target = "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; - private String opId = "createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZoneRelationshipListRelationship"; - private String path = "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; - PutRelationPathSet prp = null; - @Autowired - SchemaVersions schemaVersions; - - @Autowired - EdgeIngestor edgeIngestor; - - - @Before - public void setUpBeforeClass() throws Exception { - v = schemaVersions.getDefaultVersion(); - - relationsFile = new File(GenerateXsd.getYamlDir() + "/relations/" + v.toString()+"/createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZone.json"); - json = "{" - + " \"rules\": [" - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"complex\"," - + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"this description\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"service-capability\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"cloud-region\"," - + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"!${direction}\"," - + " \"delete-other-v\": \"!${direction}\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"NONE\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"ctag-pool\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"dvs-switch\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"generic-vnf\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vf-module\"," - + " \"to\": \"vnfc\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"ONE2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"pserver\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vce\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " ]}"; - - BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw.write(json); - bw.close(); - - } - - @Before - public void setUp() throws Exception { - - DeleteOperation.deletePaths.put("/cloud-infrastructure/pservers/pserver/{hostname}","pserver"); - DeleteOperation.deletePaths.put("/network/vces/vce/{vnf-id}","vce"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/complexes/complex/{physical-location-id}","complex"); - DeleteOperation.deletePaths.put("/service-design-and-creation/service-capabilities/service-capability/{service-type}/{vnf-type}","service-capability"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}","cloud-region"); - DeleteOperation.deletePaths.put("/network/generic-vnfs/generic-vnf/{vnf-id}","generic-vnf"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/dvs-switches/dvs-switch/{switch-name}","dvs-switch"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/complexes/complex/{physical-location-id}/ctag-pools/ctag-pool/{target-pe}/{availability-zone-name}","ctag-pool"); - - DeleteOperation.deletePaths.put(path.replace("/relationship-list/relationship", ""),"availability-zone"); - PutRelationPathSet.add(opId, path); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - File edges = new File(EDGEFILENAME); - edges.delete(); - } - @Test - public void testAdd() { - PutRelationPathSet.add(opId, path); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); - } - - @Test - public void testPutRelationPathSet() { - - this.prp = new PutRelationPathSet(v); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - prp.generateRelations(edgeIngestor); - assertTrue(this.relationsFile.exists()); - this.relationsFile.delete(); - } - - @Test - public void testPutRelationPathSetStringString() { - this.prp = new PutRelationPathSet(opId, path, v); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - } - - @Test - public void testGenerateRelations() { - PutRelationPathSet prp = new PutRelationPathSet(opId, "availability-zone", v); - prp.generateRelations(edgeIngestor); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); - assertTrue(this.relationsFile.exists()); -// this.relationsFile.delete(); - } - -} - - diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java deleted file mode 100644 index 6058ecee..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java +++ /dev/null @@ -1,631 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.collection.IsIn.*; -import static org.hamcrest.CoreMatchers.both; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.hamcrest.core.Every.everyItem; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Vector; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.lang.StringUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.aai.exceptions.AAIException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class XSDElementTest { - private static final Logger logger = LoggerFactory.getLogger("XSDElementTest.class"); - private static final int maxSizeForXml = 20000; - protected String testXML; - protected Document doc = null; - protected NodeList javaTypeNodes=null; - - public String getTestXML() { - return testXML; - } - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - setUp(0); - } - - public void setUp( int sbopt ) throws Exception { - StringBuilder sb = new StringBuilder(maxSizeForXml); - addNamespace(sb); - addBusiness(sb); - addCustomers(sb); - if ( sbopt == 0 ) { - addCustomer(sb); - } else { - addCustomerNoSubscriberType(sb); - addCustomerSubscriberType(sb); - } - addServiceSubscriptions(sb); - addServiceSubscription(sb); - addEndOfXML(sb); - testXML = sb.toString(); - init(); -} - - private void addNamespace(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addBusiness(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomers(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomer(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); -// sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomerNoSubscriberType(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomerSubscriberType(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addServiceSubscriptions(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - private void addServiceSubscription(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); -// sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationshipList(StringBuilder sb ) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("/n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationship(StringBuilder sb ) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append(""); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelatedToProperty(StringBuilder sb) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationshipData(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - - private void addEndOfXML(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - } - - public void init() throws ParserConfigurationException, SAXException, IOException, AAIException { - DocumentBuilder dBuilder = null; - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - dBuilder = dbFactory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw e; - } - try { - InputSource isInput = new InputSource(new StringReader(testXML)); - doc = dBuilder.parse(isInput); - } catch (SAXException e) { - throw e; - } catch (IOException e) { - throw e; - } - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - throw new AAIException("OXM file error: missing in XML"); - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - throw new AAIException("OXM file error: missing in XML"); - } - javaTypesElement = (Element) javaTypesNodes.item(0); - - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - throw new AAIException("OXM file error: missing in XML"); - } - logger.debug(testXML); - } - @Test - public void testXSDElement() { - // repeat of testGetIndexedProps() which uses the constructor - ArrayList target = new ArrayList(); - target.add("subscriber-name"); - target.add("global-customer-id"); - target.add("subscriber-type"); - target.add("service-type"); - - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - indexedProps.addAll(javaTypeElement.getIndexedProps()); - } - assertThat(new ArrayList<>(indexedProps),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testName() { - ArrayList target = new ArrayList(); - target.add("ServiceSubscriptions"); - target.add("ServiceSubscription"); - target.add("Inventory"); - target.add("Business"); - target.add("Customers"); - target.add("Customer"); - ArrayList names = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - names.add(javaTypeElement.name()); - } - logger.debug(String.join("|", names)); - assertThat(names,both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetAddTypes() { - HashMap> map = new HashMap>(); - HashMap> target = new HashMap>(); - target.put("Customer", new ArrayList<>(Arrays.asList("ServiceSubscriptions", "RelationshipList"))); - target.put("Customer", new ArrayList<>(Arrays.asList("ServiceSubscriptions"))); - target.put("Business", new ArrayList<>(Arrays.asList("Customers"))); - target.put("Inventory", new ArrayList<>(Arrays.asList("Business"))); - target.put("Customers", new ArrayList<>(Arrays.asList("Customer"))); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList("RelationshipList"))); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList())); - target.put("ServiceSubscriptions", new ArrayList<>(Arrays.asList("ServiceSubscription"))); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList addTypes = new ArrayList(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - String name=javaTypeElement.name(); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - addTypes.addAll(xmlElement.getAddTypes("v11")); - map.put(name,addTypes); - } - } - for(String key : map.keySet()) { - assertThat("Expected for key:"+key, map.get(key),equalTo(target.get(key))); - } - } -/* - @Test - public void testGetRequiredElements() { - HashMap> map = new HashMap>(); - ArrayList target = new ArrayList(); - target.add("global-customer-id\n"); - target.add("subscriber-name\n"); - target.add("subscriber-type"); - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList requiredItems = new ArrayList(); - String name=javaTypeElement.name(); - requiredItems.addAll(javaTypeElement.getRequiredElements("v11")); - map.put(name,requiredItems); - } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target)); - } - } -*/ - @Test - public void testGetPathDescriptionProperty() { - ArrayList target = new ArrayList(); - target.add("Namespace for business related constructs"); - target.add("Collection of customer identifiers to provide linkage back to BSS information."); - target.add("customer identifiers to provide linkage back to BSS information."); - target.add("Collection of objects that group service instances."); - target.add("Object that group service instances."); - List descs = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getPathDescriptionProperty() != null) - descs.add(javaTypeElement.getPathDescriptionProperty()); - } - logger.debug(String.join("|", descs)); - assertThat(new ArrayList<>(descs),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetIndexedProps() { - ArrayList target = new ArrayList(); - target.add("subscriber-name"); - target.add("global-customer-id"); - target.add("subscriber-type"); - target.add("service-type"); - - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - indexedProps.addAll(javaTypeElement.getIndexedProps()); - } - assertThat(new ArrayList<>(indexedProps),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetContainerProperty() { - ArrayList target = new ArrayList(); - target.add("service-subscriptions"); - target.add("customers"); - List containers = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getContainerProperty() != null) - containers.add(javaTypeElement.getContainerProperty()); - } - logger.debug(String.join("|", containers)); - assertThat(new ArrayList<>(containers),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetQueryParamYAML() { - ArrayList target = new ArrayList(); - target.add(" - name: global-customer-id\n in: query\n description:\n required: false\n type: string\n"); - target.add(" - name: subscriber-name\n in: query\n description:\n required: false\n type: string\n"); - target.add(" - name: subscriber-type\n in: query\n description:\n required: false\n type: string\n"); - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getContainerProperty() != null) { - indexedProps.addAll(javaTypeElement.getIndexedProps()); - String container = javaTypeElement.getContainerProperty(); - Vector containerProps = new Vector(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - if(indexedProps.contains(xmlElement.name())) - containerProps.add(xmlElement.getQueryParamYAML()); - } - GetOperation.addContainerProps(container, containerProps); - } - } -/* - List queryParams = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getQueryParamYAML() != null) - queryParams.add(javaTypeElement.getQueryParamYAML()); - } -*/ - assertThat(GetOperation.containers.get("customers"),equalTo( target)); - } - - @Test - public void testGetPathParamYAML() { - ArrayList target = new ArrayList(); - target.add(" - name: Inventory\n in: path\n description: Inventory\n required: true\n example: __INVENTORY__\n"); - target.add(" - name: Business\n in: path\n description: Business\n required: true\n example: __BUSINESS__\n"); - target.add(" - name: Customers\n in: path\n description: Customers\n required: true\n example: __CUSTOMERS__\n"); - target.add(" - name: Customer\n in: path\n description: Customer\n required: true\n example: __CUSTOMER__\n"); - target.add(" - name: ServiceSubscriptions\n in: path\n description: ServiceSubscriptions\n required: true\n example: __SERVICESUBSCRIPTIONS__\n"); - target.add(" - name: ServiceSubscription\n in: path\n description: ServiceSubscription\n required: true\n example: __SERVICESUBSCRIPTION__\n"); - List pathParams = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getPathParamYAML(javaTypeElement.name()) != null) - pathParams.add(javaTypeElement.getPathParamYAML(javaTypeElement.name())); - } - logger.debug(String.join("|", pathParams)); - assertThat(new ArrayList<>(pathParams),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetHTMLAnnotation() { - ArrayList target = new ArrayList(); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - List annotes = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(StringUtils.isNotEmpty(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(),""))) - annotes.add(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(), " ")); - } - logger.debug("result:"); - logger.debug(String.join("|", annotes)); - logger.debug("Expected:"); - logger.debug(String.join("|", target)); - assertThat(new ArrayList<>(annotes),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - - } - - @Test - public void testGetTypePropertyYAML() { - ArrayList target = new ArrayList(); - target.add(" Inventory:\n type: "); - target.add(" Business:\n type: description: Namespace for business related constructs\n"); - target.add(" Customers:\n type: description: Collection of customer identifiers to provide linkage back to BSS information.\n"); - target.add(" Customer:\n type: description: customer identifiers to provide linkage back to BSS information.\n"); - target.add(" ServiceSubscriptions:\n type: description: Collection of objects that group service instances.\n"); - target.add(" ServiceSubscription:\n type: description: Object that group service instances.\n"); - List types = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getTypePropertyYAML() != null) - types.add(javaTypeElement.getTypePropertyYAML()); - } - assertThat(new ArrayList<>(types),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testIsStandardType() { - HashMap> map = new HashMap>(); - HashMap> target = new HashMap>(); - target.put("Customer", new ArrayList<>(Arrays.asList("global-customer-id","subscriber-name", "subscriber-type","resource-version"))); - target.put("Business", new ArrayList<>()); - target.put("Inventory", new ArrayList<>()); - target.put("Customers", new ArrayList<>()); - target.put("ServiceSubscriptions", new ArrayList<>()); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList("service-type", "temp-ub-sub-account-id", "resource-version"))); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList addTypes = new ArrayList(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - String name=javaTypeElement.name(); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - if(xmlElement.isStandardType()) - addTypes.add(xmlElement.name()); - } - map.put(name,addTypes); - } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target.get(key))); - } - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java deleted file mode 100644 index 27d9898b..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.*; - -import java.util.HashMap; - -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Element; - -public class XSDJavaTypeTest extends XSDElementTest { - - @Before - public void setUp() throws Exception { - super.setUp(); - } - - @Test - public void testXSDJavaTypeElement() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", "global-customer-id"); - target.put("Business", "customers"); - target.put("Inventory", "business"); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", "service-type"); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getItemName()); - } - for(String key : map.keySet()) { - assertThat("For key: "+key,map.get(key),equalTo(target.get(key))); - } - } - - @Test - public void testGetItemName() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", "global-customer-id"); - target.put("Business", "customers"); - target.put("Inventory", "business"); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", "service-type"); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getItemName()); - } - for(String key : map.keySet()) { - assertThat("For key: "+key,map.get(key),equalTo(target.get(key))); - } - } - - @Test - public void testGetArrayType() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", null); - target.put("Business", null); - target.put("Inventory", null); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", null); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getArrayType()); - } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target.get(key))); - } - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java deleted file mode 100644 index e9a52a39..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java +++ /dev/null @@ -1,942 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.util.genxsd; - -import static org.hamcrest.CoreMatchers.is; - -import static org.junit.Assert.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.aai.AAISetup; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.SwaggerGenerationConfiguration; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.junit.runner.RunWith; -import org.onap.aai.edges.EdgeIngestor; -import org.onap.aai.edges.EdgeRule; -import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.testutils.TestUtilConfigTranslatorforBusiness; -import org.onap.aai.util.AAIConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.google.common.collect.Multimap; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - ConfigConfiguration.class, - TestUtilConfigTranslatorforBusiness.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class - -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) -public class YAMLfromOXMTest { - @Autowired - EdgeIngestor edgeIngestor; - - @Autowired - NodeIngestor nodeIngestor; - private static final Logger logger = LoggerFactory.getLogger("YAMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - protected static final String SERVICE_NAME = "JUNIT"; - boolean first = true; - - @Autowired - YAMLfromOXM yamlFromOxm; - - @Autowired - SchemaVersions schemaVersions; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - System.setProperty("aai.service.name", SERVICE_NAME); - - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(EdgeDefs()); - bw1.close(); - - - - - - } - - @Before - public void setUp() throws Exception { - - } - - @Test - public void AtestIngestors() throws EdgeRuleNotFoundException { - Multimap results = edgeIngestor.getAllRules(schemaVersions.getDefaultVersion()); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> ((! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); System.out.println(ed.getRuleKey()); } ); - } - Document doc = nodeIngestor.getSchema(schemaVersions.getDefaultVersion()); - assertNotNull(doc); - } - - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String header = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - header = yamlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Header:\n"+header,header, is(YAMLheader())); - } - - @Test - public void testProcess() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("FileContent-TestProcess:\n"+fileContent,fileContent, is(YAMLresult())); - } - - - @Test - public void testYAMLfromOXMFileVersionFile() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - XMLfile.delete(); - assertThat("FileContent-OXMFileVersionFile:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testYAMLfromOXMStringVersionFile() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("FileContent-OXMStringVersionFile:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testAppendDefinitions() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String definitions = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - definitions = yamlFromOxm.appendDefinitions(); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Definitions:\n"+definitions,definitions, is(YAMLdefs()+YAMLpatchDefs()+YAMLgetDefs())); - } - - @Test - public void testGetXMLRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - String root = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); - root = yamlFromOxm.getXMLRootElementName(customer); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetXmlRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String root = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - root = yamlFromOxm.getXmlRootElementName("Customer"); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetJavaTypeElementSwagger() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); - } - assertThat("Element="+customer.getNodeName()+"/"+customer.getAttribute("name"), is(target)); - } - - public String YAMLresult() { - StringBuilder sb = new StringBuilder(32368); - sb.append(YAMLheader()); - sb.append(YAMLops()); - sb.append(YAMLdefs()); - sb.append(YAMLpatchDefs()); - sb.append(YAMLgetDefs()); - return sb.toString(); - } - public String YAMLheader() { - StringBuilder sb = new StringBuilder(1500); - sb.append("swagger: \"2.0\"\n"); - sb.append("info:\n"); - sb.append(" description: |\n"); - sb.append("\n"); - sb.append(" [Differences versus the previous schema version](apidocs/aai_swagger_v11.diff)\n"); - sb.append("\n"); - sb.append(" Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.\n"); - sb.append("\n"); - sb.append(" Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n"); - sb.append("\n"); - sb.append(" You may obtain a copy of the License at\n"); - sb.append("\n"); - sb.append(" (https://creativecommons.org/licenses/by/4.0/)\n"); - sb.append("\n"); - sb.append(" Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n"); - sb.append("\n"); - sb.append(" This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n"); - sb.append(" version: \"v11\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n"); - sb.append(" name: Apache 2.0\n"); - sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n"); - sb.append(" name:\n"); - sb.append(" url:\n"); - sb.append(" email:\n"); - sb.append("host:\n"); - sb.append("basePath: /aai/v11\n"); - sb.append("schemes:\n"); - sb.append(" - https\n"); - sb.append("paths:\n"); - return sb.toString(); - } - - public String YAMLops() { - StringBuilder sb = new StringBuilder(16384); - sb.append(" /business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns service-subscription\n"); - sb.append(" description: returns service-subscription\n"); - sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/getDefinitions/service-subscription\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" put:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: create or update an existing service-subscription\n"); - sb.append(" description: |\n"); - sb.append(" Create or update an existing service-subscription.\n"); - sb.append(" #\n"); - sb.append(" Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); - sb.append(" operationId: createOrUpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: service-subscription object that needs to be created or updated. [Valid relationship examples shown here](apidocs/relations/v11/BusinessCustomersCustomerServiceSubscriptionsServiceSubscription.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" patch:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: update an existing service-subscription\n"); - sb.append(" description: |\n"); - sb.append(" Update an existing service-subscription\n"); - sb.append(" #\n"); - sb.append(" Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); - sb.append(" The PUT operation will entirely replace an existing object.\n"); - sb.append(" The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); - sb.append(" #\n"); - sb.append(" Other differences between PUT and PATCH are:\n"); - sb.append(" #\n"); - sb.append(" - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); - sb.append(" - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); - sb.append(" - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); - sb.append(" operationId: UpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: service-subscription object that needs to be updated.\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/patchDefinitions/service-subscription\"\n"); - sb.append(" delete:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: delete an existing service-subscription\n"); - sb.append(" description: delete an existing service-subscription\n"); - sb.append(" operationId: deleteBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: resource-version\n"); - sb.append(" in: query\n"); - sb.append(" description: resource-version for concurrency\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" /business/customers/customer/{global-customer-id}/service-subscriptions:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns service-subscriptions\n"); - sb.append(" description: returns service-subscriptions\n"); - sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/getDefinitions/service-subscriptions\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: query\n"); - sb.append(" description:\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" /business/customers/customer/{global-customer-id}:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns customer\n"); - sb.append(" description: returns customer\n"); - sb.append(" operationId: getBusinessCustomersCustomer\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/getDefinitions/customer\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" put:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: create or update an existing customer\n"); - sb.append(" description: |\n"); - sb.append(" Create or update an existing customer.\n"); - sb.append(" #\n"); - sb.append(" Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); - sb.append(" operationId: createOrUpdateBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: customer object that needs to be created or updated. [Valid relationship examples shown here](apidocs/relations/v11/BusinessCustomersCustomer.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" patch:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: update an existing customer\n"); - sb.append(" description: |\n"); - sb.append(" Update an existing customer\n"); - sb.append(" #\n"); - sb.append(" Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); - sb.append(" The PUT operation will entirely replace an existing object.\n"); - sb.append(" The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); - sb.append(" #\n"); - sb.append(" Other differences between PUT and PATCH are:\n"); - sb.append(" #\n"); - sb.append(" - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); - sb.append(" - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); - sb.append(" - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); - sb.append(" operationId: UpdateBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: customer object that needs to be updated.\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/patchDefinitions/customer\"\n"); - sb.append(" delete:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: delete an existing customer\n"); - sb.append(" description: delete an existing customer\n"); - sb.append(" operationId: deleteBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: resource-version\n"); - sb.append(" in: query\n"); - sb.append(" description: resource-version for concurrency\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" /business/customers:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns customers\n"); - sb.append(" description: returns customers\n"); - sb.append(" operationId: getBusinessCustomers\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/getDefinitions/customers\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: query\n"); - sb.append(" description:\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" - name: subscriber-name\n"); - sb.append(" in: query\n"); - sb.append(" description:\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" - name: subscriber-type\n"); - sb.append(" in: query\n"); - sb.append(" description:\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - return sb.toString(); - } - public String YAMLdefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("definitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - return sb.toString(); - } - public String YAMLpatchDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("patchDefinitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/patchDefinitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/patchDefinitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/patchDefinitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/patchDefinitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/patchDefinitions/service-subscription\"\n"); - return sb.toString(); - } - public String YAMLgetDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("getDefinitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/getDefinitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/getDefinitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/getDefinitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/getDefinitions/business\"\n"); - sb.append(" nodes:\n"); - sb.append(" properties:\n"); - sb.append(" inventory-item-data:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/getDefinitions/inventory-item-data\"\n"); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/getDefinitions/service-subscription\"\n"); - return sb.toString(); - } - public static String EdgeDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("{\n" + - " \"rules\": [\n"); - sb.append(" {\n"); - sb.append(" \"from\": \"service-subscription\",\n"); - sb.append(" \"to\": \"customer\",\n" + - " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2ONE\",\n" + - " \"contains-other-v\": \"!${direction}\",\n" + - " \"delete-other-v\": \"!${direction}\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n"); - sb.append(" },\n"); - sb.append(" {\n" + - " \"from\": \"service-instance\",\n" + - " \"to\": \"service-subscription\",\n" + - " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2ONE\",\n" + - " \"contains-other-v\": \"!${direction}\",\n" + - " \"delete-other-v\": \"!${direction}\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n" + - " },\n"); - sb.append(" {\n" + - " \"from\": \"service-subscription\",\n" + - " \"to\": \"tenant\",\n" + - " \"label\": \"org.onap.relationships.inventory.Uses\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2MANY\",\n" + - " \"contains-other-v\": \"NONE\",\n" + - " \"delete-other-v\": \"NONE\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n" + - " }"); - sb.append(" ]\n" + - "}\n"); - return sb.toString(); - } -} - -- cgit 1.2.3-korg