aboutsummaryrefslogtreecommitdiffstats
path: root/aai-core
diff options
context:
space:
mode:
authorKajur, Harish (vk250x) <vk250x@att.com>2018-03-24 21:59:03 -0400
committerKajur, Harish (vk250x) <vk250x@att.com>2018-03-26 08:48:18 -0400
commitf1a8fb1bc04f5d685f2b31d35db605f6fa054f60 (patch)
treea5e432ad396ec3f2587993a69099890ed723e0d8 /aai-core
parentb1264ad4012f67664d71982a0eaad7e9bcce34f4 (diff)
Add plugin to check coverage
Get line coverage to 50% and ensure it doesn't go down Issue-ID: AAI-498 Change-Id: Ib466b7e2b7cb6d2f888e3b58c2073bb02ab6f809 Signed-off-by: Kajur, Harish (vk250x) <vk250x@att.com>
Diffstat (limited to 'aai-core')
-rw-r--r--aai-core/pom.xml30
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/Version.java37
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java2038
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java57
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java106
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java242
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeRuleSet.java196
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java121
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java190
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java199
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java116
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java114
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java216
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java678
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java64
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java470
-rw-r--r--aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java7
-rw-r--r--aai-core/src/test/java/org/onap/aai/HttpTestUtil.java21
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/MoxyLoaderTest.java77
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java65
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/VersionTest.java50
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java118
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java36
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java49
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java79
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java94
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java125
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java70
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java24
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java130
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java19
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java94
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java78
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java19
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java24
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java21
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/PserverTest.java20
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/TenantTest.java23
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java129
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java16
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java195
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java18
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java125
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/AutoGenerateHtmlTest.java35
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java294
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java71
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java22
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java83
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java82
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java392
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeRuleSetTest.java243
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java107
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java278
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java82
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java84
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java223
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java564
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java101
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java826
59 files changed, 7562 insertions, 2525 deletions
diff --git a/aai-core/pom.xml b/aai-core/pom.xml
index 73f2a74d..de468af9 100644
--- a/aai-core/pom.xml
+++ b/aai-core/pom.xml
@@ -45,10 +45,11 @@
<sonar.projectVersion>${project.version}</sonar.projectVersion>
<httpclient.version>4.5.1</httpclient.version>
<jackson.version>2.2.3</jackson.version>
- <eelf.core.version>1.0.0</eelf.core.version>
- <logback.version>1.2.3</logback.version>
- <freemarker.version>2.3.21</freemarker.version>
- <activemq.version>5.15.3</activemq.version>
+ <eelf.core.version>1.0.0</eelf.core.version>
+ <logback.version>1.2.3</logback.version>
+ <freemarker.version>2.3.21</freemarker.version>
+ <activemq.version>5.15.3</activemq.version>
+ <jacoco.line.coverage.limit>0.50</jacoco.line.coverage.limit>
</properties>
<profiles>
<profile>
@@ -282,6 +283,27 @@
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
+ <execution>
+ <id>default-check</id>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ <configuration>
+ <dataFile>${project.build.directory}/coverage-reports/jacoco.exec</dataFile>
+ <rules>
+ <rule implementation="org.jacoco.maven.RuleConfiguration">
+ <element>BUNDLE</element>
+ <limits>
+ <limit implementation="org.jacoco.report.check.Limit">
+ <counter>LINE</counter>
+ <value>COVEREDRATIO</value>
+ <minimum>${jacoco.line.coverage.limit}</minimum>
+ </limit>
+ </limits>
+ </rule>
+ </rules>
+ </configuration>
+ </execution>
</executions>
</plugin>
<plugin>
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Version.java b/aai-core/src/main/java/org/onap/aai/introspection/Version.java
index 76ff939f..d32212b8 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/Version.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/Version.java
@@ -19,6 +19,9 @@
*/
package org.onap.aai.introspection;
+/**
+ * Requires the order to be in ascending order
+ */
public enum Version {
v8,
v9,
@@ -26,12 +29,38 @@ public enum Version {
v11,
v12,
v13;
-
+
+ public static final String VERSION_EXPRESSION = "v8|v9|v10|v11|v12|v13|latest";
+ public static final String VERSION_EXPRESSION_V8_PLUS = "v8|v9|v10|v11|v12|v13|latest";
+ public static final String VERSION_EXPRESSION_V9_PLUS = "v9|v10|v11|v12|v13|latest";
+
+ /**
+ * Checks if v is the latest version
+ * @param v
+ * @return
+ */
public static boolean isLatest(Version v) {
- return (Version.v13.equals(v)); //TODO update when we increment the version, or find a better way of doing this
+ return Version.getLatest().equals(v);
}
-
+
+ /**
+ * Gets the latest version
+ * @return
+ */
public static Version getLatest(){
- return Version.v13; //TODO update when we increment the version, or find a better way of doing this
+ return Version.values()[Version.values().length-1];
+ }
+
+ /**
+ * To be used inplace of <b>Version.getVersion(String)</b> to correctly get version of "latest"
+ * @param v
+ * @return
+ */
+ public static Version getVersion(String v) {
+ if ("latest".equals(v)) {
+ return Version.getLatest();
+ }
+ return Version.valueOf(v);
}
+
}
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
index 4ee65dd0..63318da3 100644
--- a/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java
+++ b/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java
@@ -7,708 +7,71 @@
* 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
- *
+ *
+ * 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.
*/
-package org.onap.aai.util;
-import com.google.common.base.Joiner;
-import com.jayway.jsonpath.JsonPath;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.text.similarity.LevenshteinDistance;
+package org.onap.aai.util;
import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeProperty;
-import org.w3c.dom.*;
-import org.xml.sax.InputSource;
+import org.onap.aai.util.genxsd.EdgeRuleSet;
+import org.onap.aai.util.genxsd.HTMLfromOXM;
+import org.onap.aai.util.genxsd.YAMLfromOXM;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.*;
-import java.io.*;
+import java.io.BufferedWriter;
+import java.io.File;
+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.*;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
public class GenerateXsd {
private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class");
-
- static String apiVersion = null;
+ protected static String apiVersion = null;
static String apiVersionFmt = null;
static boolean useAnnotationsInXsd = false;
static String responsesUrl = null;
static String responsesLabel = null;
static String jsonEdges = null;
+ static EdgeRuleSet edgeRuleSet = null;
static Map<String, String> generatedJavaType;
static Map<String, String> appliedPaths;
- static Map<String, String> deletePaths;
- static Map<String, String> putRelationPaths;
- static NodeList javaTypeNodes;
- static Map<String,String> javaTypeDefinitions = createJavaTypeDefinitions();
- private static Map<String, String> createJavaTypeDefinitions()
- {
- StringBuffer aaiInternal = new StringBuffer();
- Map<String,String> javaTypeDefinitions = new HashMap<String, String>();
- 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 static final String root = "../aai-schema/src/main/resources";
+ private static final String autoGenRoot = "aai-schema/src/main/resources";
+ private static final String normalStartDir = "aai-core";
private static final String xsd_dir = root + "/aai_schema";
- private static final String yaml_dir = root + "/aai_swagger_yaml";
+ private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/aai_swagger_yaml";
/* These three strings are for yaml auto-generation from aai-common class*/
- private static final String normalStartDir = "aai-core";
- private static final String autoGenRoot = "aai-schema/src/main/resources";
- private static final String alt_yaml_dir = autoGenRoot + "/aai_swagger_yaml";
+// private static final String alt_yaml_dir = autoGenRoot + "/aai_swagger_yaml";
private static int annotationsStartVersion = 9; // minimum version to support annotations in xsd
private static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation
- private static XPath xpath = XPathFactory.newInstance().newXPath();
-
-
- private enum LineageType {
- PARENT, CHILD, UNRELATED;
- }
- private class EdgeDescription {
-
- private String ruleKey;
- private String to;
- private String from;
- private LineageType type = LineageType.UNRELATED;
- private String direction;
- private String multiplicity;
- private String preventDelete;
- private String deleteOtherV;
- private boolean hasDelTarget = false;
- private String label;
- private String description;
- /**
- * @return the deleteOtherV
- */
- public String getDeleteOtherV() {
- return deleteOtherV;
- }
- /**
- * @param deleteOtherV the deleteOtherV to set
- */
- public void setDeleteOtherV(String deleteOtherV) {
- logger.debug("Edge: "+this.getRuleKey());
- logger.debug("Truth: "+(("${direction}".equals(deleteOtherV)) ? "true" : "false"));
- logger.debug("Truth: "+(("!${direction}".equals(deleteOtherV)) ? "true" : "false"));
-
- if("${direction}".equals(deleteOtherV) ) {
- this.deleteOtherV = this.direction;
- } else if("!${direction}".equals(deleteOtherV) ) {
- this.deleteOtherV = this.direction.equals("IN") ? "OUT" : ((this.direction.equals("OUT")) ? "IN" : deleteOtherV);
- } else {
- this.deleteOtherV = deleteOtherV;
- }
- logger.debug("DeleteOtherV="+deleteOtherV+"/"+this.direction+"="+this.deleteOtherV);
- }
- /**
- * @return the preventDelete
- */
- public String getPreventDelete() {
- return preventDelete;
- }
- /**
- * @param preventDelete the preventDelete to set
- */
- public void setPreventDelete(String preventDelete) {
- if(this.getTo().equals("flavor") || this.getFrom().equals("flavor") ){
- logger.debug("Edge: "+this.getRuleKey());
- logger.debug("Truth: "+(("${direction}".equals(preventDelete)) ? "true" : "false"));
- logger.debug("Truth: "+(("!${direction}".equals(preventDelete)) ? "true" : "false"));
- }
-
- if("${direction}".equals(preventDelete) ) {
- this.preventDelete = this.direction;
- } else if("!${direction}".equals(preventDelete) ) {
- this.preventDelete = this.direction.equals("IN") ? "OUT" : ((this.direction.equals("OUT")) ? "IN" : preventDelete);
- } else {
- this.preventDelete = preventDelete;
- }
- if(this.getTo().equals("flavor") || this.getFrom().equals("flavor")) {
- logger.debug("PreventDelete="+preventDelete+"/"+this.direction+"="+this.preventDelete);
- }
- }
- /**
- * @return the to
- */
- public String getTo() {
- return to;
- }
- /**
- * @param to the to to set
- */
- public void setTo(String to) {
- this.to = to;
- }
- /**
- * @return the from
- */
- public String getFrom() {
- return from;
- }
- /**
- * @param from the from to set
- */
- public void setFrom(String from) {
- this.from = from;
- }
-
-
- public String getRuleKey() {
- return ruleKey;
- }
- public String getMultiplicity() {
- return multiplicity;
- }
- public String getDirection() {
- return direction;
- }
- public String getDescription() {
- return this.description;
- }
- public void setRuleKey(String val) {
- this.ruleKey=val;
- }
- public void setType(LineageType val) {
- this.type=val;
- }
- public void setDirection(String val) {
- this.direction = val;
- }
- public void setMultiplicity(String val) {
- this.multiplicity=val;
- }
- public void setHasDelTarget(String val) {
- hasDelTarget = Boolean.parseBoolean(val);
- }
- public void setDescription(String val) {
- this.description = val;
- }
-
- public String getRelationshipDescription(String fromTo, String otherNodeName) {
-
- String result = "";
-
- if ("FROM".equals(fromTo)) {
- if ("OUT".equals(direction)) {
- if (LineageType.PARENT == type) {
- result = " (PARENT of "+otherNodeName;
- result = String.join(" ", result+",", this.from, this.getLabel(), this.to);
- }
- }
- else {
- if (LineageType.CHILD == type) {
- result = " (CHILD of "+otherNodeName;
- result = String.join(" ", result+",", this.from, this.getLabel(), this.to);
- }
- else if (LineageType.PARENT == type) {
- result = " (PARENT of "+otherNodeName;
- result = String.join(" ", result+",", this.from, this.getLabel(), this.to);
- }
- }
- if (result.length() == 0) result = String.join(" ", "(", this.from, this.getLabel(), this.to+",", this.getMultiplicity());
- } else {
- //if ("TO".equals(fromTo)
- if ("OUT".equals(direction)) {
- if (LineageType.PARENT == type) {
- result = " (CHILD of "+otherNodeName;
- result = String.join(" ", result+",", this.from, this.getLabel(), this.to+",", this.getMultiplicity());
- }
- } else {
- if (LineageType.PARENT == type) {
- result = " (PARENT of "+otherNodeName;
- result = String.join(" ", result+",", this.from, this.getLabel(), this.to+",", this.getMultiplicity());
- }
- }
- if (result.length() == 0) result = String.join(" ", "(", this.from, this.getLabel(), this.to+",", this.getMultiplicity());
-
- }
-
- if (hasDelTarget) result = result + ", will delete target node";
-
- if (result.length() > 0) result = result + ")";
-
- if (description != null && description.length() > 0) result = result + "\n "+ description; // 6 spaces is important for yaml
-
- return result;
- }
-
- /**
- * @return the hasDelTarget
- */
- @SuppressWarnings("unused")
- public boolean isHasDelTarget() {
- return hasDelTarget;
- }
- /**
- * @param hasDelTarget the hasDelTarget to set
- */
- @SuppressWarnings("unused")
- public void setHasDelTarget(boolean hasDelTarget) {
- this.hasDelTarget = hasDelTarget;
- }
- /**
- * @return the type
- */
- @SuppressWarnings("unused")
- public LineageType getType() {
- return type;
- }
- /**
- * @return the label
- */
- public String getLabel() {
- return label;
- }
- public void setLabel(String string) {
- this.label=string;
- }
- }
-
- private static class PutRelationPathSet {
- String apiPath;
- String opId;
- ArrayList<String> relations = new ArrayList<String>();
- String objectName = "";
- String currentAPIVersion = "";
- public PutRelationPathSet(String opId, String path) {
- super();
- this.apiPath = path.replace("/relationship-list/relationship", "");
- this.opId = opId;
- objectName = GenerateXsd.deletePaths.get(apiPath);
- currentAPIVersion = GenerateXsd.apiVersion;
- }
- public void process() {
- this.toRelations();
- this.fromRelations();
- this.writeRelationsFile();
-
- }
- public void toRelations() {
- logger.debug("{“comment”: “Valid TO Relations that can be added”},");
- logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
- Collection<EdgeDescription> toEdges = GenerateXsd.getEdgeRulesTO(objectName);
-
- if(toEdges.size() > 0) {
- relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
- }
- for (EdgeDescription ed : toEdges) {
- logger.debug(ed.getRuleKey()+"Type="+ed.type);
- String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
- String selectedRelation = "";
- if(ed.type == 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);
- }
- relations.add(selectedRelation);
- logger.trace(selectedRelation);
- }
- }
-
- public void fromRelations() {
- logger.debug("“comment”: “Valid FROM Relations that can be added”");
- Collection<EdgeDescription> fromEdges = getEdgeRulesFROM(objectName);
- if(fromEdges.size() > 0) {
- relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
- }
- for (EdgeDescription ed : fromEdges) {
- logger.debug(ed.getRuleKey()+"Type="+ed.type);
- String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
- String selectedRelation = "";
- if(ed.type == 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);
- }
- relations.add(selectedRelation);
- logger.trace(selectedRelation);
- }
- }
- public void writeRelationsFile() {
- File examplefilePath = new File(yaml_dir + "/relations/" + currentAPIVersion+"/"+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;
- }
- 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<String, String> p : 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<String, String> p : 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;
- }
- }
-
- private static class PatchOperation {
- String useOpId;
- String xmlRootElementName;
- String tag;
- String path;
- 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;
- }
-
- @Override
- public String toString() {
- StringBuffer pathSb = new StringBuffer();
- pathSb.append(" patch:\n");
- pathSb.append(" tags:\n");
- pathSb.append(" - " + tag + "\n");
-
- pathSb.append(" summary: update an existing " + xmlRootElementName + "\n");
- pathSb.append(" description: update an existing " + xmlRootElementName + "\n");
- pathSb.append(" operationId: Update" + 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(" " + responsesUrl);
-
- 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\n");
- pathSb.append(" required: true\n");
- pathSb.append(" schema:\n");
- pathSb.append(" $ref: \"patchSchema.yaml#/definitions/" + xmlRootElementName + "\"\n");
-
- return pathSb.toString();
- }
- public String toString1() {
- 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.apiVersion+"/"+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(" - 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(" " + responsesUrl);
- 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");
- pathSb.append(" $ref: \"#/patchDefinitions/" + xmlRootElementName + "\"\n");
- return pathSb.toString();
- }
- }
- private static class PutOperation {
- String useOpId;
- String xmlRootElementName;
- String tag;
- String path;
- String pathParams;
-
- public PutOperation(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() {
- 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/"+GenerateXsd.apiVersion+"/"+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(" " + responsesUrl);
-
- 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");
- pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n");
- return pathSb.toString();
- }
- public String tagRelationshipPathMapEntry() {
- if ( path.endsWith("/relationship") ) {
- putRelationPaths.put(useOpId, path);
- }
- return "";
- }
-
- }
-
- private static class GetOperation {
- String useOpId;
- String xmlRootElementName;
- String tag;
- String path;
- @SuppressWarnings("unused")
- String pathParams;
- 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;
- }
- @Override
- public String toString() {
- 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(" " + responsesUrl);
-
- return pathSb.toString();
- }
-
- }
- private static class DeleteOperation {
- String useOpId;
- String xmlRootElementName;
- String tag;
- String path;
- String pathParams;
- 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() {
- 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(" " + responsesUrl);
- 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");
- }
- return pathSb.toString();
- }
- public String objectPathMapEntry() {
- if (! path.endsWith("/relationship") ) {
- deletePaths.put(path, xmlRootElementName);
- }
- return (xmlRootElementName+":"+path);
- }
-
- }
-
private static boolean validVersion(String versionToGen) {
if ("ALL".equalsIgnoreCase(versionToGen)) {
@@ -738,6 +101,18 @@ public class GenerateXsd {
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();
@@ -768,7 +143,7 @@ public class GenerateXsd {
Collections.sort(versionsToGen);
Collections.reverse(versionsToGen);
} else {
- versionsToGen.add(Version.valueOf(versionToGen));
+ versionsToGen.add(Version.getVersion(versionToGen));
}
//process file type System property
@@ -795,31 +170,46 @@ public class GenerateXsd {
String outfileName;
File outfile;
- String fileContent;
+ String fileContent = null;
for (Version v : versionsToGen) {
apiVersion = v.toString();
- logger.info("Generating " + apiVersion + " " + fileTypeToGen);
+ logger.debug("YAMLdir = "+yaml_dir);
+ logger.debug("Generating " + apiVersion + " " + fileTypeToGen);
File oxm_file = new File(oxmPath + "aai_oxm_" + apiVersion + ".xml");
apiVersionFmt = "." + apiVersion + ".";
generatedJavaType = new HashMap<String, String>();
appliedPaths = new HashMap<String, String>();
- putRelationPaths = new HashMap<String, String>();
- deletePaths = new HashMap<String, String>();
-
+ File edgeRuleFile = null;
+ logger.debug("user.dir = "+System.getProperty("user.dir"));
+ if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
+ edgeRuleFile = new File(normalStartDir + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ }
+ else {
+ edgeRuleFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ }
+
if ( fileTypeToGen.equals(generateTypeXSD) ) {
useAnnotationsInXsd = versionUsesAnnotations(apiVersion);
outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD;
- fileContent = processOxmFile(oxm_file, v, null);
- } else if ( versionSupportsSwagger(apiVersion )) {
- if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
- outfileName = alt_yaml_dir;
+ try {
+ HTMLfromOXM swagger = new HTMLfromOXM(oxm_file, v);
+ fileContent = swagger.process();
+ } catch(Exception e) {
+ logger.error( "Exception creating output file " + outfileName);
+ logger.error( e.getMessage());
+ e.printStackTrace();
}
- else {
- outfileName = yaml_dir;
+ } else if ( versionSupportsSwagger(apiVersion )) {
+ outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML;
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(oxm_file, v, edgeRuleFile);
+ fileContent = swagger.process();
+ } catch(Exception e) {
+ logger.error( "Exception creating output file " + outfileName);
+ logger.error( e.getMessage());
+ e.printStackTrace();
}
- outfileName = outfileName + "/aai_swagger_" + apiVersion + "." + generateTypeYAML;
- fileContent = generateSwaggerFromOxmFile( oxm_file, null);
} else {
continue;
}
@@ -848,1310 +238,8 @@ public class GenerateXsd {
bw.close();
}
}
- logger.info( "GeneratedXSD successful, saved in " + outfileName);
- }
-
- }
-
-
- public static String processJavaTypeElement( String javaTypeName, Element javaTypeElement) {
-
- String xmlRootElementName = null;
-
- NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes");
- StringBuffer sb = new StringBuffer();
- if ( parentNodes.getLength() == 0 ) {
- logger.trace( "no java-attributes for java-type " + javaTypeName);
- return "";
-
- }
-
- 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();
- logger.trace("Found xml-root-element attribute: " + attrName + " with value: " + attrValue);
- if ( attrName.equals("name"))
- xmlRootElementName = attrValue;
- }
-
- Element parentElement = (Element)parentNodes.item(0);
- NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element");
- NodeList childNodes;
- Element childElement;
- String xmlElementWrapper;
-
- Element xmlElementElement;
- String addType;
- String elementName, elementType, elementIsKey, elementIsRequired, elementContainerType;
- StringBuffer sb1 = new StringBuffer();
- if ( xmlElementNodes.getLength() > 0 ) {
- sb1.append(" <xs:element name=\"" + xmlRootElementName + "\">\n");
- sb1.append(" <xs:complexType>\n");
- NodeList properties = GenerateXsd.locateXmlProperties(javaTypeElement);
- if (properties != null && useAnnotationsInXsd) {
- logger.trace("properties found for: " + xmlRootElementName);
- sb1.append(" <xs:annotation>\r\n");
- insertAnnotation(properties, false, "class", sb1, " ");
-
- sb1.append(" </xs:annotation>\r\n");
- } else {
- logger.trace("no properties found for: " + xmlRootElementName);
- }
- sb1.append(" <xs:sequence>\n");
- for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) {
-
- xmlElementElement = (Element)xmlElementNodes.item(i);
- childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper");
-
- xmlElementWrapper = null;
- if ( childNodes.getLength() > 0 ) {
- childElement = (Element)childNodes.item(0);
- // get name
- 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.equals("name")) {
- xmlElementWrapper = attrValue;
- logger.trace("found xml-element-wrapper " + xmlElementWrapper);
- }
- }
-
- }
- attributes = xmlElementElement.getAttributes();
- addType = null;
-
-
- elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null;
- for ( int j = 0; j < attributes.getLength(); ++j ) {
- Attr attr = (Attr) attributes.item(j);
- String attrName = attr.getNodeName();
-
- String attrValue = attr.getNodeValue();
- logger.trace("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue);
- if ( attrName.equals("name")) {
- elementName = attrValue;
- }
- if ( attrName.equals("type")) {
- elementType = attrValue;
- if ( attrValue.contains(apiVersionFmt) ) {
- addType = attrValue.substring(attrValue.lastIndexOf('.')+1);
- if ( !generatedJavaType.containsKey(addType) ) {
- generatedJavaType.put(addType, attrValue);
- sb.append(processJavaTypeElement( addType, getJavaTypeElement(addType) ));
- }
- }
-
- }
-
- if ( attrName.equals("xml-key")) {
- elementIsKey = attrValue;
- }
- if ( attrName.equals("required")) {
- elementIsRequired = attrValue;
- }
- if ( attrName.equals("container-type")) {
- elementContainerType = attrValue;
- }
- }
-
- if ( xmlElementWrapper != null ) {
- sb1.append(" <xs:element name=\"" + xmlElementWrapper +"\"");
- if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) {
- sb1.append(" minOccurs=\"0\"");
- }
- sb1.append(">\n");
- sb1.append(" <xs:complexType>\n");
- properties = GenerateXsd.locateXmlProperties(javaTypeElement);
- if (properties != null && useAnnotationsInXsd) {
- sb1.append(" <xs:annotation>\r\n");
- insertAnnotation(properties, false, "class", sb1, " ");
- sb1.append(" </xs:annotation>\r\n");
- } else {
- logger.trace("no properties found for: " + xmlElementWrapper);
- }
- sb1.append(" <xs:sequence>\n");
- sb1.append(" ");
- }
- if ("Nodes".equals(addType)) {
- logger.trace("Skipping nodes, temporary testing");
- continue;
- }
- if ( addType != null ) {
- sb1.append(" <xs:element ref=\"tns:" + getXmlRootElementName(addType) +"\"");
- } else {
- sb1.append(" <xs:element name=\"" + elementName +"\"");
- }
- if ( elementType.equals("java.lang.String"))
- sb1.append(" type=\"xs:string\"");
- if ( elementType.equals("java.lang.Long"))
- sb1.append(" type=\"xs:unsignedInt\"");
- if ( elementType.equals("java.lang.Integer"))
- sb1.append(" type=\"xs:int\"");
- if ( elementType.equals("java.lang.Boolean"))
- sb1.append(" type=\"xs:boolean\"");
- if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) {
- sb1.append(" minOccurs=\"0\"");
- }
- if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) {
- sb1.append(" maxOccurs=\"unbounded\"");
- }
- properties = GenerateXsd.locateXmlProperties(xmlElementElement);
- if (properties != null || elementIsKey != null) {
- sb1.append(">\n");
- if ( useAnnotationsInXsd ) {
- sb1.append(" <xs:annotation>\r\n");
- insertAnnotation(properties, elementIsKey != null, "field", sb1, " ");
- sb1.append(" </xs:annotation>\r\n");
- }
- if (xmlElementWrapper== null) {
- sb1.append(" </xs:element>\n");
- }
- } else {
- sb1.append("/>\n");
- }
- if ( xmlElementWrapper != null ) {
- sb1.append(" </xs:sequence>\n");
- sb1.append(" </xs:complexType>\n");
- sb1.append(" </xs:element>\n");
- }
- }
- sb1.append(" </xs:sequence>\n");
- sb1.append(" </xs:complexType>\n");
- sb1.append(" </xs:element>\n");
- }
-
- if ( xmlElementNodes.getLength() < 1 ) {
- sb.append(" <xs:element name=\"" + xmlRootElementName + "\">\n");
- sb.append(" <xs:complexType>\n");
- sb.append(" <xs:sequence/>\n");
- sb.append(" </xs:complexType>\n");
- sb.append(" </xs:element>\n");
- generatedJavaType.put(javaTypeName, null);
- return sb.toString();
- }
- sb.append( sb1 );
- return sb.toString();
- }
-
- private static void insertAnnotation(NodeList items, boolean isKey, String target, StringBuffer sb1, String indentation) {
- if (items != null || isKey) {
- List<String> metadata = new ArrayList<>();
-
- String name = "";
- String value = "";
- Element item = null;
- if (isKey) {
- metadata.add("isKey=true");
- }
- if (items != null) {
- for (int i = 0; i < items.getLength(); i++) {
- item = (Element)items.item(i);
- name = item.getAttribute("name");
- value = item.getAttribute("value");
- if (name.equals("abstract")) {
- name = "isAbstract";
- } else if (name.equals("extends")) {
- name = "extendsFrom";
- }
- metadata.add(name + "=\"" + value.replaceAll("&", "&amp;") + "\"");
- }
- }
- sb1.append(
- indentation + " <xs:appinfo>\r\n" +
- indentation + " <annox:annotate target=\""+target+"\">@org.onap.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")</annox:annotate>\r\n" +
- indentation + " </xs:appinfo>\r\n");
- }
-
- }
-
- private static Element getJavaTypeElement( 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))
- return javaTypeElement;
- }
- }
- logger.error( "oxm file format error, missing java-type " + javaTypeName);
- return (Element) null;
- }
-
- private static Element getJavaTypeElementSwagger( 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))
- return javaTypeElement;
- }
- }
- logger.error( "oxm file format error, missing java-type " + javaTypeName);
- return (Element) null;
- }
- private static 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);
- }
- }
- }
- }
- logger.error( "oxm file format error, missing java-type " + javaTypeName);
- return null;
- }
-
-
- public static String processOxmFile( File oxmFile, Version v, String xml )
- {
- if ( xml != null ){
- apiVersion = v.toString();
- useAnnotationsInXsd = true;
- apiVersionFmt = "." + apiVersion + ".";
- generatedJavaType = new HashMap<>();
- appliedPaths = new HashMap<>();
- }
- StringBuilder sb = new StringBuilder();
- logger.trace("processing starts");
- sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
- String namespace = "org.onap";
- if (v.compareTo(Version.v11) < 0) {
- namespace = "org.openecomp";
- }
- if ( useAnnotationsInXsd ) {
- sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/"
- + apiVersion + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + apiVersion + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
- + "\n"
- + "xmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\"\r\n" +
- " jaxb:version=\"2.1\" \r\n" +
- " xmlns:annox=\"http://annox.dev.java.net\" \r\n" +
- " jaxb:extensionBindingPrefixes=\"annox\">\n\n");
- } else {
-
- sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/"
- + apiVersion + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + apiVersion + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\n");
- }
-
- try {
-
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc;
-
- if ( xml == null ){
- doc = dBuilder.parse(oxmFile);
- } else {
- InputSource is = new InputSource(new StringReader(xml));
- doc = dBuilder.parse(is);
- }
- NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings");
- Element bindingElement;
- NodeList javaTypesNodes;
- Element javaTypesElement;
-
- Element javaTypeElement;
-
-
- if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) {
- logger.error( "missing <binding-nodes> in " + oxmFile );
- return null;
- }
-
- bindingElement = (Element) bindingsNodes.item(0);
- javaTypesNodes = bindingElement.getElementsByTagName("java-types");
- if ( javaTypesNodes.getLength() < 1 ) {
- logger.error( "missing <binding-nodes><java-types> in " + oxmFile );
- return null;
- }
- javaTypesElement = (Element) javaTypesNodes.item(0);
- javaTypeNodes = javaTypesElement.getElementsByTagName("java-type");
- if ( javaTypeNodes.getLength() < 1 ) {
- logger.error( "missing <binding-nodes><java-types><java-type> in " + oxmFile );
- return null;
- }
-
- String javaTypeName;
- String attrName, attrValue;
- Attr attr;
- for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) {
- javaTypeElement = (Element) javaTypeNodes.item(i);
- NamedNodeMap attributes = javaTypeElement.getAttributes();
- javaTypeName = null;
- for ( int j = 0; j < attributes.getLength(); ++j ) {
- attr = (Attr) attributes.item(j);
- attrName = attr.getNodeName();
- attrValue = attr.getNodeValue();
- if ( attrName.equals("name"))
- javaTypeName = attrValue;
- }
- if ( javaTypeName == null ) {
- logger.error( "<java-type> has no name attribute in " + oxmFile );
- return null;
- }
- if ("Nodes".equals(javaTypeName)) {
- logger.debug("skipping Nodes entry (temporary feature)");
- continue;
- }
- if ( !generatedJavaType.containsKey(javaTypeName) ) {
- generatedJavaType.put(javaTypeName, null);
- sb.append(processJavaTypeElement( javaTypeName, javaTypeElement ));
- }
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- sb.append("</xs:schema>\n");
- return sb.toString();
- }
-
- public static String toDeleteRules(String objectName) {
- Collection<EdgeDescription> toEdges = GenerateXsd.getEdgeRulesTO(objectName);
- logger.debug("TO Edges count: "+toEdges.size()+" Object: "+objectName);
- String prevent=null;
- String also=null;
- LinkedHashSet<String> preventDelete = new LinkedHashSet<String>();
- LinkedHashSet<String> alsoDelete = new LinkedHashSet<String>();
- for (EdgeDescription ed : toEdges) {
- logger.debug("{“comment”: From = "+ed.getFrom()+" To: "+ed.getTo()+" Object: "+objectName);
- logger.debug("{“comment”: Direction = "+ed.getDirection()+" PreventDelete: "+ed.getPreventDelete()+" DeleteOtherV: "+ed.getDeleteOtherV()+" Object: "+objectName);
- if(ed.getPreventDelete().equals("IN") && ed.getTo().equals(objectName)) {
- preventDelete.add(ed.getFrom().toUpperCase());
- }
- if(ed.getDeleteOtherV().equals("IN") && ed.getTo().equals(objectName) ) {
- alsoDelete.add(ed.getFrom().toUpperCase());
- }
- }
- if(preventDelete.size() > 0) {
- prevent = " - "+objectName.toUpperCase()+" cannot be deleted if linked to "+String.join(",",preventDelete);
- logger.info(prevent);
- }
- if(alsoDelete.size() > 0) {
- also = " - "+objectName.toUpperCase()+" is DELETED when these are DELETED "+String.join(",",alsoDelete);
- // This commented out line is better (gets who deletes what correct) but still not accurate.
- //also = " - Deletion of an instance of "+objectName.toUpperCase()+" causes instances of these directly related types to be DELETED ["+String.join(",",alsoDelete)+"]";
- logger.info(also);
- }
- return String.join((prevent == null || also == null) ? "" : "\n", prevent == null ? "" : prevent, also == null ? "" : also)+((prevent == null && also == null) ? "" : "\n");
- }
-
- public static String fromDeleteRules(String objectName) {
- Collection<EdgeDescription> fromEdges = GenerateXsd.getEdgeRulesFROM(objectName);
- LinkedHashSet<String> preventDelete = new LinkedHashSet <String>();
- LinkedHashSet<String> alsoDelete = new LinkedHashSet <String>();
- String prevent=null;
- String also=null;
- for (EdgeDescription ed : fromEdges) {
- logger.debug("{“comment”: From = "+ed.getFrom()+" To: "+ed.getTo()+" Object: "+objectName);
- logger.debug("{“comment”: Direction = "+ed.getDirection()+" PreventDelete: "+ed.getPreventDelete()+" DeleteOtherV: "+ed.getDeleteOtherV()+" Object: "+objectName);
- if(ed.getPreventDelete().equals("OUT") && ed.getFrom().equals(objectName)) {
- preventDelete.add(ed.getTo().toUpperCase());
- }
- if(ed.getDeleteOtherV().equals("OUT") && ed.getFrom().equals(objectName) ) {
- alsoDelete.add(ed.getTo().toUpperCase());
- }
- }
- if(preventDelete.size() > 0) {
- prevent = " - "+objectName.toUpperCase()+" cannot be deleted if linked to "+String.join(",",preventDelete);
- logger.info(prevent);
- }
- if(alsoDelete.size() > 0) {
- also = " - "+objectName.toUpperCase()+" deletion means associated objects of these types are also DELETED:"+String.join(",",alsoDelete);
- // This commented out line is better (gets who deletes what correct) but still not accurate.
- //also = " - Deletion of an instance of "+objectName.toUpperCase()+" causes instances of these directly related types to be DELETED ["+String.join(",",alsoDelete)+"]";
- logger.info(also);
- }
- return String.join((prevent == null || also == null) ? "" : "\n", prevent == null ? "" : prevent, also == null ? "" : also)+((prevent == null && also == null) ? "" : "\n");
- }
-
-
- private static boolean isStandardType( String elementType )
- {
- switch ( elementType ) {
- case "java.lang.String":
- case "java.lang.Long":
- case "java.lang.Integer":
- case"java.lang.Boolean":
- return true;
- }
- return false;
- }
-
- private static Vector<String> getIndexedProps( String attrValue )
- {
- if ( attrValue == null )
- return null;
- StringTokenizer st = new StringTokenizer( attrValue, ",");
- if ( st.countTokens() == 0 )
- return null;
- Vector<String> result = new Vector<String>();
- while ( st.hasMoreTokens()) {
- result.add(st.nextToken());
- }
- return result;
- }
-
- /**
- * Guaranteed to at least return non null but empty collection of edge descriptions
- * @param nodeName name of the vertex whose edge relationships to return
- * @return collection of node neighbors based on DbEdgeRules
- **/
- private static Collection<EdgeDescription> getEdgeRulesFromJson( String path, boolean skipMatch )
- {
-
- ArrayList<EdgeDescription> result = new ArrayList<>();
- Iterator<Map<String, Object>> edgeRulesIterator;
- try {
-
- GenerateXsd x = new GenerateXsd();
-
- List<Map<String, Object>> inEdges = JsonPath.parse(jsonEdges).read(path);
-
- edgeRulesIterator = inEdges.iterator();
- Map<String, Object> edgeMap;
- String fromNode;
- String toNode;
- String direction;
- String multiplicity;
- String isParent;
- String hasDelTarget;
- String deleteOtherV;
- String preventDelete;
- String description;
- EdgeDescription edgeDes;
-
- while( edgeRulesIterator.hasNext() ){
- edgeMap = edgeRulesIterator.next();
- fromNode = (String)edgeMap.get("from");
- toNode = (String)edgeMap.get("to");
- if ( skipMatch ) {
- if ( fromNode.equals(toNode)) {
- continue;
- }
- }
- edgeDes = x.new EdgeDescription();
- edgeDes.setRuleKey(fromNode + "|" + toNode);
- edgeDes.setLabel((String)edgeMap.get("label"));
- edgeDes.setTo((String)edgeMap.get("to"));
- edgeDes.setFrom((String)edgeMap.get("from"));
- direction = (String)edgeMap.get("direction");
- edgeDes.setDirection(direction);
- multiplicity = (String)edgeMap.get("multiplicity");
- edgeDes.setMultiplicity(multiplicity);
- isParent = (String)edgeMap.get(EdgeProperty.CONTAINS.toString());
- if ( "${direction}".equals(isParent)) {
- edgeDes.setType(LineageType.PARENT);
- } else {
- edgeDes.setType(LineageType.UNRELATED);
- }
- hasDelTarget = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString());
- deleteOtherV = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString());
- edgeDes.setDeleteOtherV(deleteOtherV);
- edgeDes.setHasDelTarget(hasDelTarget);
- preventDelete = (String)edgeMap.get(EdgeProperty.PREVENT_DELETE.toString());
- edgeDes.setPreventDelete(preventDelete);
- description = (String)edgeMap.get(EdgeProperty.DESCRIPTION.toString());
- edgeDes.setDescription(description);
-
- result.add(edgeDes);
- logger.debug("Edge: "+edgeDes.getRuleKey());
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- return result;
-
- }
-
- /**
- * Guaranteed to at least return non null but empty collection of edge descriptions
- * @param nodeName name of the vertex whose edge relationships to return
- * @return collection of node neighbors based on DbEdgeRules
- **/
- private static Collection<EdgeDescription> getEdgeRules( String nodeName )
- {
- String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]";
- String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]";
- Collection<EdgeDescription> fromEdges = getEdgeRulesFromJson( fromRulesPath, false );
- Collection<EdgeDescription> edges = getEdgeRulesFromJson( toRulesPath, true );
- edges.addAll(fromEdges);
- return edges;
- }
-
- private static Collection<EdgeDescription> getEdgeRulesTO( String nodeName )
- {
- String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]";
- Collection<EdgeDescription> edges = getEdgeRulesFromJson( toRulesPath, true );
- return edges;
- }
-
- private static Collection<EdgeDescription> getEdgeRulesFROM( String nodeName )
- {
- String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]";
- Collection<EdgeDescription> edges = getEdgeRulesFromJson( fromRulesPath, true );
- return edges;
- }
- public static String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement,
- StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId,
- String getItemName, StringBuffer pathParams, String queryParams, String validEdges) {
-
- String xmlRootElementName = null;
- StringBuilder definitionsLocalSb = new StringBuilder(256);
-
- String useTag = null;
- String useOpId = null;
-
- if ( tag != null ) {
- switch ( tag ) {
- case "Network":
- case "ServiceDesignAndCreation":
- case "Business":
- case "LicenseManagement":
- case "CloudInfrastructure":
- break;
- default:
- 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;
- }
-
- NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes");
-
- if ( parentNodes.getLength() == 0 ) {
- logger.trace( "no java-attributes for java-type " + javaTypeName);
- return "";
- }
-
- 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();
- logger.trace("Found xml-root-element attribute: " + attrName + " with value: " + attrValue);
- if ( attrName.equals("name"))
- xmlRootElementName = attrValue;
- }
-
- NodeList childNodes;
- Element childElement;
- NodeList xmlPropNodes = javaTypeElement.getElementsByTagName("xml-properties");
- Element xmlPropElement;
- String pathDescriptionProperty = null;
-
-
- Vector<String> indexedProps = null;
-
- if ( xmlPropNodes.getLength() > 0 ) {
-
- for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) {
- xmlPropElement = (Element)xmlPropNodes.item(i);
- if ( !xmlPropElement.getParentNode().isSameNode(javaTypeElement))
- continue;
- childNodes = xmlPropElement.getElementsByTagName("xml-property");
-
- if ( childNodes.getLength() > 0 ) {
- for ( int j = 0; j < childNodes.getLength(); ++j ) {
- childElement = (Element)childNodes.item(j);
- // get name
- int useValue = VALUE_NONE;
- 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;
- }
- if ( attrValue.equals("indexedProps")) {
- useValue = VALUE_INDEXED_PROPS;
- }
- if ( useValue == VALUE_INDEXED_PROPS && attrName.equals("value")) {
- indexedProps = getIndexedProps( attrValue );
- }
- }
- }
- }
- }
- }
- logger.trace("javaTypeName " + javaTypeName + " description " + pathDescriptionProperty);
-
- Element parentElement = (Element)parentNodes.item(0);
- NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element");
-
-
- String attrDescription = null;
-
- Element xmlElementElement;
- String addType = null;
- String elementType = null, elementIsKey = null, elementIsRequired, elementContainerType = null;
- String elementName = null;
- StringBuffer sbParameters = new StringBuffer();
-
- StringBuffer sbRequired = new StringBuffer();
- int requiredCnt = 0;
- int propertyCnt = 0;
- StringBuffer sbProperties = new StringBuffer();
- StringBuffer sbIndexedParams = new StringBuffer();
-
-
- StringTokenizer st;
- if ( xmlRootElementName.equals("inventory"))
- path = "";
- else if ( path == null )
- path = "/" + xmlRootElementName;
- else
- path += "/" + xmlRootElementName;
- st = new StringTokenizer(path, "/");
- boolean genPath = false;
-
- if ( st.countTokens() > 1 && getItemName == null ) {
- if ( appliedPaths.containsKey(path))
- return null;
- appliedPaths.put(path, xmlRootElementName);
- genPath = true;
- if ( path.contains("/relationship/") ) { // filter paths with relationship-list
- genPath = false;
- }
- if ( path.endsWith("/relationship-list")) {
- genPath = false;
- }
-
- }
-
- Vector<String> addTypeV = null;
- if ( xmlElementNodes.getLength() > 0 ) {
-
- for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) {
- xmlElementElement = (Element)xmlElementNodes.item(i);
- if ( !xmlElementElement.getParentNode().isSameNode(parentElement))
- continue;
-
- valNodes = xmlElementElement.getElementsByTagName("xml-properties");
- attrDescription = null;
- if ( valNodes.getLength() > 0 ) {
- for ( int j = 0; j < valNodes.getLength(); ++j ) {
- valElement = (Element)valNodes.item(j);
- if ( !valElement.getParentNode().isSameNode(xmlElementElement))
- continue;
- childNodes = valElement.getElementsByTagName("xml-property");
- if ( childNodes.getLength() > 0 ) {
- childElement = (Element)childNodes.item(0);
- // get name
- attributes = childElement.getAttributes();
- attrDescription = null;
- boolean useValue = false;
- for ( int k = 0; k < attributes.getLength(); ++k ) {
- Attr attr = (Attr) attributes.item(k);
- String attrName = attr.getNodeName();
- String attrValue = attr.getNodeValue();
- if ( attrName.equals("name") && attrValue.equals("description")) {
- useValue = true;
- }
- if ( useValue && attrName.equals("value")) {
- attrDescription = attrValue;
- }
- }
-
- }
- }
- }
-
- attributes = xmlElementElement.getAttributes();
- addTypeV = null; // vector of 1
- addType = null;
-
- elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null;
- for ( int j = 0; j < attributes.getLength(); ++j ) {
- Attr attr = (Attr) attributes.item(j);
- String attrName = attr.getNodeName();
-
- String attrValue = attr.getNodeValue();
- logger.trace("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue);
- if ( attrName.equals("name")) {
- elementName = attrValue;
-
- }
- if ( attrName.equals("type") && getItemName == null ) {
- elementType = attrValue;
- if ( attrValue.contains(apiVersionFmt) ) {
- addType = attrValue.substring(attrValue.lastIndexOf('.')+1);
- if ( addTypeV == null )
- addTypeV = new Vector<String>();
- addTypeV.add(addType);
- }
-
- }
- if ( attrName.equals("xml-key")) {
- elementIsKey = attrValue;
- path += "/{" + elementName + "}";
- }
- if ( attrName.equals("required")) {
- elementIsRequired = attrValue;
- }
- if ( attrName.equals("container-type")) {
- elementContainerType = attrValue;
- }
- }
- if ( getItemName != null ) {
- if ( getItemName.equals("array") ) {
- if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) {
- logger.trace( " returning array " + elementName );
- return elementName;
- }
-
- } else { // not an array check
- if ( elementContainerType == null || !elementContainerType.equals("java.util.ArrayList")) {
- logger.trace( " returning object " + elementName );
- return elementName;
- }
-
- }
- logger.trace( " returning null" );
- return null;
- }
- if ( elementIsRequired != null ) {
- if ( requiredCnt == 0 )
- sbRequired.append(" required:\n");
- ++requiredCnt;
- if ( addTypeV != null ) {
- for ( int k = 0; k < addTypeV.size(); ++i ) {
- sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n");
- }
- } else
- sbRequired.append(" - " + elementName + "\n");
-
- }
-
- if ( elementIsKey != null ) {
- sbParameters.append((" - name: " + elementName + "\n"));
- sbParameters.append((" in: path\n"));
- if ( attrDescription != null && attrDescription.length() > 0 )
- sbParameters.append((" description: " + attrDescription + "\n"));
- sbParameters.append((" required: true\n"));
- if ( elementType.equals("java.lang.String"))
- sbParameters.append(" type: string\n");
- if ( elementType.equals("java.lang.Long")) {
- sbParameters.append(" type: integer\n");
- sbParameters.append(" format: int64\n");
- }
- if ( elementType.equals("java.lang.Integer")) {
- sbParameters.append(" type: integer\n");
- sbParameters.append(" format: int32\n");
- }
- if ( elementType.equals("java.lang.Boolean")) {
- sbParameters.append(" type: boolean\n");
- }
- if(StringUtils.isNotBlank(elementName)) {
- sbParameters.append(" example: "+"__"+elementName.toUpperCase()+"__"+"\n");
- }
- } else if ( indexedProps != null
- && indexedProps.contains(elementName ) ) {
- sbIndexedParams.append((" - name: " + elementName + "\n"));
- sbIndexedParams.append((" in: query\n"));
- if ( attrDescription != null && attrDescription.length() > 0 )
- sbIndexedParams.append((" description: " + attrDescription + "\n"));
- sbIndexedParams.append((" required: false\n"));
- if ( elementType.equals("java.lang.String"))
- sbIndexedParams.append(" type: string\n");
- if ( elementType.equals("java.lang.Long")) {
- sbIndexedParams.append(" type: integer\n");
- sbIndexedParams.append(" format: int64\n");
- }
- if ( elementType.equals("java.lang.Integer")) {
- sbIndexedParams.append(" type: integer\n");
- sbIndexedParams.append(" format: int32\n");
- }
- if ( elementType.equals("java.lang.Boolean"))
- sbIndexedParams.append(" type: boolean\n");
- }
- if ( isStandardType(elementType)) {
- sbProperties.append(" " + elementName + ":\n");
- ++propertyCnt;
- sbProperties.append(" type: ");
-
- if ( elementType.equals("java.lang.String"))
- sbProperties.append("string\n");
- else if ( elementType.equals("java.lang.Long")) {
- sbProperties.append("integer\n");
- sbProperties.append(" format: int64\n");
- }
- else if ( elementType.equals("java.lang.Integer")){
- sbProperties.append("integer\n");
- sbProperties.append(" format: int32\n");
- }
- else if ( elementType.equals("java.lang.Boolean"))
- sbProperties.append("boolean\n");
- if ( attrDescription != null && attrDescription.length() > 0 )
- sbProperties.append(" description: " + attrDescription + "\n");
- }
-
- if ( addTypeV != null ) {
- StringBuffer newPathParams = null;
- if ( pathParams != null ) {
- newPathParams = new StringBuffer();
- newPathParams.append(pathParams);
- }
- if ( sbParameters.toString().length() > 0 ) {
- if ( newPathParams == null )
- newPathParams = new StringBuffer();
- newPathParams.append(sbParameters);
- }
- String newQueryParams = null;
- if ( sbIndexedParams.toString().length() > 0 ) {
- if ( queryParams == null )
- newQueryParams = sbIndexedParams.toString();
- else
- newQueryParams = queryParams + sbIndexedParams.toString();
- } else {
- newQueryParams = queryParams;
- }
- for ( int k = 0; k < addTypeV.size(); ++k ) {
- addType = addTypeV.elementAt(k);
-
- if ( opId == null || !opId.contains(addType)) {
- processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType),
- pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null,
- newPathParams, newQueryParams, validEdges);
- }
- // need item name of array
- String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType),
- pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId,
- "array", null, 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 ( attrDescription != null && attrDescription.length() > 0 )
- sbProperties.append(" description: " + attrDescription + "\n");
- }
- } else {
- if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) {
- // need properties for getXmlRootElementName(addType)
- newPathParams = null;
- if ( pathParams != null ) {
- newPathParams = new StringBuffer();
- newPathParams.append(pathParams);
- }
- if ( sbParameters.toString().length() > 0 ) {
- if ( newPathParams == null )
- newPathParams = new StringBuffer();
- newPathParams.append(sbParameters);
- }
- newQueryParams = null;
- if ( sbIndexedParams.toString().length() > 0 ) {
- if ( queryParams == null )
- newQueryParams = sbIndexedParams.toString();
- else
- newQueryParams = queryParams + sbIndexedParams.toString();
- } else {
- newQueryParams = queryParams;
- }
- processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType),
- pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId,
- null, newPathParams, newQueryParams, validEdges );
- sbProperties.append(" " + getXmlRootElementName(addType) + ":\n");
- sbProperties.append(" type: array\n items: \n");
- sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n");
- } else {
- sbProperties.append(" " + getXmlRootElementName(addType) + ":\n");
- sbProperties.append(" type: object\n");
- sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n");
- }
- if ( attrDescription != null && attrDescription.length() > 0 )
- sbProperties.append(" description: " + attrDescription + "\n");
- ++propertyCnt;
- }
- }
- }
- }
- }
- if ( genPath ) {
- if ( !path.endsWith("/relationship") ) {
- GetOperation get = new GetOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString());
- pathSb.append(get.toString());
-// if ( path.indexOf('{') > 0 ) {
-
- if ( sbParameters.toString().length() > 0 ) {
- if ( pathParams == null )
- pathParams = new StringBuffer();
- pathParams.append(sbParameters);
- }
- if ( pathParams != null) {
- pathSb.append(" parameters:\n");
- pathSb.append(pathParams);
- } else
- logger.trace( "null pathParams for " + useOpId);
- if ( sbIndexedParams.toString().length() > 0 ) {
- if ( queryParams == null )
- queryParams = sbIndexedParams.toString();
- else
- queryParams = queryParams + sbIndexedParams.toString();
- }
- if ( queryParams != null ) {
- if ( pathParams == null ) {
- pathSb.append(" parameters:\n");
- }
- pathSb.append(queryParams);
- }
-// }
- }
- boolean skipPutDelete = false; // no put or delete for "all"
- if ( !path.endsWith("/relationship") ) {
- if ( !path.endsWith("}") ){
- skipPutDelete = true;
- }
-
- }
- if ( path.indexOf('{') > 0 && !opId.startsWith("Search") &&!skipPutDelete) {
- // add PUT
- PutOperation put = new PutOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString());
- pathSb.append(put.toString());
- if ( !path.endsWith("/relationship") ) {
- PatchOperation patch = new PatchOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString());
- pathSb.append(patch.toString1());
- }
- logger.debug(put.tagRelationshipPathMapEntry());
-
- // add DELETE
- DeleteOperation del = new DeleteOperation(useOpId, xmlRootElementName, tag, path, pathParams == null ? "" : pathParams.toString());
- pathSb.append(del.toString());
- logger.debug(del.objectPathMapEntry());
- }
-
- }
- if ( generatedJavaType.containsKey(xmlRootElementName) ) {
- return null;
- }
-
- definitionsSb.append(" " + xmlRootElementName + ":\n");
- definitionsLocalSb.append(" " + xmlRootElementName + ":\n");
- Collection<EdgeDescription> edges = getEdgeRules(xmlRootElementName );
-
- if ( edges.size() > 0 ) {
- StringBuffer sbEdge = new StringBuffer();
- sbEdge.append(" ###### Related Nodes\n");
- for (EdgeDescription ed : edges) {
- if ( ed.getRuleKey().startsWith(xmlRootElementName)) {
- sbEdge.append(" - TO ").append(ed.getRuleKey().substring(ed.getRuleKey().indexOf("|")+1));
- sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName));
- sbEdge.append("\n");
- }
- }
- for (EdgeDescription ed : edges) {
- if ( ed.getRuleKey().endsWith(xmlRootElementName)) {
- sbEdge.append(" - FROM ").append(ed.getRuleKey().substring(0, ed.getRuleKey().indexOf("|")));
- sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName));
- sbEdge.append("\n");
- }
- }
- // Delete rule processing is incorrect. One cannot express the delete rules in isolation from the
- // specific edge. Take the case of allotted-resource and service-instance. When the service-instance owns the
- // allotted-resource, yes, it deletes it. But when the service-instance only uses the allotted-resource, the deletion
- // of the service instance does not cause the deletion of the allotted-resource.
- // I put some lines into the toDeleteRules and fromDeleteRules to correct things to an extent, but it's still
- // not right.
- sbEdge.append(toDeleteRules(xmlRootElementName));
- sbEdge.append(fromDeleteRules(xmlRootElementName));
- 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 (pathDescriptionProperty != null || validEdges != null) {
- definitionsSb.append(" description: |\n");
- definitionsLocalSb.append(" description: |\n");
-
- if ( pathDescriptionProperty != null ) {
- definitionsSb.append(" " + pathDescriptionProperty + "\n" );
- definitionsLocalSb.append(" " + pathDescriptionProperty + "\n" );
- }
- if (validEdges != null) {
- 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);
- definitionsLocalSb.append(" properties:\n");
- definitionsLocalSb.append(sbProperties);
- }
- try {
- javaTypeDefinitions.put(xmlRootElementName, definitionsLocalSb.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- generatedJavaType.put(xmlRootElementName, null);
- return null;
- }
-
- public static void generateRelations() {
- if(putRelationPaths == null)
- return;
- 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);
- prp.process();
- });
- }
-
- public static String generateSwaggerFromOxmFile( File oxmFile, String xml )
- {
- if ( xml != null ){
- apiVersion = Version.getLatest().toString();
- apiVersionFmt = "." + apiVersion + ".";
- generatedJavaType = new HashMap<>();
- appliedPaths = new HashMap<>();
- responsesUrl = "Description: response-label\n";
- }
- StringBuffer sb = new StringBuffer();
- sb.append("swagger: \"2.0\"\ninfo:\n ");
- sb.append("description: |");
- sb.append("\n\n [Differences versus the previous schema version]("+"apidocs/aai_swagger_" + apiVersion + ".diff)");
- sb.append("\n\n Copyright &copy; 2017 AT&amp;T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the &quot;License&quot;); 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 &quot;AS IS&quot; 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 ECOMP and OpenECOMP are trademarks and service marks of AT&amp;T Intellectual Property.\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: \"" + apiVersion +"\"\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: /aai/" + apiVersion + "\n");
- sb.append("schemes:\n - https\npaths:\n");
-
- try {
- File initialFile;
- if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
- initialFile = new File(normalStartDir + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
- }
- else {
- initialFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
- }
- InputStream is = new FileInputStream(initialFile);
-
- Scanner scanner = new Scanner(is);
- jsonEdges = scanner.useDelimiter("\\Z").next();
- scanner.close();
- is.close();
-
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc;
-
- if ( xml == null ) {
- doc = dBuilder.parse(oxmFile);
- } else {
- InputSource isInput = new InputSource(new StringReader(xml));
- doc = dBuilder.parse(isInput);
- }
-
- NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings");
- Element bindingElement;
- NodeList javaTypesNodes;
- Element javaTypesElement;
-
- Element javaTypeElement;
-
-
- if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) {
- logger.error( "missing <binding-nodes> in " + oxmFile );
- return null;
- }
-
- bindingElement = (Element) bindingsNodes.item(0);
- javaTypesNodes = bindingElement.getElementsByTagName("java-types");
- if ( javaTypesNodes.getLength() < 1 ) {
- logger.error( "missing <binding-nodes><java-types> in " + oxmFile );
- return null;
- }
- javaTypesElement = (Element) javaTypesNodes.item(0);
-
- javaTypeNodes = javaTypesElement.getElementsByTagName("java-type");
- if ( javaTypeNodes.getLength() < 1 ) {
- logger.error( "missing <binding-nodes><java-types><java-type> in " + oxmFile );
- return null;
- }
-
- String javaTypeName;
- String attrName, attrValue;
- Attr attr;
- StringBuffer pathSb = new StringBuffer();
-
- StringBuffer definitionsSb = new StringBuffer();
- for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) {
- javaTypeElement = (Element) javaTypeNodes.item(i);
- NamedNodeMap attributes = javaTypeElement.getAttributes();
- javaTypeName = null;
- for ( int j = 0; j < attributes.getLength(); ++j ) {
- attr = (Attr) attributes.item(j);
- attrName = attr.getNodeName();
- attrValue = attr.getNodeValue();
- if ( attrName.equals("name"))
- javaTypeName = attrValue;
- }
- if ( javaTypeName == null ) {
- logger.error( "<java-type> has no name attribute in " + oxmFile );
- return null;
- }
- if ( !generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)) ) {
-
- processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb,
- definitionsSb, null, null, null, null, null, null, null);
- }
- }
- sb.append(pathSb);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- //append definitions
- sb.append("definitions:\n");
- Map<String, String> sortedJavaTypeDefinitions = new TreeMap<String, String>(javaTypeDefinitions);
- for (Map.Entry<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
- logger.debug("Key: "+entry.getKey()+"Test: "+ (entry.getKey() == "relationship"));
- if(entry.getKey().matches("relationship")) {
- 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<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
- 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<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
- String jb=entry.getValue().replaceAll("/definitions/", "/getDefinitions/");
- sb.append(jb);
- }
-
- logger.debug("generated " + sb.toString());
- generateRelations();
- return sb.toString();
- }
-
- private static NodeList locateXmlProperties(Element element) {
- XPathExpression expr;
- NodeList result = null;
- try {
- expr = xpath.compile("xml-properties");
- if (expr != null) {
- Object nodeset = expr.evaluate(element, XPathConstants.NODESET);
- if (nodeset != null) {
- NodeList nodes = (NodeList) nodeset;
- if (nodes != null && nodes.getLength() > 0) {
- Element xmlProperty = (Element)nodes.item(0);
- result = xmlProperty.getElementsByTagName("xml-property");
- }
- }
- }
- } catch (XPathExpressionException e) {
- e.printStackTrace();
+ logger.debug( "GeneratedXSD successful, saved in " + outfileName);
}
- return result;
}
} \ No newline at end of file
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
new file mode 100644
index 00000000..dca5b7ce
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteFootnoteSet.java
@@ -0,0 +1,57 @@
+/**
+ * ============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<String> footnotes = new TreeSet<>();
+ protected String targetNode = "<NodeType>";
+ 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
new file mode 100644
index 00000000..0651566e
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/DeleteOperation.java
@@ -0,0 +1,106 @@
+/**
+ * ============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.util.GenerateXsd;
+
+import java.util.HashMap;
+import java.util.StringTokenizer;
+
+public class DeleteOperation {
+ private String useOpId;
+ private String xmlRootElementName;
+ private String tag;
+ private String path;
+ private String pathParams;
+
+ public static HashMap<String, String> deletePaths = new HashMap<String, String>();
+ 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
new file mode 100644
index 00000000..6e1294ab
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeDescription.java
@@ -0,0 +1,242 @@
+/**
+ * ============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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class EdgeDescription {
+ private static final Logger logger = LoggerFactory.getLogger("EdgeDescription.class");
+
+ public static enum LineageType {
+ PARENT, CHILD, UNRELATED;
+ }
+ private String ruleKey;
+ private String to;
+ private String from;
+ private LineageType type = LineageType.UNRELATED;
+ private String direction;
+ private String multiplicity;
+ private String preventDelete;
+ private String deleteOtherV;
+ private String label;
+ private String description;
+ /**
+ * @return the deleteOtherV
+ */
+ public String getDeleteOtherV() {
+ return deleteOtherV;
+ }
+ /**
+ * @param deleteOtherV the deleteOtherV to set
+ */
+ public void setDeleteOtherV(String deleteOtherV) {
+ logger.debug("Edge: "+this.getRuleKey());
+ logger.debug("Truth: "+(("${direction}".equals(deleteOtherV)) ? "true" : "false"));
+ logger.debug("Truth: "+(("!${direction}".equals(deleteOtherV)) ? "true" : "false"));
+
+ if("${direction}".equals(deleteOtherV) ) {
+ this.deleteOtherV = this.direction;
+ } else if("!${direction}".equals(deleteOtherV) ) {
+ this.deleteOtherV = this.direction.equals("IN") ? "OUT" : ((this.direction.equals("OUT")) ? "IN" : deleteOtherV);
+ } else {
+ this.deleteOtherV = deleteOtherV;
+ }
+ logger.debug("DeleteOtherV="+deleteOtherV+"/"+this.direction+"="+this.deleteOtherV);
+ }
+ /**
+ * @return the preventDelete
+ */
+ public String getPreventDelete() {
+ return preventDelete;
+ }
+ /**
+ * @param preventDelete the preventDelete to set
+ */
+ public void setPreventDelete(String preventDelete) {
+ if(this.getTo().equals("flavor") || this.getFrom().equals("flavor") ){
+ logger.debug("Edge: "+this.getRuleKey());
+ logger.debug("Truth: "+(("${direction}".equals(preventDelete)) ? "true" : "false"));
+ logger.debug("Truth: "+(("!${direction}".equals(preventDelete)) ? "true" : "false"));
+ }
+
+ if("${direction}".equals(preventDelete) ) {
+ this.preventDelete = this.direction;
+ } else if("!${direction}".equals(preventDelete) ) {
+ this.preventDelete = this.direction.equals("IN") ? "OUT" : ((this.direction.equals("OUT")) ? "IN" : preventDelete);
+ } else {
+ this.preventDelete = preventDelete;
+ }
+ }
+ public String getAlsoDeleteFootnote(String targetNode) {
+ String returnVal = "";
+ if(this.deleteOtherV.equals("IN") && this.to.equals(targetNode) ) {
+ logger.debug("Edge: "+this.getRuleKey());
+ logger.debug("IF this "+targetNode+" node is deleted, this FROM node is DELETED also");
+ returnVal = "(1)";
+ }
+ if(this.deleteOtherV.equals("OUT") && this.from.equals(targetNode) ) {
+ logger.debug("Edge: "+this.getRuleKey());
+ logger.debug("IF this "+targetNode+" is deleted, this TO node is DELETED also");
+ returnVal = "(2)";
+ }
+ if(this.deleteOtherV.equals("OUT") && this.to.equals(targetNode) ) {
+ logger.debug("Edge: "+this.getRuleKey());
+ logger.debug("IF this FROM node is deleted, this "+targetNode+" is DELETED also");
+ returnVal = "(3)";
+ }
+ if(this.deleteOtherV.equals("IN") && this.from.equals(targetNode) ) {
+ logger.debug("Edge: "+this.getRuleKey());
+ 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 to;
+ }
+ /**
+ * @param to the to to set
+ */
+ public void setTo(String to) {
+ this.to = to;
+ }
+ /**
+ * @return the from
+ */
+ public String getFrom() {
+ return from;
+ }
+ /**
+ * @param from the from to set
+ */
+ public void setFrom(String from) {
+ this.from = from;
+ }
+
+
+ public String getRuleKey() {
+ return ruleKey;
+ }
+ public String getMultiplicity() {
+ return multiplicity;
+ }
+ public String getDirection() {
+ return direction;
+ }
+ public String getDescription() {
+ return this.description;
+ }
+ public void setRuleKey(String val) {
+ this.ruleKey=val;
+ }
+ public void setType(LineageType val) {
+ this.type=val;
+ }
+ public void setDirection(String val) {
+ this.direction = val;
+ }
+ public void setMultiplicity(String val) {
+ this.multiplicity=val;
+ }
+
+ public void setDescription(String val) {
+ this.description = val;
+ }
+
+ public String getRelationshipDescription(String fromTo, String otherNodeName) {
+
+ String result = "";
+
+ if ("FROM".equals(fromTo)) {
+ if ("OUT".equals(direction)) {
+ if (LineageType.PARENT == type) {
+ result = " (PARENT of "+otherNodeName;
+ result = String.join(" ", result+",", this.from, this.getShortLabel(), this.to);
+ }
+ }
+ else {
+ if (LineageType.CHILD == type) {
+ result = " (CHILD of "+otherNodeName;
+ result = String.join(" ", result+",", this.from, this.getShortLabel(), this.to);
+ }
+ else if (LineageType.PARENT == type) {
+ result = " (PARENT of "+otherNodeName;
+ result = String.join(" ", result+",", this.from, this.getShortLabel(), this.to);
+ }
+ }
+ if (result.length() == 0) result = String.join(" ", "(", this.from, this.getShortLabel(), this.to+",", this.getMultiplicity());
+ } else {
+ //if ("TO".equals(fromTo)
+ if ("OUT".equals(direction)) {
+ if (LineageType.PARENT == type) {
+ result = " (CHILD of "+otherNodeName;
+ result = String.join(" ", result+",", this.from, this.getShortLabel(), this.to+",", this.getMultiplicity());
+ }
+ } else {
+ if (LineageType.PARENT == type) {
+ result = " (PARENT of "+otherNodeName;
+ result = String.join(" ", result+",", this.from, this.getShortLabel(), this.to+",", this.getMultiplicity());
+ }
+ }
+ if (result.length() == 0) result = String.join(" ", "(", this.from, this.getShortLabel(), this.to+",", this.getMultiplicity());
+ }
+// Confusing...
+// if (hasDelTarget()) result = result + ", will delete target node";
+
+ if (result.length() > 0) result = result + ")";
+
+ if (description != null && description.length() > 0) result = result + "\n "+ description; // 6 spaces is important for yaml
+
+ return result;
+ }
+
+ /**
+ * @return the hasDelTarget
+ */
+
+ public boolean hasDelTarget() {
+ return StringUtils.isNotEmpty(this.deleteOtherV) && (! "NONE".equalsIgnoreCase(this.deleteOtherV));
+ }
+
+ /**
+ * @return the type
+ */
+ public LineageType getType() {
+ return type;
+ }
+ /**
+ * @return the label
+ */
+ public String getLabel() {
+ return label;
+ }
+ public String getShortLabel() {
+ String[] pieces = this.getLabel().split("[.]");
+ return pieces[pieces.length-1];
+ }
+ public void setLabel(String string) {
+ this.label=string;
+ }
+} \ No newline at end of file
diff --git a/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeRuleSet.java b/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeRuleSet.java
new file mode 100644
index 00000000..f3ef298a
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/EdgeRuleSet.java
@@ -0,0 +1,196 @@
+/**
+ * ============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 com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.onap.aai.serialization.db.EdgeProperty;
+
+import java.io.*;
+import java.util.*;
+
+public class EdgeRuleSet {
+ private File edgeFile;
+ private DocumentContext jsonContext;
+
+ public EdgeRuleSet(File edgeFile) throws IOException,FileNotFoundException {
+ this.edgeFile = edgeFile;
+ init();
+ }
+ public EdgeRuleSet(DocumentContext jsonContext) {
+ this.jsonContext = jsonContext;
+ }
+
+ public Collection<EdgeDescription> getEdgeRules( String nodeName )
+ {
+ String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]";
+ String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]";
+ Collection<EdgeDescription> fromEdges = getEdgeRulesFromJson( fromRulesPath, false );
+ Collection<EdgeDescription> edges = getEdgeRulesFromJson( toRulesPath, true );
+ edges.addAll(fromEdges);
+ return edges;
+ }
+
+ public Collection<EdgeDescription> getEdgeRulesTO( String nodeName )
+ {
+ String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]";
+ Collection<EdgeDescription> edges = getEdgeRulesFromJson( toRulesPath, true );
+ return edges;
+ }
+
+ public Collection<EdgeDescription> getEdgeRulesFROM( String nodeName )
+ {
+ String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]";
+ Collection<EdgeDescription> edges = getEdgeRulesFromJson( fromRulesPath, true );
+ return edges;
+ }
+
+ /**
+ * Guaranteed to at least return non null but empty collection of edge descriptions
+ * @param nodeName name of the vertex whose edge relationships to return
+ * @return collection of node neighbors based on DbEdgeRules
+ **/
+ public Collection<EdgeDescription> getEdgeRulesFromJson( String path, boolean skipMatch )
+ {
+
+ ArrayList<EdgeDescription> result = new ArrayList<>();
+ Iterator<Map<String, Object>> edgeRulesIterator;
+ try {
+ List<Map<String, Object>> inEdges = jsonContext.read(path);
+
+ edgeRulesIterator = inEdges.iterator();
+ Map<String, Object> edgeMap;
+ String fromNode;
+ String toNode;
+ String direction;
+ String multiplicity;
+ String isParent;
+ String deleteOtherV;
+ String preventDelete;
+ String description;
+ EdgeDescription edgeDes;
+
+ while( edgeRulesIterator.hasNext() ){
+ edgeMap = edgeRulesIterator.next();
+ fromNode = (String)edgeMap.get("from");
+ toNode = (String)edgeMap.get("to");
+ if ( skipMatch ) {
+ if ( fromNode.equals(toNode)) {
+ continue;
+ }
+ }
+ edgeDes = new EdgeDescription();
+ edgeDes.setRuleKey(fromNode + "|" + toNode);
+ edgeDes.setLabel((String)edgeMap.get("label"));
+ edgeDes.setTo((String)edgeMap.get("to"));
+ edgeDes.setFrom((String)edgeMap.get("from"));
+ direction = (String)edgeMap.get("direction");
+ edgeDes.setDirection(direction);
+ multiplicity = (String)edgeMap.get("multiplicity");
+ edgeDes.setMultiplicity(multiplicity);
+ isParent = (String)edgeMap.get(EdgeProperty.CONTAINS.toString());
+ if ( "${direction}".equals(isParent)) {
+ edgeDes.setType(EdgeDescription.LineageType.PARENT);
+ } else {
+ edgeDes.setType(EdgeDescription.LineageType.UNRELATED);
+ }
+ deleteOtherV = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString());
+ edgeDes.setDeleteOtherV(deleteOtherV);
+ preventDelete = (String)edgeMap.get(EdgeProperty.PREVENT_DELETE.toString());
+ edgeDes.setPreventDelete(preventDelete);
+ description = (String)edgeMap.get(EdgeProperty.DESCRIPTION.toString());
+ edgeDes.setDescription(description);
+
+ result.add(edgeDes);
+// logger.debug("Edge: "+edgeDes.getRuleKey());
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ return result;
+
+ }
+
+ private void init() throws FileNotFoundException, IOException {
+ InputStream is = null;
+ Scanner scanner = null;
+ String jsonEdges = null;
+ try {
+ is = new FileInputStream(edgeFile);
+ scanner = new Scanner(is);
+ jsonEdges = scanner.useDelimiter("\\Z").next();
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ scanner.close();
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ throw e;
+ }
+ }
+ }
+ jsonContext = JsonPath.parse(jsonEdges);
+ }
+
+ public String preventDeleteRules(String objectName) {
+ Collection<EdgeDescription> toEdges = getEdgeRulesTO(objectName);
+ toEdges.addAll(getEdgeRulesFROM(objectName));
+// logger.debug("TO Edges count: "+toEdges.size()+" Object: "+objectName);
+ String prevent=null;
+ LinkedHashSet<String> preventDelete = new LinkedHashSet<String>();
+ for (EdgeDescription ed : toEdges) {
+// logger.debug("{“comment”: From = "+ed.getFrom()+" To: "+ed.getTo()+" Object: "+objectName);
+// logger.debug("{“comment”: Direction = "+ed.getDirection()+" PreventDelete: "+ed.getPreventDelete()+" DeleteOtherV: "+ed.getDeleteOtherV()+" Object: "+objectName);
+ if(ed.getPreventDelete().equals("IN") && ed.getTo().equals(objectName)) {
+ preventDelete.add(ed.getFrom().toUpperCase());
+ }
+ if(ed.getPreventDelete().equals("OUT") && ed.getFrom().equals(objectName)) {
+ preventDelete.add(ed.getTo().toUpperCase());
+ }
+ }
+ if(preventDelete.size() > 0) {
+ prevent = objectName.toUpperCase()+" cannot be deleted if related to "+String.join(",",preventDelete);
+// logger.debug(prevent);
+ }
+ return String.join((prevent == null) ? "" : "\n", prevent == null ? "" : prevent)+((prevent == null) ? "" : "\n");
+// return String.join((prevent == null) ? "" : "\n", prevent == null ? "" : prevent, also == null ? "" : also)+((prevent == null) ? "" : "\n");
+ }
+
+ public String fromDeleteRules(String objectName) {
+ Collection<EdgeDescription> fromEdges = getEdgeRulesFROM(objectName);
+ LinkedHashSet<String> preventDelete = new LinkedHashSet <String>();
+ String prevent=null;
+ String also=null;
+ for (EdgeDescription ed : fromEdges) {
+// logger.debug("{“comment”: From = "+ed.getFrom()+" To: "+ed.getTo()+" Object: "+objectName);
+// logger.debug("{“comment”: Direction = "+ed.getDirection()+" PreventDelete: "+ed.getPreventDelete()+" DeleteOtherV: "+ed.getDeleteOtherV()+" Object: "+objectName);
+ if(ed.getPreventDelete().equals("OUT") && ed.getFrom().equals(objectName)) {
+ preventDelete.add(ed.getTo().toUpperCase());
+ }
+ }
+ if(preventDelete.size() > 0) {
+ prevent = objectName.toUpperCase()+" cannot be deleted if related to "+String.join(",",preventDelete);
+// logger.debug(prevent);
+ }
+ return String.join((prevent == null || also == null) ? "" : "\n", prevent == null ? "" : prevent, also == null ? "" : also)+((prevent == null && also == null) ? "" : "\n");
+ }
+}
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
new file mode 100644
index 00000000..16a2e682
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/GetOperation.java
@@ -0,0 +1,121 @@
+/**
+ * ============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.util.GenerateXsd;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+public class GetOperation {
+ static Map<String, Vector<String>> containers = new HashMap<String, Vector<String>>();
+ public static void addContainerProps(String container, Vector<String> 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
new file mode 100644
index 00000000..287b3b5c
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/HTMLfromOXM.java
@@ -0,0 +1,190 @@
+/**
+ * ============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.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Version;
+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;
+
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.File;
+import java.io.IOException;
+
+public class HTMLfromOXM extends OxmFileProcessor {
+ private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXM.class");
+
+ Version v;
+ public HTMLfromOXM(File oxmFile, Version v) throws ParserConfigurationException, SAXException, IOException, AAIException {
+ super(oxmFile, v);
+ super.init();
+ this.v = v;
+ }
+ public HTMLfromOXM(String xml, Version v) throws ParserConfigurationException, SAXException, IOException, AAIException {
+ super(xml, v);
+ super.init();
+ this.v = v;
+ }
+
+ @Override
+ public String getDocumentHeader() {
+ StringBuffer sb = new StringBuffer();
+ logger.trace("processing starts");
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
+ String namespace = "org.onap";
+ if (v.compareTo(Version.v11) < 0 || v.compareTo(Version.v12) < 0) {
+ namespace = "org.openecomp";
+ }
+ if ( versionUsesAnnotations(v.name()) ) {
+ sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/"
+ + v.name() + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + v.name() + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
+ + "\n"
+ + "xmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\"\r\n" +
+ " jaxb:version=\"2.1\"\r\n" +
+ " xmlns:annox=\"http://annox.dev.java.net\"\r\n" +
+ " jaxb:extensionBindingPrefixes=\"annox\">\n\n");
+ } else {
+ sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/"
+ + v.name() + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + v.name() + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\n");
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String process() throws AAIException {
+ StringBuilder sb = new StringBuilder();
+ sb.append(getDocumentHeader());
+ for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) {
+ XSDElement javaTypeElement = new XSDElement((Element)javaTypeNodes.item(i));
+ String javaTypeName = javaTypeElement.name();
+ if ( javaTypeName == null ) {
+ String msg = "Invalid OXM file: <java-type> 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;
+ }
+ //Skip any type that has already been processed(recursion could be the reason)
+ logger.debug(getXmlRootElementName(javaTypeName)+" vs "+ javaTypeName+":"+generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)));
+ if ( generatedJavaType.containsKey(javaTypeName) ) {
+ continue;
+ }
+ generatedJavaType.put(javaTypeName, null);
+ sb.append(processJavaTypeElement( javaTypeName, javaTypeElement ));
+ }
+ sb.append("</xs:schema>\n");
+ return sb.toString();
+ }
+
+ public String processJavaTypeElement( String javaTypeName, Element javaType_Element) {
+
+ 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");
+
+ StringBuffer sb1 = new StringBuffer();
+ if ( xmlElementNodes.getLength() > 0 ) {
+ sb1.append(" <xs:element name=\"" + xmlRootElementName + "\">\n");
+ sb1.append(" <xs:complexType>\n");
+ XSDElement javaTypeElement = new XSDElement(javaType_Element);
+ logger.debug("XSDElement name: "+javaTypeElement.name());
+ if(versionUsesAnnotations(v.name())) {
+ sb1.append(javaTypeElement.getHTMLAnnotation("class", " "));
+ }
+ sb1.append(" <xs:sequence>\n");
+ for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) {
+
+ XSDElement xmlElementElement = new XSDElement((Element)xmlElementNodes.item(i));
+
+ String elementName = xmlElementElement.getAttribute("name");
+ String elementType = xmlElementElement.getAttribute("type");
+ //No simple types; only AAI custom types
+ String addType = elementType.contains("." + v.name() + ".") ? elementType.substring(elementType.lastIndexOf('.')+1) : null;
+ if ( elementType.contains("." + v.name() + ".") && !generatedJavaType.containsKey(addType) ) {
+ generatedJavaType.put(addType, elementType);
+ sb.append(processJavaTypeElement( addType, getJavaTypeElement(addType) ));
+ }
+ if ("Nodes".equals(addType)) {
+ logger.trace("Skipping nodes, temporary testing");
+ continue;
+ }
+ //assembles the basic <element>
+ sb1.append(xmlElementElement.getHTMLElement(v, versionUsesAnnotations(v.name()), this));
+ }
+ sb1.append(" </xs:sequence>\n");
+ sb1.append(" </xs:complexType>\n");
+ sb1.append(" </xs:element>\n");
+ }
+
+ if ( xmlElementNodes.getLength() < 1 ) {
+ sb.append(" <xs:element name=\"" + xmlRootElementName + "\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:sequence/>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ generatedJavaType.put(javaTypeName, null);
+ return sb.toString();
+ }
+ sb.append( sb1 );
+ return sb.toString();
+ }
+
+ private Element getJavaTypeElement( 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))
+ return javaTypeElement;
+ }
+ }
+ logger.error( "oxm file format error, missing java-type " + javaTypeName);
+ return (Element) null;
+ }
+
+ private boolean versionUsesAnnotations( String version) {
+ if (new Integer(version.substring(1)).intValue() >= HTMLfromOXM.annotationsStartVersion ) {
+ return true;
+ }
+ return false;
+ }
+} \ No newline at end of file
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
new file mode 100644
index 00000000..04fdd3c0
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/OxmFileProcessor.java
@@ -0,0 +1,199 @@
+/**
+ * ============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.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Version;
+import org.w3c.dom.*;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.Map;
+
+public abstract class OxmFileProcessor {
+ protected File oxmFile;
+ protected String xml;
+ protected Version v;
+ protected Document doc = null;
+ protected String apiVersion = null;
+ protected static int annotationsStartVersion = 9; // minimum version to support annotations in xsd
+ protected static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation
+
+ protected String apiVersionFmt = null;
+ protected HashMap<String, String> generatedJavaType = new HashMap<String, String>();
+ protected HashMap<String, String> appliedPaths = new HashMap<String, String>();
+ protected NodeList javaTypeNodes = null;
+ protected static Map<String,String> javaTypeDefinitions = createJavaTypeDefinitions();
+ private static Map<String, String> createJavaTypeDefinitions()
+ {
+ StringBuffer aaiInternal = new StringBuffer();
+ StringBuffer nodes = new StringBuffer();
+ Map<String,String> javaTypeDefinitions = new HashMap<String, String>();
+ 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;
+ }
+
+
+ public OxmFileProcessor(File oxmFile, Version v) {
+ super();
+ this.oxmFile = oxmFile;
+ this.v = v;
+ }
+
+ public OxmFileProcessor(String xml, Version v) {
+ this.xml = xml;
+ this.v = v;
+ }
+ protected 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 {
+ 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;
+ }
+
+ 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 <binding-nodes> in " + oxmFile);
+ }
+
+ bindingElement = (Element) bindingsNodes.item(0);
+ javaTypesNodes = bindingElement.getElementsByTagName("java-types");
+ if ( javaTypesNodes.getLength() < 1 ) {
+ throw new AAIException("OXM file error: missing <binding-nodes><java-types> in " + oxmFile);
+ }
+ javaTypesElement = (Element) javaTypesNodes.item(0);
+
+ javaTypeNodes = javaTypesElement.getElementsByTagName("java-type");
+ if ( javaTypeNodes.getLength() < 1 ) {
+ throw new AAIException("OXM file error: missing <binding-nodes><java-types><java-type> in " + oxmFile );
+ }
+ }
+ public abstract String getDocumentHeader();
+ public abstract String process() throws AAIException;
+
+ 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 Element getJavaTypeElementSwagger( 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))
+ return javaTypeElement;
+ }
+ }
+ return (Element) null;
+ }
+
+}
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
new file mode 100644
index 00000000..cc90114f
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/PatchOperation.java
@@ -0,0 +1,116 @@
+/**
+ * ============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.util.GenerateXsd;
+
+import java.util.StringTokenizer;
+
+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(" - 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 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
new file mode 100644
index 00000000..58ccec37
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/PutOperation.java
@@ -0,0 +1,114 @@
+/**
+ * ============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.introspection.Version;
+import org.onap.aai.util.GenerateXsd;
+
+import java.util.StringTokenizer;
+
+public class PutOperation {
+ private String useOpId;
+ private String xmlRootElementName;
+ private String tag;
+ private String path;
+ private String pathParams;
+ private Version version;
+
+ public PutOperation(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, Version v) {
+ super();
+ this.useOpId = useOpId;
+ this.xmlRootElementName = xmlRootElementName;
+ this.tag = tag;
+ this.path = path;
+ this.pathParams = pathParams;
+ this.version = v;
+ }
+
+ @Override
+ public String toString() {
+ StringTokenizer st = new StringTokenizer(path, "/");
+ //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.name()+"/"+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");
+ pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n");
+ this.tagRelationshipPathMapEntry();
+ return pathSb.toString();
+ }
+
+ public String tagRelationshipPathMapEntry() {
+ if ( path.endsWith("/relationship") ) {
+ PutRelationPathSet.add(useOpId, path);
+ }
+ return "";
+ }
+
+ } \ No newline at end of file
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
new file mode 100644
index 00000000..3e411946
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/PutRelationPathSet.java
@@ -0,0 +1,216 @@
+/**
+ * ============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.text.similarity.LevenshteinDistance;
+import org.onap.aai.introspection.Version;
+import org.onap.aai.util.GenerateXsd;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+public class PutRelationPathSet {
+ private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class");
+ protected static HashMap<String, String> putRelationPaths = new HashMap<String, String>();
+ private static EdgeRuleSet edgeRuleSet = null;
+ public static void add(String useOpId, String path) {
+ putRelationPaths.put(useOpId, path);
+ }
+
+ String apiPath;
+ String opId;
+ Version version;
+ protected ArrayList<String> relations = new ArrayList<String>();
+ String objectName = "";
+
+ public PutRelationPathSet(Version v) {
+ this.version = v;
+ }
+
+ public PutRelationPathSet(String opId, String path, Version 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() {
+ 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);
+ Collection<EdgeDescription> toEdges = edgeRuleSet.getEdgeRulesTO(objectName);
+
+ if(toEdges.size() > 0) {
+ relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
+ }
+ for (EdgeDescription ed : toEdges) {
+ logger.debug(ed.getRuleKey()+"Type="+ed.getType());
+ String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
+ String selectedRelation = "";
+ if(ed.getType() == EdgeDescription.LineageType.UNRELATED) {
+ String selectObj = getUnrelatedObjectPaths(obj, apiPath);
+ logger.debug("SelectedObj:"+selectObj);
+ selectedRelation = formatObjectRelationSet(obj,selectObj);
+ logger.debug("ObjectRelationSet"+selectedRelation);
+ } else {
+ String selectObj = getKinObjectPath(obj, apiPath);
+ logger.debug("SelectedObj:"+selectObj);
+ selectedRelation = formatObjectRelation(obj,selectObj);
+ logger.debug("ObjectRelationSet"+selectedRelation);
+ }
+ relations.add(selectedRelation);
+ logger.debug("Relation added: "+selectedRelation);
+ }
+ }
+
+ private void fromRelations() {
+ logger.debug("“comment”: “Valid FROM Relations that can be added”");
+ Collection<EdgeDescription> fromEdges = edgeRuleSet.getEdgeRulesFROM(objectName);
+ if(fromEdges.size() > 0) {
+ relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
+ }
+ for (EdgeDescription ed : fromEdges) {
+ logger.debug(ed.getRuleKey()+"Type="+ed.getType());
+ String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
+ String selectedRelation = "";
+ 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);
+ }
+ relations.add(selectedRelation);
+ logger.trace(selectedRelation);
+ }
+ }
+ private void writeRelationsFile() {
+ File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.name()+"/"+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;
+ }
+ 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<String, String> 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<String, String> 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(EdgeRuleSet edgeRuleSet) {
+
+ if(putRelationPaths == null)
+ return;
+ if(edgeRuleSet == null)
+ return;
+ else
+ PutRelationPathSet.edgeRuleSet = edgeRuleSet;
+ 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();
+ });
+ }
+
+}
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
new file mode 100644
index 00000000..894e7520
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDElement.java
@@ -0,0 +1,678 @@
+/**
+ * ============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 com.google.common.base.Joiner;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.aai.introspection.Version;
+import org.w3c.dom.*;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+public class XSDElement implements Element {
+ Element xmlElementElement;
+ 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;
+
+ public XSDElement(Element xmlElementElement) {
+ super();
+ this.xmlElementElement = xmlElementElement;
+ }
+ public String name() {
+ return this.getAttribute("name");
+ }
+
+ public Vector<String> getAddTypes(String version) {
+ String apiVersionFmt = "." + version + ".";
+ NamedNodeMap attributes = this.getAttributes();
+ Vector<String> addTypeV = new Vector<String>(); // 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<String>();
+ addTypeV.add(addType);
+ }
+
+ }
+ }
+ return addTypeV;
+ }
+
+ 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<String> getIndexedProps() {
+ Vector<String> indexedProps = new Vector<String>();
+ 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<String> getIndexedProps( String attrValue )
+ {
+ if ( attrValue == null )
+ return null;
+ StringTokenizer st = new StringTokenizer( attrValue, ",");
+ if ( st.countTokens() == 0 )
+ return null;
+ Vector<String> result = new Vector<String>();
+ 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() {
+ StringBuffer sbParameter = new StringBuffer();
+ sbParameter.append((" - name: " + this.getAttribute("name") + "\n"));
+ sbParameter.append((" in: query\n"));
+ if ( this.getAttribute("description") != null && this.getAttribute("description").length() > 0 )
+ sbParameter.append((" description: " + this.getAttribute("description") + "\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");
+ }
+ return sbParameter.toString();
+ }
+
+ public String getPathParamYAML(String elementDescription) {
+ 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"));
+ sbParameter.append((" required: true\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(Version 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.name() + ".") ? elementType.substring(elementType.lastIndexOf('.')+1) : null;
+
+ if ( addType != null ) {
+ sbElement.append(" <xs:element ref=\"tns:" + driver.getXmlRootElementName(addType)+"\"");
+ } else {
+ sbElement.append(" <xs:element name=\"" + elementName +"\"");
+ }
+ if ( elementType.equals("java.lang.String"))
+ sbElement.append(" type=\"xs:string\"");
+ if ( elementType.equals("java.lang.Long"))
+ sbElement.append(" type=\"xs:unsignedInt\"");
+ if ( elementType.equals("java.lang.Integer"))
+ sbElement.append(" type=\"xs:int\"");
+ if ( elementType.equals("java.lang.Boolean"))
+ sbElement.append(" type=\"xs:boolean\"");
+ if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) {
+ sbElement.append(" minOccurs=\"0\"");
+ }
+ if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) {
+ sbElement.append(" maxOccurs=\"unbounded\"");
+ }
+ if(useAnnotation) {
+ String annotation = new XSDElement(xmlElementElement).getHTMLAnnotation("field", " ");
+ sbElement.append(StringUtils.isNotEmpty(annotation) ? ">\n" : "");
+ sbElement.append(annotation);
+ sbElement.append(StringUtils.isNotEmpty(annotation) ? " </xs:element>\n" : "/>\n" );
+ } else {
+ sbElement.append("/>\n");
+ }
+ return this.getHTMLElementWrapper(sbElement.toString(), v, useAnnotation);
+// return sbElement.toString();
+ }
+
+ public String getHTMLElementWrapper(String unwrappedElement, Version 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(" <xs:element name=\"" + xmlElementWrapper +"\"");
+ String elementType = xmlElementElement.getAttribute("type");
+ String elementIsRequired = this.getAttribute("required");
+ String addType = elementType.contains("." + v.name() + ".") ? elementType.substring(elementType.lastIndexOf('.')+1) : null;
+
+ if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) {
+ sbElement.append(" minOccurs=\"0\"");
+ }
+ sbElement.append(">\n");
+ sbElement.append(" <xs:complexType>\n");
+ if(useAnnotation) {
+ XSDElement javaTypeElement = new XSDElement((Element)this.getParentNode());
+ sbElement.append(javaTypeElement.getHTMLAnnotation("class", " "));
+ }
+ sbElement.append(" <xs:sequence>\n");
+ sbElement.append(" ");
+ sbElement.append(unwrappedElement);
+ sbElement.append(" </xs:sequence>\n");
+ sbElement.append(" </xs:complexType>\n");
+ sbElement.append(" </xs:element>\n");
+ return sbElement.toString();
+ }
+
+ public String getHTMLAnnotation(String target, String indentation) {
+ StringBuffer sb = new StringBuffer();
+ List<String> 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("&", "&amp;") + "\"");
+ }
+ }
+ if(metadata.size() == 0) {
+ return "";
+ }
+ sb.append(indentation +"<xs:annotation>\r\n");
+ sb.append(
+ indentation + " <xs:appinfo>\r\n" +
+ indentation + " <annox:annotate target=\""+target+"\">@org.onap.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")</annox:annotate>\r\n" +
+ indentation + " </xs:appinfo>\r\n");
+ sb.append(indentation +"</xs:annotation>\r\n");
+ 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");
+ 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;
+ }
+
+
+}
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
new file mode 100644
index 00000000..6315ddff
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/XSDJavaType.java
@@ -0,0 +1,64 @@
+/**
+ * ============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
new file mode 100644
index 00000000..ff7d44b6
--- /dev/null
+++ b/aai-core/src/main/java/org/onap/aai/util/genxsd/YAMLfromOXM.java
@@ -0,0 +1,470 @@
+/**
+ * ============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.exceptions.AAIException;
+import org.onap.aai.introspection.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import javax.xml.parsers.ParserConfigurationException;
+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.*;
+
+public class YAMLfromOXM 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 File edgeFile;
+ private EdgeRuleSet edgeRuleSet = null;
+ public YAMLfromOXM(File oxmFile, Version v, File edgeFile) throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException {
+ super(oxmFile, v);
+ this.edgeFile = edgeFile;
+ init();
+ }
+ public YAMLfromOXM(String xml, Version v, File edgeFile) throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException {
+ super(xml, v);
+ this.edgeFile = edgeFile;
+ init();
+ }
+
+ @Override
+ public String getDocumentHeader() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("swagger: \"2.0\"\ninfo:\n ");
+ sb.append("description: |");
+ sb.append("\n\n [Differences versus the previous schema version]("+"apidocs/aai_swagger_" + v.name() + ".diff)");
+ sb.append("\n\n Copyright &copy; 2017 AT&amp;T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the &quot;License&quot;); 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 &quot;AS IS&quot; 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 ECOMP and OpenECOMP are trademarks and service marks of AT&amp;T Intellectual Property.\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.name() +"\"\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: /aai/" + v.name() + "\n");
+ sb.append("schemes:\n - https\npaths:\n");
+ return sb.toString();
+ }
+
+ protected void init() throws ParserConfigurationException, SAXException, IOException, AAIException, FileNotFoundException {
+ super.init();
+ edgeRuleSet = new EdgeRuleSet(edgeFile);
+ }
+
+ @Override
+ public String process() throws AAIException {
+ StringBuffer sb = new StringBuffer();
+ EdgeRuleSet edgeRuleSet = null;
+ try {
+ edgeRuleSet = new EdgeRuleSet(edgeFile);
+ } catch (Exception e) {
+ logger.warn("No valid Edge Rule Set available("+edgeFile+"): "+e.getMessage());
+ }
+
+ StringBuffer pathSb = new StringBuffer();
+ pathSb.append(getDocumentHeader());
+ StringBuffer definitionsSb = new StringBuffer();
+ for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) {
+ XSDElement javaTypeElement = new XSDElement((Element)javaTypeNodes.item(i));
+ logger.debug("External: "+javaTypeElement.getAttribute("name"));
+ String javaTypeName = javaTypeElement.name();
+ if ( javaTypeName == null ) {
+ String msg = "Invalid OXM file: <java-type> has no name attribute in " + oxmFile;
+ logger.error(msg);
+ throw new AAIException(msg);
+ }
+ //Skip any type that has already been processed(recursion could be the reason)
+ if ( generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)) ) {
+ continue;
+ }
+ processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb,
+ definitionsSb, null, null, null, null, null, null);
+ }
+ sb.append(pathSb);
+
+ sb.append(appendDefinitions());
+ PutRelationPathSet prp = new PutRelationPathSet(v);
+ prp.generateRelations(edgeRuleSet);
+ return sb.toString();
+ }
+
+ public String appendDefinitions() {
+ //append definitions
+ StringBuffer sb = new StringBuffer("definitions:\n");
+ Map<String, String> sortedJavaTypeDefinitions = new TreeMap<String, String>(javaTypeDefinitions);
+ for (Map.Entry<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
+ logger.debug("Key: "+entry.getKey()+"Test: "+ (entry.getKey() == "relationship"));
+ if(entry.getKey().matches("relationship")) {
+ 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<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
+ 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<String, String> entry : sortedJavaTypeDefinitions.entrySet()) {
+ String jb=entry.getValue().replaceAll("/definitions/", "/getDefinitions/");
+ sb.append(jb);
+ }
+ 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 ) {
+ switch ( tag ) {
+ case "Network":
+ case "ServiceDesignAndCreation":
+ case "Business":
+ case "LicenseManagement":
+ case "CloudInfrastructure":
+ 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<String> indexedProps = javaType.getIndexedProps();
+ Vector<String> containerProps = new Vector<String>();
+ 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<String> 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.name());
+ }
+ 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);
+ logger.debug("addType: "+ addType);
+ if(addType == "overloaded-model" || addType.equals("OverloadedModel") || addType == "owning-entity") {
+ logger.debug("Description check: "+ addType+"opId="+opId+" itemName=none");
+// Log.info("Element name="+xmlElementElement.getAttribute("name"));
+ }
+
+
+ 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)
+ 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 {
+ if(addType.equals("AaiInternal")) //Filter out references to AaiInternal
+ sbProperties.append("");
+ 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());
+ //Write operations by Namespace(tagName)
+// if(javaTypeName == useTag && tag == null) {
+// pathSb.append(appendDefinitions());
+// writeYAMLfile(javaTypeName, pathSb.toString());
+// pathSb.delete(0, pathSb.length());
+// javaTypeDefinitions.clear();
+// generatedJavaType.clear();
+// }
+ if ( generatedJavaType.containsKey(xmlRootElementName) ) {
+ logger.debug("xmlRootElementName(1)="+xmlRootElementName);
+ return null;
+ }
+
+ definitionsSb.append(" " + xmlRootElementName + ":\n");
+ definitionsLocalSb.append(" " + xmlRootElementName + ":\n");
+ Collection<EdgeDescription> edges = edgeRuleSet.getEdgeRules(xmlRootElementName );
+ DeleteFootnoteSet footnotes = new DeleteFootnoteSet(xmlRootElementName);
+ if ( edges.size() > 0 ) {
+ StringBuffer sbEdge = new StringBuffer();
+ sbEdge.append(" ###### Related Nodes\n");
+
+ for (EdgeDescription ed : edges) {
+ if ( ed.getRuleKey().startsWith(xmlRootElementName)) {
+ sbEdge.append(" - TO ").append(ed.getRuleKey().substring(ed.getRuleKey().indexOf("|")+1));
+ String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName);
+ sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)+footnote+"\n");
+ if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);
+ }
+ }
+ for (EdgeDescription ed : edges) {
+ if ( ed.getRuleKey().endsWith(xmlRootElementName)) {
+ sbEdge.append(" - FROM ").append(ed.getRuleKey().substring(0, ed.getRuleKey().indexOf("|")));
+ String footnote = ed.getAlsoDeleteFootnote(xmlRootElementName);
+ sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)+footnote+"\n");
+ if(StringUtils.isNotEmpty(footnote)) footnotes.add(footnote);
+ }
+ }
+ footnotes.add(edgeRuleSet.preventDeleteRules(xmlRootElementName));
+ 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 (pathDescriptionProperty != null || validEdges != null) {
+ definitionsSb.append(" description: |\n");
+ definitionsLocalSb.append(" description: |\n");
+
+ if ( pathDescriptionProperty != null ) {
+ definitionsSb.append(" " + pathDescriptionProperty + "\n" );
+ definitionsLocalSb.append(" " + pathDescriptionProperty + "\n" );
+ }
+ if (validEdges != null) {
+ 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);
+ definitionsLocalSb.append(" properties:\n");
+ definitionsLocalSb.append(sbProperties);
+ }
+ try {
+ javaTypeDefinitions.put(xmlRootElementName, definitionsLocalSb.toString());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ generatedJavaType.put(xmlRootElementName, null);
+ 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.name() + "." + 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();
+ }
+ BufferedWriter bw = null;
+ try {
+ Charset charset = Charset.forName("UTF-8");
+ Path path = Paths.get(outfileName);
+ 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();
+ }
+ }
+}
diff --git a/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java b/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
index 41a2f424..94fce5d4 100644
--- a/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
+++ b/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
@@ -19,16 +19,15 @@
*/
package org.onap.aai;
-import org.junit.runners.BlockJUnit4ClassRunner;
-import org.junit.runners.model.InitializationError;
+import org.junit.runners.Parameterized;
import org.onap.aai.util.AAIConstants;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
-public class AAIJunitRunner extends BlockJUnit4ClassRunner {
+public class AAIJunitRunner extends Parameterized {
- public AAIJunitRunner(Class<?> klass) throws InitializationError {
+ public AAIJunitRunner(Class<?> klass) throws Throwable {
super(klass);
setProps();
modifyOxmHome();
diff --git a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
index 7284593e..943ebad5 100644
--- a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
+++ b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
@@ -41,7 +41,9 @@ import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import javax.ws.rs.core.*;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doReturn;
@@ -54,6 +56,7 @@ public class HttpTestUtil extends RESTAPI {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
private static final String EMPTY = "";
+ private final QueryStyle queryStyle;
protected HttpHeaders httpHeaders;
protected UriInfo uriInfo;
@@ -64,6 +67,10 @@ public class HttpTestUtil extends RESTAPI {
protected List<String> aaiRequestContextList;
protected List<MediaType> outputMediaTypes;
+ public HttpTestUtil(QueryStyle qs) {
+ this.queryStyle = qs;
+ }
+
public void init(){
httpHeaders = Mockito.mock(HttpHeaders.class);
@@ -114,7 +121,7 @@ public class HttpTestUtil extends RESTAPI {
if(arr != null && arr.length > 1){
if(arr[0].matches("^v\\d+")){
- version = Version.valueOf(arr[0]);
+ version = Version.getVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
@@ -125,7 +132,7 @@ public class HttpTestUtil extends RESTAPI {
Mockito.when(uriInfo.getPath()).thenReturn(uri);
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
dbEngine = httpEntry.getDbEngine();
@@ -206,7 +213,7 @@ public class HttpTestUtil extends RESTAPI {
if(arr != null && arr.length > 1){
if(arr[0].matches("^v\\d+")){
- version = Version.valueOf(arr[0]);
+ version = Version.getVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
@@ -216,7 +223,7 @@ public class HttpTestUtil extends RESTAPI {
}
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
dbEngine = httpEntry.getDbEngine();
@@ -287,7 +294,7 @@ public class HttpTestUtil extends RESTAPI {
if(arr != null && arr.length > 1){
if(arr[0].matches("^v\\d+")){
- version = Version.valueOf(arr[0]);
+ version = Version.getVersion(arr[0]);
if(!uri.contains("relationship-list/relationship")){
uri = uri.replaceAll("^v\\d+", "");
}
@@ -300,7 +307,7 @@ public class HttpTestUtil extends RESTAPI {
Mockito.when(uriInfo.getPath()).thenReturn(uri);
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
dbEngine = httpEntry.getDbEngine();
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/MoxyLoaderTest.java b/aai-core/src/test/java/org/onap/aai/introspection/MoxyLoaderTest.java
new file mode 100644
index 00000000..95a4bb61
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/MoxyLoaderTest.java
@@ -0,0 +1,77 @@
+/**
+ * ============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.introspection;
+
+import org.junit.Test;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.onap.aai.restcore.MediaType;
+
+import static org.junit.Assert.assertEquals;
+
+public class MoxyLoaderTest extends IntrospectorTestSpec {
+
+ /**
+ * Container object.
+ * @throws AAIUnknownObjectException
+ */
+ @Test
+ public void testMethodsForExceptions() throws AAIUnknownObjectException {
+
+ MoxyLoader loader = (MoxyLoader) LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9);
+ String payload = "{\"att-uuid\":\"wr148d\",\"application\":\"testApp\",\"application-vendor\":\"testVendor\",\"application-version\":\"versionTest\"}";
+ Boolean exceptionThrownForIntrospector = false;
+ Boolean exceptionThrownForLoaderMethods = false;
+ Boolean exceptionThrownForUnmarshalling = false;
+ Boolean exceptionThrownForObjectFromName = false;
+ try {
+ loader.getAllObjects();
+ loader.getJAXBContext();
+ }catch(Exception e){
+ exceptionThrownForLoaderMethods = true;
+ }
+ try{
+ loader.introspectorFromName("TEST");
+ }catch(Exception e){
+ exceptionThrownForIntrospector = true;
+ }
+ try {
+ loader.unmarshal("vnf-image", payload, MediaType.APPLICATION_JSON_TYPE);
+ loader.unmarshal("vnf-image", null, MediaType.APPLICATION_JSON_TYPE);
+ loader.unmarshal("vnf-image", "{}", MediaType.APPLICATION_JSON_TYPE);
+ }catch(Exception e){
+ exceptionThrownForUnmarshalling = true;
+ }
+ try{
+ loader.objectFromName(null);
+ loader.objectFromName("test");
+ }catch(Exception e) {
+ exceptionThrownForObjectFromName = true;
+ }
+
+ assertEquals(false, exceptionThrownForLoaderMethods);
+ assertEquals(true, exceptionThrownForIntrospector);
+ assertEquals(true, exceptionThrownForUnmarshalling);
+ assertEquals(true, exceptionThrownForObjectFromName);
+
+ }
+
+
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java
index d30b51b0..1c68d087 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java
@@ -39,4 +39,69 @@ public class PojoStrategyTest {
assertEquals("", volumegroup.getMetadata(ObjectMetadata.NAMESPACE));
}
+ @Test
+ public void testGetWithBogusValue(){
+ Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion());
+ assertEquals(null, cloudregion.get("test"));
+ }
+
+ @Test
+ public void testSetWithValue(){
+ Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion());
+ cloudregion.set("cloudOwner", "test");
+ assertEquals("test", cloudregion.get("cloudOwner"));
+ }
+
+ @Test
+ public void testHasProperty(){
+ Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion());
+ assertEquals( true, cloudregion.hasProperty("test"));
+ }
+
+ @Test
+ public void testMethodsforExceptions(){
+ PojoStrategy ps = new PojoStrategy(new CloudRegion());
+ Exception ex = null;
+ Boolean exceptionThrownForKeys = false;
+ Boolean exceptionThrownForProcessKeys = false;
+ try{
+ ps.findKey();
+ ps.getKeys();
+ }catch(Exception e){
+ exceptionThrownForKeys= true;
+ }
+ try {
+ ps.getProperties();
+ ps.getRequiredProperties();
+ ps.getClass("TEST");
+ ps.getGenericTypeClass("TEST");
+ ps.getJavaClassName();
+ ps.getUnderlyingObject();
+ ps.clone();
+ ps.getChildName();
+ ps.getObjectId();
+ ps.getPropertyMetadata("TEST");
+ ps.getName();
+ ps.getVersion();
+ }catch(Exception e){
+ ex = e;
+ }
+
+
+ try{
+ ps.preProcessKey("TEST/TEST/TEST");
+ }catch(Exception e){
+ exceptionThrownForProcessKeys = true;
+ }
+ try{
+ ps.set("TEST", new Object());
+ }catch(Exception e){
+
+ }
+ assertEquals(null, ex);
+ assertEquals(true, exceptionThrownForKeys);
+ assertEquals(true, exceptionThrownForProcessKeys);
+ }
+
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/VersionTest.java b/aai-core/src/test/java/org/onap/aai/introspection/VersionTest.java
new file mode 100644
index 00000000..3fec8701
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/VersionTest.java
@@ -0,0 +1,50 @@
+/**
+ * ============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.introspection;
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.endsWith;
+import static org.junit.Assert.*;
+
+public class VersionTest {
+
+ @Test
+ public void isLatest() throws Exception {
+ assertTrue(Version.isLatest(Version.getVersion("latest")));
+ }
+
+ @Test
+ public void getLatest() throws Exception {
+ assertEquals(Version.getVersion("latest"), Version.getLatest());
+ }
+
+ @Test
+ public void getVersionLatestString() throws Exception {
+ assertEquals(Version.getLatest(), Version.getVersion("latest"));
+ }
+
+ @Test
+ public void getVersion() throws Exception {
+ assertEquals(Version.v13, Version.getVersion("v13"));
+ }
+
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java b/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java
new file mode 100644
index 00000000..8c373052
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java
@@ -0,0 +1,118 @@
+/**
+ * ============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.introspection.generator;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.aai.AAISetup;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class CreateExampleTest extends AAISetup {
+
+ private static CreateExample createExample;
+ private static Loader loader;
+
+ @BeforeClass
+ public static void setUp() {
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v11);
+ createExample = new CreateExample(loader, "edge-prop-names");
+ }
+
+ @Test
+ public void testGetExampleObject() throws AAIException {
+ Introspector introspector = loader.introspectorFromName("edge-prop-names");
+ Introspector res = createExample.getExampleObject();
+ assertEquals(introspector.getName(), res.getName());
+ }
+
+ @Test
+ public void testProcessPrimitiveString() throws AAIUnknownObjectException {
+ String propName = "direction";
+ Introspector introspector = loader.introspectorFromName("edge-prop-names");
+ createExample.processPrimitive(propName, introspector);
+ }
+
+ @Test
+ public void testProcessPrimitiveLong() throws AAIUnknownObjectException {
+ String propName = "vlan-id-inner";
+ Introspector introspector = loader.introspectorFromName("ctag-assignment");
+ createExample.processPrimitive(propName, introspector);
+ }
+
+ @Test
+ public void testProcessPrimitiveBoolean() throws AAIUnknownObjectException {
+ String propName = "in-maint";
+ Introspector introspector = loader.introspectorFromName("vserver");
+ createExample.processPrimitive(propName, introspector);
+ }
+
+ @Test
+ public void testProcessPrimitiveInteger() throws AAIUnknownObjectException {
+ String propName = "module-index";
+ Introspector introspector = loader.introspectorFromName("vf-module");
+ createExample.processPrimitive(propName, introspector);
+ }
+
+ @Test
+ public void testProcessPrimitiveList() throws AAIUnknownObjectException {
+ String propName = "ipaddress-v4-vig";
+ Introspector introspector = loader.introspectorFromName("vig-server");
+ createExample.processPrimitiveList(propName, introspector);
+ }
+
+ @Test
+ public void testProcessComplexObj() {
+ // empty method
+ Introspector introspector = Mockito.mock(Introspector.class);
+ createExample.processComplexObj(introspector);
+ }
+
+ @Test
+ public void testModifyComplexList() {
+ // empty method
+ List<Introspector> introList = new ArrayList<Introspector>();
+ List<Object> objList = new ArrayList<Object>();
+ Introspector introspector = Mockito.mock(Introspector.class);
+ createExample.modifyComplexList(introList, objList, introspector, introspector);
+ }
+
+ @Test
+ public void testCreateComplexObjIfNull() {
+ boolean res = createExample.createComplexObjIfNull();
+ assertTrue(res);
+ }
+
+ @Test
+ public void testCreateComplexListSize() {
+ Introspector introspector = Mockito.mock(Introspector.class);
+ int res = createExample.createComplexListSize(introspector, introspector);
+ assertEquals(1, res);
+ }
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
index 250c34cd..27efbdb2 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
@@ -28,6 +28,8 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.*;
import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.aai.db.props.AAIProperties;
@@ -48,25 +50,36 @@ import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+@RunWith(value = Parameterized.class)
public class DataCopyTest {
private static TitanGraph graph;
private final static Version version = Version.getLatest();
private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
private final static DBConnectionType type = DBConnectionType.REALTIME;
private static Loader loader;
private static TransactionalGraphEngine dbEngine;
@Mock private Vertex self;
@Mock private VertexProperty<String> prop;
@Mock private QueryParser uriQuery;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+ @Rule public ExpectedException thrown = ExpectedException.none();
+
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
@BeforeClass
@@ -75,16 +88,11 @@ public class DataCopyTest {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new TitanDBEngine(
- queryStyle,
- type,
- loader);
-
- graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1").as("v1")
- .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue")
+ graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1").as("v1")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v1", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "model", "model-invariant-id", "key3").as("v2")
- .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4")
+ .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3").as("v2")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true)
.next();
graph.tx().commit();
@@ -99,6 +107,10 @@ public class DataCopyTest {
@Before
public void initMock() {
MockitoAnnotations.initMocks(this);
+ dbEngine = new TitanDBEngine(
+ queryStyle,
+ type,
+ loader);
}
@Test
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
index 3b58f449..59fe8b86 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
@@ -27,6 +27,8 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.*;
import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.aai.AAISetup;
@@ -45,18 +47,20 @@ import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+@RunWith(value = Parameterized.class)
public class DataLinkTest extends AAISetup {
private static TitanGraph graph;
private final static Version version = Version.getLatest();
private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
private final static DBConnectionType type = DBConnectionType.REALTIME;
private static Loader loader;
private static TransactionalGraphEngine dbEngine;
@@ -65,32 +69,39 @@ public class DataLinkTest extends AAISetup {
@Mock private VertexProperty<String> prop;
@Rule
public ExpectedException thrown = ExpectedException.none();
-
+
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
@BeforeClass
public static void setup() throws NoSuchFieldException, SecurityException, Exception {
graph = TitanFactory.build().set("storage.backend","inmemory").open();
loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new TitanDBEngine(
- queryStyle,
- type,
- loader);
-
- graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey").as("v1")
- .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey").as("v2")
- .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true)
+
+ graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/addKey").as("v1")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey").as("v2")
+ .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey/modifyRoleKey")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey").as("v3")
- .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true)
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey",AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey").as("v3" )
+ .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey/route-targets/route-target/deleteTargetKey/deleteRoleKey")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v3", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey").as("v4")
- .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true)
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey").as("v4")
+ .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v4", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink").as("v5")
- .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink").as("v5")
+ .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v5", EdgeProperty.CONTAINS.toString(), true)
.next();
graph.tx().commit();
+
+ graph.traversal().V().has("aai-uri","/network/vpn-bindings/vpn-binding/deleteKey").properties().forEachRemaining(p->System.out.println(p.key() +" : " + p.value()));
}
@AfterClass
@@ -102,6 +113,10 @@ public class DataLinkTest extends AAISetup {
@Before
public void initMock() {
MockitoAnnotations.initMocks(this);
+ dbEngine = new TitanDBEngine(
+ queryStyle,
+ type,
+ loader);
}
@Test
@@ -129,7 +144,6 @@ public class DataLinkTest extends AAISetup {
assertEquals("route-target vertex found", true, traversal.V()
.has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext());
-
g.tx().rollback();
}
@@ -194,6 +208,7 @@ public class DataLinkTest extends AAISetup {
.has("linked", true)
.hasNext()
);
+
g.tx().rollback();
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java
new file mode 100644
index 00000000..89b1257f
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java
@@ -0,0 +1,79 @@
+/**
+ * ============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.introspection.tools;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+
+import static junit.framework.TestCase.assertNotNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class DefaultFieldsTest extends AAISetup {
+
+ private Loader loader;
+ private Issue issue;
+ private DefaultFields defaultFields;
+
+ @Before
+ public void setup() {
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
+ issue = new Issue();
+ defaultFields = new DefaultFields();
+ }
+
+ @Test
+ public void testDefaultFieldOfPserverIsSucccessfullyResolved() throws AAIUnknownObjectException {
+
+ Introspector pserver = loader.introspectorFromName("pserver");
+ assertNotNull("Unable to load the template introspector", pserver);
+
+ issue.setDetail("Some message");
+ issue.setType(IssueType.MISSING_REQUIRED_PROP);
+ issue.setPropName("in-maint");
+ issue.setIntrospector(pserver);
+
+ boolean isResolved = defaultFields.resolveIssue(issue);
+
+ assertTrue("Unable to resolve the pserver in-maint default field issue", isResolved);
+ assertEquals("Introspector didn't successfully modify the pserver in-maint", false,
+ pserver.getValue("in-maint"));
+ }
+
+ @Test
+ public void testDefaultFieldResolverShouldFailWhenResolveOnNonDefaultField() throws AAIUnknownObjectException {
+
+ Introspector pserver = loader.introspectorFromName("pserver");
+ assertNotNull("Unable to load the template introspector", pserver);
+
+ issue.setDetail("Some message");
+ issue.setType(IssueType.MISSING_REQUIRED_PROP);
+ issue.setPropName("hostname");
+ issue.setIntrospector(pserver);
+
+ boolean isResolved = defaultFields.resolveIssue(issue);
+
+ assertFalse("It shouldn't be resolving this issue as hostname is required key", isResolved);
+ }
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java
new file mode 100644
index 00000000..817934f0
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java
@@ -0,0 +1,94 @@
+/**
+ * ============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.introspection.tools;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+
+import java.net.URI;
+
+import static junit.framework.TestCase.assertNotNull;
+import static org.eclipse.persistence.jpa.jpql.Assert.fail;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class InjectKeysFromURITest extends AAISetup {
+
+ private Loader loader;
+ private Issue issue;
+ private InjectKeysFromURI ik;
+
+ @Before
+ public void setup() {
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
+ issue = new Issue();
+ }
+ @Test
+ public void testInjectKeysFromURIOfPserverIsNotResolved() throws AAIUnknownObjectException {
+ try {
+ ik = new InjectKeysFromURI(loader, new URI("/aai/v12/cloud-infrastructure/complexes"));
+ }catch(Exception e) {
+ fail("InjectKeys instantiation threw an exception");
+ }
+
+ Introspector pserver = loader.introspectorFromName("pserver");
+ pserver.setValue("in-maint",false);
+ pserver.setValue("hostname", "pserver2");
+ assertNotNull("Unable to load the template introspector", pserver);
+
+ issue.setDetail("Some message");
+ issue.setType(IssueType.MISSING_KEY_PROP);
+ issue.setPropName("in-maint");
+ issue.setIntrospector(pserver);
+
+ Boolean issueResolved = ik.resolveIssue(issue);
+
+ assertFalse("Unable to resolve the pserver in-maint issue", issueResolved);
+ assertEquals("Introspector didn't successfully modify the pserver in-maint", false,
+ pserver.getValue("in-maint"));
+ }
+ @Test
+ public void testInjectKeysFromURIOfPserverSuccessfullyResolved() throws AAIUnknownObjectException {
+ try {
+ ik = new InjectKeysFromURI(loader, new URI("/aai/v12/cloud-infrastructure/pservers/pserver/pserver1"));
+ }catch(Exception e) {
+ fail("InjectKeys instantiation threw an exception");
+ }
+
+ Introspector pserver = loader.introspectorFromName("pserver");
+ assertNotNull("Unable to load the template introspector", pserver);
+
+ issue.setDetail("Some message");
+ issue.setType(IssueType.MISSING_KEY_PROP);
+ issue.setPropName("hostname");
+ issue.setIntrospector(pserver);
+
+ Boolean issueResolved = ik.resolveIssue(issue);
+
+ assertTrue("Unable to resolve the pserver hostname default field issue", issueResolved);
+ assertEquals("Introspector didn't successfully modify the pserver hostname", "pserver1",
+ pserver.getValue("hostname"));
+ }
+
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java
new file mode 100644
index 00000000..7c0539b8
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java
@@ -0,0 +1,125 @@
+/**
+ * ============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.introspection.tools;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+
+import static junit.framework.TestCase.assertNotNull;
+import static org.eclipse.persistence.jpa.jpql.Assert.fail;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class IntrospectorValidatorTest extends AAISetup {
+
+ private Loader loader;
+ private Issue issue;
+ private Introspector introspector;
+ private IntrospectorValidator.Builder b;
+ private IntrospectorValidator iv;
+
+ @Before
+ public void setup() {
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
+ issue = new Issue();
+ try {
+ introspector = loader.introspectorFromName("pserver");
+ }catch(Exception e){
+ fail("Introspector instantiation call threw an exception " + e);
+ }
+ b = new IntrospectorValidator.Builder();
+ iv = b.build();
+
+ b.addResolver(new IssueResolver() {
+ @Override
+ public boolean resolveIssue(Issue issue) {
+ return true;
+ }
+ });
+ //this method does nothing
+ iv.processPrimitiveList("TEST",introspector);
+ }
+
+ public void setupIssue(String message, IssueType type, String propName, Introspector introspector){
+ issue.setDetail(message);
+ issue.setType(type);
+ issue.setPropName(propName);
+ issue.setIntrospector(introspector);
+ }
+
+ @Test
+ public void testIntrospectorValidatorMaxDepth() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ b.restrictDepth(4);
+ assertEquals("Maximum Depth should be 4", 4, b.getMaximumDepth());
+ }
+
+ @Test
+ public void testIntrospectorValidatorValidationRequired() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ b.validateRequired(true);
+ assertTrue("Validation should be required", b.getValidateRequired());
+ }
+
+ @Test
+ public void testIntrospectorValidatorValidatedFalse() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ try {
+ assertFalse("Not currently validated", iv.validate(introspector));
+ }catch (Exception e){
+ fail("Introspector validate call threw an exception " + e);
+ }
+ }
+
+ @Test
+ public void testIntrospectorValidatorResolveIssues() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ assertTrue("Introspector call to resolve issues should return true", iv.resolveIssues());
+ }
+
+ @Test
+ public void testIntrospectorValidatorGetIssues() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ iv.getIssues();
+ }
+
+ @Test
+ public void testIntrospectorValidatorProcessComplexObject() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ iv.processComplexObj(introspector);
+ }
+
+ @Test
+ public void testIntrospectorValidatorCreateComplexListSize() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ assertEquals("create complex list size should return 0", 0, iv.createComplexListSize(introspector, introspector));
+ }
+
+ @Test
+ public void testIntrospectorValidatorGetResolvers() throws AAIUnknownObjectException{
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ assertNotNull("Get resolvers should not be null", b.getResolvers());
+ }
+
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java
new file mode 100644
index 00000000..cddaf649
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java
@@ -0,0 +1,70 @@
+/**
+ * ============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.introspection.tools;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertNotNull;
+
+public class RemoveNonVisiblePropertyTest extends AAISetup {
+
+ private Loader loader;
+ private Issue issue;
+ private RemoveNonVisibleProperty rn;
+
+ @Before
+ public void setup(){
+ rn = new RemoveNonVisibleProperty();
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
+ }
+
+ @Test
+ public void testNonVisiblePropertyResolved() throws AAIUnknownObjectException {
+ Introspector introspector = loader.introspectorFromName("pserver");
+ issue = new Issue();
+ issue.setDetail("Some message");
+ issue.setType(IssueType.PROPERTY_NOT_VISIBLE);
+ issue.setPropName("in-maint");
+ issue.setIntrospector(introspector);
+ assertTrue("Nonvisible property should be removed", rn.resolveIssue(issue));
+ assertNull("Introspector did not remove the non visible property", introspector.getValue("in-maint"));
+ }
+
+ @Test
+ public void testNonVisiblePropertyNotResolved() throws AAIUnknownObjectException {
+ Introspector introspector = loader.introspectorFromName("pserver");
+ issue = new Issue();
+ issue.setDetail("Some message");
+ issue.setType(IssueType.MISSING_REQUIRED_PROP);
+ issue.setPropName("in-maint");
+ issue.setIntrospector(introspector);
+ assertFalse("Nonvisible property not present so should not have been removed", rn.resolveIssue(issue));
+ }
+
+
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
index b1ddcf6c..02e9efa1 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
@@ -27,6 +27,8 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -44,6 +46,8 @@ import javax.ws.rs.core.UriBuilder;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import static org.hamcrest.CoreMatchers.containsString;
@@ -51,13 +55,23 @@ import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
+@RunWith(value = Parameterized.class)
public class GraphTraversalTest extends AAISetup {
private TransactionalGraphEngine dbEngine;
private TransactionalGraphEngine dbEnginev9;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
+ @Rule public ExpectedException thrown = ExpectedException.none();
/**
* Configure.
@@ -68,12 +82,12 @@ public class GraphTraversalTest extends AAISetup {
@Before
public void configure() throws Exception {
dbEngine =
- new TitanDBEngine(QueryStyle.TRAVERSAL,
+ new TitanDBEngine(queryStyle,
LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST),
false);
dbEnginev9 =
- new TitanDBEngine(QueryStyle.TRAVERSAL,
+ new TitanDBEngine(queryStyle,
LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9),
false);
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java
new file mode 100644
index 00000000..97255f9e
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java
@@ -0,0 +1,130 @@
+/**
+ * ============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.query.builder;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.introspection.ModelType;
+import org.onap.aai.serialization.db.EdgeRules;
+import org.onap.aai.serialization.db.EdgeType;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+
+public class ExcludeQueryTest extends AAISetup {
+
+ private Loader loader;
+
+ @Before
+ public void setup() throws Exception {
+ loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST);
+ }
+
+ private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException{
+ return qb.createEdgeTraversal(EdgeType.TREE, "cloud-region","availability-zone").getVerticesExcludeByProperty("hypervisor-type", "hypervisortype-11").store("x").cap("x").unfold().dedup();
+ }
+
+ @Test
+ public void gremlinQueryExcludeTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ EdgeRules rules = EdgeRules.getInstance();
+ GraphTraversalSource g = graph.traversal();
+
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
+ Vertex availibityzone = graph.addVertex(T.label, "availability-zone", T.id, "1", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1", "hypervisor-type", "hypervisortype-1");
+ Vertex availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
+
+
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-10", "cloud-owner", "cloud-owner-10");
+ Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "4", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-10", "hypervisor-type", "hypervisortype-10");
+ Vertex availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
+
+ rules.addTreeEdge(g, cloudregion, availibityzone);
+ rules.addTreeEdge(g, cloudregion, availibityzone11);
+
+
+
+ rules.addTreeEdge(g, cloudregion1, availibityzone1);
+ rules.addTreeEdge(g, cloudregion1, availibityzone12);
+
+ List<Vertex> expected = new ArrayList<>();
+ expected.add(availibityzone);
+
+ GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, cloudregion);
+ QueryBuilder q = buildTestQuery(qb);
+
+ List<Vertex> results = q.toList();
+
+ assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
+ }
+
+ @Test
+ public void traversalQueryExcludeTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ EdgeRules rules = EdgeRules.getInstance();
+ GraphTraversalSource g = graph.traversal();
+
+
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
+ Vertex availibityzone = graph.addVertex(T.label, "availability-zone", T.id, "1", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1", "hypervisor-type", "hypervisortype-1");
+ Vertex availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
+
+
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-10", "cloud-owner", "cloud-owner-10");
+ Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "4", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-10", "hypervisor-type", "hypervisortype-10");
+ Vertex availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
+
+ rules.addTreeEdge(g, cloudregion, availibityzone);
+ rules.addTreeEdge(g, cloudregion, availibityzone11);
+
+
+
+ rules.addTreeEdge(g, cloudregion1, availibityzone1);
+ rules.addTreeEdge(g, cloudregion1, availibityzone12);
+
+ List<Vertex> expected = new ArrayList<>();
+ expected.add(availibityzone);
+
+
+
+
+ TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, cloudregion);
+ QueryBuilder<Vertex> q = buildTestQuery(qb);
+
+ List<Vertex> results = q.toList();
+
+ assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
+ }
+
+
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
index 98ac0dee..3632543f 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
@@ -19,28 +19,39 @@
*/
package org.onap.aai.query.builder;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
public class GremlinTraversalTest extends QueryBuilderTestAbstraction {
@Override
- protected QueryBuilder<Edge> getNewEdgeTraversal(Vertex v) {
+ protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v) {
return new GremlinTraversal<>(loader, g, v, testEdgeRules);
}
@Override
- protected QueryBuilder<Edge> getNewEdgeTraversal() {
+ protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules() {
return new GremlinTraversal<>(loader, g, testEdgeRules);
}
@Override
- protected QueryBuilder<Vertex> getNewVertexTraversal(Vertex v) {
+ protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules(Vertex v) {
return new GremlinTraversal<>(loader, g, v, testEdgeRules);
}
@Override
- protected QueryBuilder<Vertex> getNewVertexTraversal() {
+ protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules() {
+ return new GremlinTraversal<>(loader, g, testEdgeRules);
+ }
+
+ @Override
+ protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules(Vertex v) {
+ return new GremlinTraversal<>(loader, g, v, testEdgeRules);
+ }
+
+ @Override
+ protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules() {
return new GremlinTraversal<>(loader, g, testEdgeRules);
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
index bd8f078a..9cdab403 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
@@ -19,17 +19,10 @@
*/
package org.onap.aai.query.builder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
+import com.thinkaurelius.titan.core.TitanFactory;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -42,10 +35,15 @@ import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.serialization.db.EdgeRules;
import org.onap.aai.serialization.db.EdgeType;
-
-import com.thinkaurelius.titan.core.TitanFactory;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
public abstract class QueryBuilderTestAbstraction extends AAISetup {
protected static Loader loader;
@@ -83,7 +81,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex vnfc = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
testEdgeRules.addEdge(g, gvnf, vnfc, "uses");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "vnfc");
assertEquals(vnfc, tQ.next());
@@ -98,7 +96,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
testEdgeRules.addEdge(g, lInterface, logicalLink, "sourceLInterface");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(lInterface);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
tQ.createEdgeTraversal(EdgeType.COUSIN, "l-interface", "logical-link");
Vertex next = tQ.next();
@@ -107,7 +105,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
}
-
+
@Test
public void createEdgeLinterfaceToLogicalLinkIntrospectorTraversal() throws AAIException {
@@ -115,7 +113,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
testEdgeRules.addEdge(g, lInterface, logicalLink, "sourceLInterface");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(lInterface);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
tQ.createEdgeTraversal(EdgeType.COUSIN, loader.introspectorFromName("l-interface"), loader.introspectorFromName("logical-link"));
Vertex next = tQ.next();
@@ -132,7 +130,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
testEdgeRules.addEdge(g, lInterface, logicalLink, "sourceLInterface");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(lInterface);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
tQ.createEdgeTraversal(EdgeType.COUSIN, lInterface, loader.introspectorFromName("logical-link"));
Vertex next = tQ.next();
@@ -150,7 +148,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, vnfc1);
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "vnfc");
List<Vertex> list = tQ.toList();
@@ -169,10 +167,10 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, vce, vnfc1);
- QueryBuilder<Vertex> tQ1 = getNewVertexTraversal(vce);
+ QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vce", "vnfc");
- QueryBuilder<Vertex> tQ2 = getNewVertexTraversal(vnfc1);
+ QueryBuilder<Vertex> tQ2 = getNewVertexTraversalWithTestEdgeRules(vnfc1);
tQ2.createEdgeTraversal(EdgeType.COUSIN, "vnfc", "vce");
List<Vertex> list1 = tQ1.toList();
@@ -194,7 +192,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, vce, pserver);
- QueryBuilder<Vertex> tQ1 = getNewVertexTraversal(vce);
+ QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vce", "pserver");
List<Vertex> list = tQ1.toList();
@@ -215,7 +213,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, vnfc1);
testEdgeRules.addEdge(g, gvnf, vnfc2, "re-uses");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "vnfc");
List<Vertex> list = tQ.toList();
@@ -237,7 +235,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, vnfc1);
testEdgeRules.addEdge(g, pserver, vnfc1);
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(vnfc1);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(vnfc1);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnfc", "generic-vnf");
List<Vertex> list = tQ.toList();
@@ -305,7 +303,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, pserver);
testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "pserver").dedup();
List<Vertex> list = tQ.toList();
@@ -345,7 +343,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, pserver);
testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "pserver").store("x").cap("x").unfold();
List<Vertex> list = tQ.toList();
@@ -385,7 +383,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, pserver);
testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "pserver");
List<Vertex> list = tQ.toList();
@@ -405,7 +403,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
testEdgeRules.addEdge(g, gvnf, complex);
testEdgeRules.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "complex");
List<Vertex> list = tQ.toList();
@@ -424,7 +422,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e = testEdgeRules.addEdge(g, vce, pserver);
- QueryBuilder<Edge> tQ1 = getNewEdgeTraversal(vce);
+ QueryBuilder<Edge> tQ1 = getNewEdgeTraversalWithTestEdgeRules(vce);
tQ1.getEdgesBetween(EdgeType.COUSIN, "vce", "pserver");
List<Edge> list = tQ1.toList();
@@ -443,7 +441,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e = testEdgeRules.addEdge(g, vce, vnfc1);
- QueryBuilder<Edge> tQ1 = getNewEdgeTraversal(vce);
+ QueryBuilder<Edge> tQ1 = getNewEdgeTraversalWithTestEdgeRules(vce);
tQ1.getEdgesBetween(EdgeType.COUSIN, "vce", "vnfc");
List<Edge> list1 = tQ1.toList();
@@ -463,7 +461,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetween(EdgeType.COUSIN, "generic-vnf", "pserver");
List<Edge> list = tQ.toList();
@@ -484,7 +482,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, complex);
Edge e2 = testEdgeRules.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetween(EdgeType.COUSIN, "generic-vnf", "complex");
List<Edge> list = tQ.toList();
@@ -506,7 +504,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, vnfc1);
Edge e2 = testEdgeRules.addEdge(g, gvnf, vnfc2, "re-uses");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetween(EdgeType.COUSIN, "generic-vnf", "vnfc");
List<Edge> list = tQ.toList();
@@ -524,10 +522,10 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
- Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
- Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
+ testEdgeRules.addEdge(g, gvnf, pserver);
+ testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.emptyList());
}
@@ -541,7 +539,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.singletonList("generic-vnf-pserver-B"));
List<Edge> list = tQ.toList();
@@ -561,7 +559,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
List<Edge> list = tQ.toList();
@@ -577,10 +575,10 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex gvnf = getVertex();
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.emptyList());
- List<Edge> list = tQ.toList();
+ tQ.toList();
}
@@ -589,8 +587,8 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
- Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
- Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
+ testEdgeRules.addEdge(g, gvnf, pserver);
+ testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
return gvnf;
}
@@ -603,7 +601,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.singletonList("generic-vnf-pserver-B"));
List<Edge> list = tQ.toList();
@@ -623,7 +621,7 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
Edge e1 = testEdgeRules.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Edge> tQ = getNewEdgeTraversal(gvnf);
+ QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
List<Edge> list = tQ.toList();
@@ -634,13 +632,17 @@ public abstract class QueryBuilderTestAbstraction extends AAISetup {
}
- protected abstract QueryBuilder<Edge> getNewEdgeTraversal(Vertex v);
+ protected abstract QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v);
- protected abstract QueryBuilder<Edge> getNewEdgeTraversal();
+ protected abstract QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules();
- protected abstract QueryBuilder<Vertex> getNewVertexTraversal(Vertex v);
+ protected abstract QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules(Vertex v);
- protected abstract QueryBuilder<Vertex> getNewVertexTraversal();
+ protected abstract QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules();
+
+ protected abstract QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules(Vertex v);
+
+ protected abstract QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules();
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
index d5a0e4ab..1eeca6f0 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
@@ -19,16 +19,9 @@
*/
package org.onap.aai.query.builder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.List;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
@@ -36,63 +29,86 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.EdgeType;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
public class TraversalQueryTest extends QueryBuilderTestAbstraction {
@Override
- protected QueryBuilder<Edge> getNewEdgeTraversal(Vertex v) {
+ protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v) {
return new TraversalQuery<>(loader, g, v, testEdgeRules);
}
@Override
- protected QueryBuilder<Edge> getNewEdgeTraversal() {
+ protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules() {
return new TraversalQuery<>(loader, g, testEdgeRules);
}
@Override
- protected QueryBuilder<Vertex> getNewVertexTraversal(Vertex v) {
+ protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules(Vertex v) {
return new TraversalQuery<>(loader, g, v, testEdgeRules);
}
@Override
+ protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules() {
+ return new TraversalQuery<>(loader, g, testEdgeRules);
+ }
+
+
protected QueryBuilder<Vertex> getNewVertexTraversal() {
+ return new TraversalQuery<>(loader, g);
+ }
+
+ @Override
+ protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules(Vertex v) {
+ return new TraversalQuery<>(loader, g, v, testEdgeRules);
+ }
+
+ @Override
+ protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules() {
return new TraversalQuery<>(loader, g, testEdgeRules);
}
@Test
public void unionQuery() {
- QueryBuilder<Vertex> tQ = new TraversalQuery<>(loader, g);
- QueryBuilder<Vertex> tQ2 = new TraversalQuery<>(loader, g);
- QueryBuilder<Vertex> tQ3 = new TraversalQuery<>(loader, g);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversal();
+ QueryBuilder<Vertex> tQ2 = getNewVertexTraversal();
+ QueryBuilder<Vertex> tQ3 = getNewVertexTraversal();
tQ.union(
tQ2.getVerticesByProperty("test1", "value1"),
tQ3.getVerticesByIndexedProperty("test2", "value2"));
-
+
GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
.union(__.has("test1", "value1"),__.has("test2", "value2"));
-
+
assertEquals("they are equal", expected, tQ.getQuery());
-
+
}
@Test
public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException {
- QueryBuilder<Vertex> tQ = new TraversalQuery<>(loader, g);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversal();
QueryBuilder<Vertex> builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")).getQueryBuilder();
GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf");
GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("aai-node-type", "generic-vnf");
-
+
assertEquals("query object", expected.toString(), builder.getQuery().toString());
assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString());
-
+
}
@Test
public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException {
-
- QueryBuilder<Vertex> tQ = new TraversalQuery<>(loader, g);
+
+ QueryBuilder<Vertex> tQ = getNewVertexTraversal();
QueryBuilder<Vertex> builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder();
GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
.has("vnf-id", "key1")
@@ -119,7 +135,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, gvnf, vnfc1);
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
List<Vertex> list = tQ.toList();
@@ -138,10 +154,10 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, vce, vnfc1);
- QueryBuilder<Vertex> tQ1 = new TraversalQuery<>(loader, g, vce, testEdgeRules);
+ QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
- QueryBuilder<Vertex> tQ2 = new TraversalQuery<>(loader, g, vnfc1, testEdgeRules);
+ QueryBuilder<Vertex> tQ2 = getNewVertexTraversalWithTestEdgeRules(vnfc1);
tQ2.createEdgeTraversal(EdgeType.COUSIN, "vnfc", "vnf");
List<Vertex> list1 = tQ1.toList();
@@ -163,7 +179,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, vce, pserver);
- QueryBuilder<Vertex> tQ1 = new TraversalQuery<>(loader, g, vce, testEdgeRules);
+ QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vnf", "pserver");
List<Vertex> list = tQ1.toList();
@@ -184,7 +200,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, gvnf, vnfc1);
testEdgeRules.addEdge(g, gvnf, vnfc2, "re-uses");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
List<Vertex> list = tQ.toList();
@@ -205,7 +221,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, gvnf, pserver);
testEdgeRules.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "pserver");
List<Vertex> list = tQ.toList();
@@ -225,7 +241,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
testEdgeRules.addEdge(g, gvnf, complex);
testEdgeRules.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
- QueryBuilder<Vertex> tQ = getNewVertexTraversal(gvnf);
+ QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "complex");
List<Vertex> list = tQ.toList();
@@ -235,7 +251,7 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
}
-
-
+
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java b/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
index 5abe4daf..6ffc10f6 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
@@ -24,14 +24,18 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAIJunitRunner;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import javax.ws.rs.core.Response;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
import static org.junit.Assert.assertEquals;
@@ -40,14 +44,24 @@ import static org.junit.Assert.assertEquals;
* children nodes associated to it then you should be able to
* remove the cloud region without removing the individual child nodes first
*/
-@RunWith(AAIJunitRunner.class)
+@RunWith(value = AAIJunitRunner.class)
public class CloudRegionTest {
private HttpTestUtil httpTestUtil;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
public void setUp(){
- httpTestUtil = new HttpTestUtil();
+ httpTestUtil = new HttpTestUtil(queryStyle);
}
@Ignore("Test is failing due to the deletion of node with children not correct will be fixed soon")
@@ -70,5 +84,4 @@ public class CloudRegionTest {
response = httpTestUtil.doDelete(cloudRegionUri, resourceVersion);
assertEquals("Expected the cloud region to be deleted", 204, response.getStatus());
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java b/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
index 9f8045b8..14ff6d5a 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
@@ -23,25 +23,40 @@ import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAIJunitRunner;
+import org.onap.aai.AAISetup;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
-@RunWith(AAIJunitRunner.class)
-public class GenericVnfLInterfaceTest {
+@RunWith(value = AAIJunitRunner.class)
+public class GenericVnfLInterfaceTest extends AAISetup {
private HttpTestUtil httpTestUtil;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
public void setUp(){
- httpTestUtil = new HttpTestUtil();
+ httpTestUtil = new HttpTestUtil(queryStyle);
}
@Test
@@ -57,7 +72,8 @@ public class GenericVnfLInterfaceTest {
response = httpTestUtil.doGet("/aai/v12/network/generic-vnfs/generic-vnf/vnf1");
assertEquals("Expecting the generic vnf to be updated", 200, response.getStatus());
- resource = response.getEntity().toString().replaceAll("ipv1\",\"resource-version\":\"\\d+\"", "ipv2\"");
+ resource = response.getEntity().toString();
+ resource = resource.replaceAll("ipv1\",\"resource-version\":\"\\d+\"", "ipv2\"");
response = httpTestUtil.doPut("/aai/v12/network/generic-vnfs/generic-vnf/vnf1", resource);
assertEquals("Expecting the generic vnf to be updated", 200, response.getStatus());
diff --git a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
index ed7d8e36..279b9c73 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
@@ -25,20 +25,17 @@ import com.jayway.jsonpath.JsonPath;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAIJunitRunner;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
-import org.onap.aai.introspection.*;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
@RunWith(AAIJunitRunner.class)
public class HPACapabilityTest {
@@ -47,9 +44,19 @@ public class HPACapabilityTest {
private HttpTestUtil httpTestUtil;
private Map<String, String> templateValuesMap;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
public void setup() {
- httpTestUtil = new HttpTestUtil();
+ httpTestUtil = new HttpTestUtil(queryStyle);
templateValuesMap = new HashMap<>();
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
index d97c706b..32c7483f 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
@@ -25,29 +25,43 @@ import com.jayway.jsonpath.JsonPath;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAIJunitRunner;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
import org.onap.aai.introspection.*;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-@RunWith(AAIJunitRunner.class)
+@RunWith(value = AAIJunitRunner.class)
public class PserverTest {
private static EELFLogger logger = EELFManager.getInstance().getLogger(PserverTest.class);
private HttpTestUtil httpTestUtil;
private Map<String, String> relationshipMap;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
- public void setup(){
- httpTestUtil = new HttpTestUtil();
+ public void setUp(){
+ httpTestUtil = new HttpTestUtil(queryStyle);
relationshipMap = new HashMap<>();
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java b/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
index d454c783..72ea49ad 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
@@ -24,28 +24,37 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAIJunitRunner;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
import static org.junit.Assert.assertEquals;
-@RunWith(AAIJunitRunner.class)
+@RunWith(value = AAIJunitRunner.class)
public class TenantTest {
private HttpTestUtil httpTestUtil;
-
private Map<String, String> templateValuesMap;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
- public void setup(){
- httpTestUtil = new HttpTestUtil();
+ public void setUp(){
+ httpTestUtil = new HttpTestUtil(queryStyle);
templateValuesMap = new HashMap<>();
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
index cf6f1774..6ff75c7f 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
@@ -19,41 +19,40 @@
*/
package org.onap.aai.rest.db;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
import org.javatuples.Pair;
import org.junit.Before;
import org.junit.FixMethodOrder;
-import org.junit.runners.MethodSorters;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.domain.yang.Pserver;
-import org.onap.aai.domain.yang.Pservers;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
+import org.onap.aai.introspection.Version;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import javax.ws.rs.core.*;
-
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.*;
-import java.util.stream.Collectors;
-
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
+import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.when;
+@RunWith(value = Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HttpEntryTest extends AAISetup {
@@ -67,6 +66,16 @@ public class HttpEntryTest extends AAISetup {
VALID_HTTP_STATUS_CODES.add(204);
}
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
private HttpHeaders httpHeaders;
private UriInfo uriInfo;
@@ -114,7 +123,7 @@ public class HttpEntryTest extends AAISetup {
when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
}
- private Response getResponse(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, String uri, String content) throws UnsupportedEncodingException, AAIException {
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, String uri, String content) throws UnsupportedEncodingException, AAIException {
URI uriObject = UriBuilder.fromPath(uri).build();
QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
String objType = uriQuery.getResultType();
@@ -144,13 +153,13 @@ public class HttpEntryTest extends AAISetup {
public void test1PutOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1";
String content = "{\"hostname\":\"junit-test1\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
dbEngine.commit();
assertEquals("Expected the pserver to be created", 201, response.getStatus());
}
@@ -159,13 +168,13 @@ public class HttpEntryTest extends AAISetup {
public void test2PutOnPserverNoPInterface() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test2";
String content = "{\"hostname\":\"junit-test2\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
dbEngine.commit();
assertEquals("Expected the pserver to be created", 201, response.getStatus());
}
@@ -174,13 +183,13 @@ public class HttpEntryTest extends AAISetup {
public void test3PutOnPInterface() {
try {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1/p-interfaces/p-interface/p1";
String content = "{\"interface-name\":\"p1\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
dbEngine.commit();
assertEquals("Expected the p-interface to be created", 201, response.getStatus());
} catch (UnsupportedEncodingException | AAIException e) {
@@ -195,7 +204,7 @@ public class HttpEntryTest extends AAISetup {
public void test4GetOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
@@ -203,7 +212,7 @@ public class HttpEntryTest extends AAISetup {
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1";
String content = "{\"hostname\":\"junit-test1\", \"equip-type\":\"junit-equip-type\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
dbEngine.commit();
assertEquals("Expected the pserver to be returned", 200, response.getStatus());
}
@@ -212,13 +221,13 @@ public class HttpEntryTest extends AAISetup {
public void test5MergePatchOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1";
String content = "{\"hostname\":\"junit-test1\", \"equip-type\":\"junit-equip-type\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.MERGE_PATCH, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.MERGE_PATCH, uri, content);
dbEngine.commit();
assertEquals("Expected the pserver to be updated", 200, response.getStatus());
}
@@ -226,7 +235,7 @@ public class HttpEntryTest extends AAISetup {
private int doDelete(String resourceVersion, String uri, String nodeType) throws UnsupportedEncodingException, AAIException {
queryParameters.add("resource-version", resourceVersion);
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
@@ -256,14 +265,14 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath("/cloud-infrastructure/pservers/pserver/junit-test1").build();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1";
String content = "";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
dbEngine.commit();
String msg = response.getEntity().toString();
JsonObject jsonObj = new JsonParser().parse(msg).getAsJsonObject();
@@ -279,13 +288,13 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test2";
String content = "";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
dbEngine.commit();
String msg = response.getEntity().toString();
JsonObject jsonObj = new JsonParser().parse(msg).getAsJsonObject();
@@ -301,13 +310,13 @@ public class HttpEntryTest extends AAISetup {
public void test8FailedGetOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
String uri = "/cloud-infrastructure/pservers/pserver/junit-test2";
String content = "";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
dbEngine.commit();
assertEquals("Expected the pserver to be deleted", 404, response.getStatus());
@@ -317,55 +326,89 @@ public class HttpEntryTest extends AAISetup {
public void putEdgeTest() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
//Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
- getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
//Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
- getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
//PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + Version.getLatest().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
dbEngine.rollback();
//System.out.println(response.getEntity().toString());
- assertEquals("Expected the pserver to be created", 200, response.getStatus());
+ assertEquals("Expected the pserver relationship to be created", 200, response.getStatus());
}
@Test
public void putEdgeWrongLabelTest() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
- HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = httpEntry.getLoader();
TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
//Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
- getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
//Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
- getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
//PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + Version.getLatest().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"junk\"}";
- Response response = getResponse(httpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
dbEngine.rollback();
String msg = response.getEntity().toString();
assertEquals("Expected the pserver to be created", 400, response.getStatus());
- assertTrue(msg.contains("ERR.5.4.6107"));
- assertTrue(msg.contains("Required Edge-property not found in input data:no COUSIN edge rule between complex and pserver with label junk"));
+ assertThat(msg, containsString("ERR.5.4.6107"));
+ assertThat(msg, containsString("Required Edge-property not found in input data:no COUSIN edge rule between complex and pserver with label junk"));
+
+ }
+
+ @Test
+ public void relatedToTest() throws UnsupportedEncodingException, AAIException {
+
+ DBConnectionType type = DBConnectionType.REALTIME;
+ HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ Loader loader = httpEntry.getLoader();
+ TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
+
+ //Put pserver
+ String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
+ String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ //Put complex
+ uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
+ content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+
+ //PutEdge
+ uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + Version.getLatest().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+ doRequest(httpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
+
+ //getRelatedTo
+ uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/related-to/pservers";
+ content = "";
+ Response response = doRequest(httpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
+ String respBody = response.getEntity().toString();
+
+ dbEngine.rollback();
+ assertEquals("Expected the pserver to be created", 200, response.getStatus());
+ assertThat("Related to pserver is returned.", respBody, containsString("\"hostname\":\"junit-edge-test-pserver\""));
}
-}
+} \ No newline at end of file
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
index e00c7eb3..27d14c94 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
@@ -27,6 +27,8 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
@@ -42,6 +44,8 @@ import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.Map;
@@ -49,17 +53,27 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+@RunWith(value = Parameterized.class)
public class DbAliasTest extends AAISetup {
private TitanGraph graph;
private final Version version = Version.v9;
private final ModelType introspectorFactoryType = ModelType.MOXY;
- private final QueryStyle queryStyle = QueryStyle.TRAVERSAL;
private final DBConnectionType type = DBConnectionType.REALTIME;
private Loader loader;
private TransactionalGraphEngine dbEngine;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@Before
public void setup() throws Exception {
graph = TitanFactory.build().set("storage.backend","inmemory").open();
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
index cff374ca..3cf43b4a 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
@@ -19,40 +19,35 @@
*/
package org.onap.aai.serialization.db;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Field;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-
+import com.thinkaurelius.titan.core.TitanFactory;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.T;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.*;
import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
+import org.onap.aai.introspection.*;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TitanDBEngine;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import com.thinkaurelius.titan.core.TitanFactory;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Field;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+@RunWith(value = Parameterized.class)
public class DbSerializerTest extends AAISetup {
//to use, set thrown.expect to whatever your test needs
@@ -65,7 +60,6 @@ public class DbSerializerTest extends AAISetup {
private final Version version = Version.getLatest();
private final ModelType introspectorFactoryType = ModelType.MOXY;
- private final QueryStyle queryStyle = QueryStyle.TRAVERSAL;
private final DBConnectionType type = DBConnectionType.REALTIME;
private Loader loader;
private TransactionalGraphEngine dbEngine;
@@ -74,15 +68,25 @@ public class DbSerializerTest extends AAISetup {
TransactionalGraphEngine spy;
TransactionalGraphEngine.Admin adminSpy;
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {QueryStyle.TRAVERSAL}
+ });
+ }
+
@BeforeClass
public static void init() throws Exception {
graph = TitanFactory.build().set("storage.backend", "inmemory").open();
- createGraph();
}
@Before
public void setup() throws Exception {
+ //createGraph();
loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
dbEngine = new TitanDBEngine(queryStyle, type, loader);
spy = spy(dbEngine);
@@ -93,29 +97,6 @@ public class DbSerializerTest extends AAISetup {
dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
}
- public static void createGraph() throws AAIException {
- /*
- * This setus up the test graph, For future junits , add more vertices
- * and edges
- */
-
- Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
- Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
- Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
- Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
- Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
- Vertex l3network_6 = graph.traversal()
- .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
- .next();
-
- GraphTraversalSource g = graph.traversal();
- EdgeRules.getInstance().addEdge(g, l3interipv4addresslist_1, subnet_2);
- EdgeRules.getInstance().addEdge(g, l3interipv6addresslist_3, subnet_4);
- EdgeRules.getInstance().addTreeEdge(g, subnet_5, l3network_6);
- }
-
@Test
public void testFindDeletableDoesNotReturnDuplicates() throws AAIException {
@@ -166,8 +147,33 @@ public class DbSerializerTest extends AAISetup {
graph.close();
}
+
+ public void subnetSetup() throws AAIException {
+ /*
+ * This setus up the test graph, For future junits , add more vertices
+ * and edges
+ */
+
+ Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
+ Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
+ Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
+ Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
+ Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
+ Vertex l3network_6 = graph.traversal()
+ .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
+ .next();
+
+ GraphTraversalSource g = graph.traversal();
+ EdgeRules.getInstance().addEdge(g, l3interipv4addresslist_1, subnet_2);
+ EdgeRules.getInstance().addEdge(g, l3interipv6addresslist_3, subnet_4);
+ EdgeRules.getInstance().addTreeEdge(g, subnet_5, l3network_6);
+ }
+
@Test
public void subnetDelWithInEdgesIpv4Test() throws AAIException {
+ subnetSetup();
String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]";
/*
@@ -182,6 +188,7 @@ public class DbSerializerTest extends AAISetup {
@Test
public void subnetDelWithInEdgesIpv6Test() throws AAIException {
+ subnetSetup();
String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]";
/*
@@ -195,6 +202,7 @@ public class DbSerializerTest extends AAISetup {
@Test
public void subnetDelWithInEdgesL3network() throws AAIException {
+ subnetSetup();
String expected_message = "";
/*
@@ -278,6 +286,37 @@ public class DbSerializerTest extends AAISetup {
}
@Test
+ public void serializeToDbNewVertexAndEdgeAAIUUIDTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
+ String testName = new Object() {}.getClass().getEnclosingMethod().getName();
+ EdgeRules ers = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test.json");
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules(ers);
+
+ engine.startTransaction();
+
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","vnfc-" + testName, AAIProperties.AAI_URI, "/network/vnfcs/vnfc/vnfc-" + testName);
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/vnfc-" + testName);
+
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "vnf-" + testName);
+
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/vnf-" + testName));
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+ assertTrue("Generic-vnf has uuid ", gvnf.property(AAIProperties.AAI_UUID).isPresent());
+ assertTrue("Edge has uuid ", gvnf.edges(Direction.BOTH).next().property(AAIProperties.AAI_UUID).isPresent());
+
+
+ }
+
+ @Test
public void verifyResourceVersion_SunnyDayTest() throws AAIException {
engine.startTransaction();
@@ -400,8 +439,8 @@ public class DbSerializerTest extends AAISetup {
public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
EdgeRules rules = EdgeRules.getInstance();
rules.addEdge(engine.tx().traversal(), gvnf, vnfc);
@@ -424,8 +463,8 @@ public class DbSerializerTest extends AAISetup {
public void createEdgeTest() throws AAIException, UnsupportedEncodingException {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
//sunny day case
Introspector relData = loader.introspectorFromName("relationship-data");
@@ -446,8 +485,8 @@ public class DbSerializerTest extends AAISetup {
public void createCousinEdgeThatShouldBeTreeTest() throws AAIException, UnsupportedEncodingException, URISyntaxException {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vf = engine.tx().addVertex("aai-node-type","vf-module","vf-module-id","vf-id");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vf = engine.tx().addVertex("aai-node-type","vf-module","vf-module-id","vf-id", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/vf-id");
EdgeRules.getInstance().addTreeEdge(engine.tx().traversal(), gvnf, vf);
@@ -475,7 +514,7 @@ public class DbSerializerTest extends AAISetup {
public void createEdgeNodeDoesNotExistExceptionTest() throws AAIException, UnsupportedEncodingException {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
//rainy day case, edge to non-existent object
Introspector relData = loader.introspectorFromName("relationship-data");
@@ -579,8 +618,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
//sunny day case
Introspector relData = loader.introspectorFromName("relationship-data");
@@ -603,8 +642,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relData = loader.introspectorFromName("relationship-data");
relData.setValue("relationship-key", "vnfc.vnfc-name");
@@ -630,8 +669,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
ers.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
Introspector relData = loader.introspectorFromName("relationship-data");
@@ -658,8 +697,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
ers.addEdge(graph.traversal(), gvnf, vnfc, "uses");
Introspector relData = loader.introspectorFromName("relationship-data");
@@ -692,8 +731,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relData = loader.introspectorFromName("relationship-data");
relData.setValue("relationship-key", "vnfc.vnfc-name");
@@ -722,8 +761,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
ers.addEdge(graph.traversal(), gvnf, vnfc, "uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
@@ -756,8 +795,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
ers.addEdge(graph.traversal(), gvnf, vnfc, "uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
@@ -791,8 +830,8 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
ers.addEdge(graph.traversal(), gvnf, vnfc, "uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
ers.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
@@ -819,7 +858,7 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relationship = loader.introspectorFromName("relationship");
relationship.setValue("related-to", "vnfc");
@@ -858,7 +897,7 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relationship = loader.introspectorFromName("relationship");
relationship.setValue("related-to", "vnfc");
@@ -897,7 +936,7 @@ public class DbSerializerTest extends AAISetup {
engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relationship = loader.introspectorFromName("relationship");
relationship.setValue("related-to", "vnfc");
@@ -926,7 +965,7 @@ public class DbSerializerTest extends AAISetup {
DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules(ers);
engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
Introspector relationship;
Introspector relationshipList;
@@ -982,7 +1021,8 @@ public class DbSerializerTest extends AAISetup {
DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules(ers);
engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name");
+ engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
Introspector relationship;
Introspector relationshipList;
@@ -1145,14 +1185,15 @@ public class DbSerializerTest extends AAISetup {
ModelType.MOXY, "AAI-TEST");
engine.startTransaction();
- Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
- Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
+ Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", "aai-uri", "/network/generic-vnfs/generic-vnf/id1");
+ Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface");
rules.addTreeEdge(engine.tx().traversal(), gv, lint);
Introspector lintIntro = loader.introspectorFromName("l-interface");
+ lintIntro.setValue("interface-name", "name1");
lintIntro.setValue("interface-role", "actor");
URI lintURI = new URI("/network/generic-vnfs/generic-vnf/id1/l-interfaces/l-interface/name1");
- QueryParser uriQuery = dbEngine.getQueryBuilder(gv).createQueryFromURI(lintURI);
+ QueryParser uriQuery = engine.getQueryBuilder(gv).createQueryFromURI(lintURI);
dbser.serializeToDb(lintIntro, lint, uriQuery, "test-identifier", "AAI-TEST");
assertTrue(engine.tx().traversal().V(lint).has("interface-role", "actor").hasNext());
@@ -1174,4 +1215,4 @@ public class DbSerializerTest extends AAISetup {
assertTrue("very-fast".equals(res.getValue("speed-value")));
assertTrue("things".equals(res.getValue("service-provider-bandwidth-up-units")));
}
-} \ No newline at end of file
+}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
index 81d4c885..60691acb 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
@@ -157,7 +157,6 @@ public class EdgeRulesTest extends AAISetup {
assertEquals(true, "IN".equalsIgnoreCase(rule.getContains()));
assertEquals(true, "NONE".equalsIgnoreCase(rule.getDeleteOtherV()));
assertEquals(true, MultiplicityRule.MANY2ONE.equals(rule.getMultiplicityRule()));
- assertEquals(true, "OUT".equalsIgnoreCase(rule.getServiceInfrastructure()));
assertEquals(true, "IN".equalsIgnoreCase(rule.getPreventDelete()));
}
@@ -242,23 +241,6 @@ public class EdgeRulesTest extends AAISetup {
}
@Test
- public void getChildrenMissingPropertyTest() {
- EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json");
-
- thrown.expect(RuntimeException.class);
- thrown.expectMessage("org.onap.aai.exceptions.AAIException: Rule between quux and foo is missing property SVC-INFRA.");
- rules.getChildren("foo");
- }
-
- @Test
- public void getEdgeRuleMissingPropertyTest() throws AAIException {
- EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json");
-
- thrown.expect(RuntimeException.class);
- rules.getEdgeRules("foo", "quux");
- }
-
- @Test
public void verifyAllRules() {
// This will cause every rule in the real json files to be verified
// so if any required properties are missing, the verification builds
diff --git a/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java b/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java
new file mode 100644
index 00000000..deefdc1b
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java
@@ -0,0 +1,125 @@
+/**
+ * ============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.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Properties;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.exceptions.AAIException;
+
+public class AAIConfigTest extends AAISetup {
+
+ @BeforeClass
+ public static void setUp() throws AAIException {
+ AAIConfig.init();
+ }
+
+ @Test
+ public void testGetDefaultBools() {
+ HashMap<String,ArrayList<String>> res = AAIConfig.getDefaultBools();
+ assertNotNull(res);
+ assertEquals(6, res.size());
+ assertEquals("in-maint", res.get("generic-vnf").get(0));
+ assertEquals("is-closed-loop-disabled", res.get("generic-vnf").get(1));
+ assertEquals("is-bound-to-vpn", res.get("l3-network").get(0));
+ assertEquals("in-maint", res.get("pserver").get(0));
+ assertEquals("dhcp-enabled", res.get("subnet").get(0));
+ assertEquals("in-maint", res.get("vserver").get(0));
+ assertEquals("is-closed-loop-disabled", res.get("vserver").get(1));
+ assertEquals("in-maint", res.get("vnfc").get(0));
+ assertEquals("is-closed-loop-disabled", res.get("vnfc").get(1));
+ }
+
+ @Test
+ public void testGetConfigFile() {
+ String res = AAIConfig.getConfigFile();
+ assertNotNull(res);
+ assertTrue(res.endsWith("aaiconfig.properties"));
+ }
+
+ @Test
+ public void testGetStringStringReturnDefaultvalue() {
+ String res = AAIConfig.get("key", "result");
+ assertNotNull(res);
+ assertEquals("result", res);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStringInvalidKey() throws AAIException {
+ AAIConfig.get("key");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStringEmptyResponse() throws AAIException {
+ AAIConfig.get("aai.response.null");
+ }
+
+ @Test
+ public void testGetStringReloadConfig() throws AAIException {
+ String res = AAIConfig.get("aai.config.nodename");
+ assertNotNull(res);
+ assertEquals(AAIConfig.getNodeName(), res);
+ }
+
+ @Test
+ public void testGetServerProps() {
+ Properties res = AAIConfig.getServerProps();
+ assertNotNull(res);
+ }
+
+ @Test
+ public void testGetNodeName() throws UnknownHostException {
+ InetAddress ip = InetAddress.getLocalHost();
+ String res = AAIConfig.getNodeName();
+ assertNotNull(res);
+ assertEquals(ip.getHostName(), res);
+ }
+
+ @Test
+ public void testIsEmpty() {
+ boolean res = AAIConfig.isEmpty("hllo world");
+ assertFalse(res);
+ }
+
+ @Test
+ public void testIsEmptyEmpty() {
+ boolean res = AAIConfig.isEmpty("");
+ assertTrue(res);
+ }
+
+ @Test
+ public void testIsEmptyNull() {
+ boolean res = AAIConfig.isEmpty(null);
+ assertTrue(res);
+ }
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/util/AutoGenerateHtmlTest.java b/aai-core/src/test/java/org/onap/aai/util/AutoGenerateHtmlTest.java
new file mode 100644
index 00000000..f2f9f61a
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/AutoGenerateHtmlTest.java
@@ -0,0 +1,35 @@
+/**
+ * ============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 java.io.IOException;
+
+import org.junit.Test;
+
+import freemarker.template.TemplateException;
+
+public class AutoGenerateHtmlTest {
+
+ @Test(expected=NullPointerException.class)
+ public void testMain() throws IOException, TemplateException {
+ AutoGenerateHtml.main(new String[] {});
+ }
+
+}
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
index 6fa55559..f8ede632 100644
--- a/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java
@@ -19,271 +19,81 @@
*/
package org.onap.aai.util;
+import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
-import java.io.StringReader;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.File;
import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
import org.junit.Before;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
import org.onap.aai.introspection.Version;
+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;
public class GenerateXsdTest {
- private static final int maxSizeForXml = 20000;
- private String testXML;
+ private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class");
+ private String testXML;
@Before
public void setUp() throws Exception {
//PowerMockito.mockStatic(GenerateXsd.class);
- StringBuilder sb = new StringBuilder(maxSizeForXml);
- addNamespace(sb);
- addRelationshipList(sb);
- addRelationship(sb);
- addRelatedToProperty(sb);
- addRelationshipData(sb);
- addBusiness(sb);
- addCustomers(sb);
- addCustomer(sb);
- addServiceSubscriptions(sb);
- addServiceSubscription(sb);
- addEndOfXML(sb);
- testXML = sb.toString();
- }
-
- private void addNamespace(StringBuilder sb){
- sb.append("<xml-bindings xmlns=\"http://www.eclipse.org/eclipselink/xsds/persistence/oxm\" package-name=\"inventory.aai.onap.org.v11\" xml-mapping-metadata-complete=\"true\">\n");
- sb.append("<xml-schema element-form-default=\"QUALIFIED\">\n");
- sb.append("<xml-ns namespace-uri=\"http://org.onap.aai.inventory/v11\" />\n");
- sb.append("</xml-schema>\n");
- sb.append("<java-types>\n");
- sb.append("<java-type name=\"Inventory\">\n");
- sb.append("<xml-root-element name=\"inventory\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"business\" name=\"business\" type=\"inventory.aai.onap.org.v11.Business\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
-
- private void addRelationshipList(StringBuilder sb ) {
- sb.append("<java-type name=\"RelationshipList\">\n");
- sb.append("<xml-root-element name=\"relationship-list\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relationship\" name=\"relationship\" type=\"inventory.aai.onap.org.v11.Relationship\" />/n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
-
- private void addRelationship(StringBuilder sb ) {
- sb.append("<java-type name=\"Relationship\">\n");
- sb.append("<xml-root-element name=\"relationship\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"relatedTo\" name=\"related-to\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"A keyword provided by A&amp;AI to indicate type of node.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"relatedLink\" name=\"related-link\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"URL to the object in A&amp;AI.\" />");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relationshipData\" name=\"relationship-data\" type=\"inventory.aai.onap.org.v11.RelationshipData\" />\n");
- sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relatedToProperty\" name=\"related-to-property\" type=\"inventory.aai.onap.org.v11.RelatedToProperty\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
-
- private void addRelatedToProperty(StringBuilder sb) {
- sb.append("<java-type name=\"RelatedToProperty\">\n");
- sb.append("<xml-root-element name=\"related-to-property\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"propertyKey\" name=\"property-key\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Key part of a key/value pair\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"propertyValue\" name=\"property-value\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Value part of a key/value pair\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
+ XSDElementTest x = new XSDElementTest();
+ x.setUp();
+ testXML = x.getTestXML();
}
- private void addRelationshipData(StringBuilder sb){
- sb.append("<java-type name=\"RelationshipData\">\n");
- sb.append("<xml-root-element name=\"relationship-data\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"relationshipKey\" name=\"relationship-key\" required=\"true\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"A keyword provided by A&amp;AI to indicate an attribute.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"relationshipValue\" name=\"relationship-value\" required=\"true\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Value of the attribute.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
-
- private void addBusiness(StringBuilder sb){
- sb.append("<java-type name=\"Business\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Namespace for business related constructs\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("<xml-root-element name=\"business\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"customers\" name=\"customers\" type=\"inventory.aai.onap.org.v11.Customers\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
-
- private void addCustomers(StringBuilder sb){
- sb.append("<java-type name=\"Customers\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Collection of customer identifiers to provide linkage back to BSS information.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("<xml-root-element name=\"customers\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"customer\" name=\"customer\" type=\"inventory.aai.onap.org.v11.Customer\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"maximumDepth\" value=\"0\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</java-type>\n");
- }
-
- private void addCustomer(StringBuilder sb){
- sb.append("<java-type name=\"Customer\">\n");
- sb.append("<xml-root-element name=\"customer\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"globalCustomerId\" name=\"global-customer-id\" required=\"true\" type=\"java.lang.String\" xml-key=\"true\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Global customer id used across ECOMP to uniquely identify customer.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"subscriberName\" name=\"subscriber-name\" required=\"true\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Subscriber name, an alternate way to retrieve a customer.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"subscriberType\" name=\"subscriber-type\" required=\"true\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Subscriber type, a way to provide VID with only the INFRA customers.\" />\n");
- sb.append("<xml-property name=\"defaultValue\" value=\"CUST\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"resourceVersion\" name=\"resource-version\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"serviceSubscriptions\" name=\"service-subscriptions\" type=\"inventory.aai.onap.org.v11.ServiceSubscriptions\" />\n");
- sb.append("<xml-element java-attribute=\"relationshipList\" name=\"relationship-list\" type=\"inventory.aai.onap.org.v11.RelationshipList\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"customer identifiers to provide linkage back to BSS information.\" />\n");
- sb.append("<xml-property name=\"nameProps\" value=\"subscriber-name\" />\n");
- sb.append("<xml-property name=\"indexedProps\" value=\"subscriber-name,global-customer-id,subscriber-type\" />\n");
- sb.append("<xml-property name=\"searchable\" value=\"global-customer-id,subscriber-name\" />\n");
- sb.append("<xml-property name=\"uniqueProps\" value=\"global-customer-id\" />\n");
- sb.append("<xml-property name=\"container\" value=\"customers\" />\n");
- sb.append("<xml-property name=\"namespace\" value=\"business\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</java-type>\n");
- }
-
- private void addServiceSubscriptions(StringBuilder sb){
- sb.append("<java-type name=\"ServiceSubscriptions\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Collection of objects that group service instances.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("<xml-root-element name=\"service-subscriptions\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"serviceSubscription\" name=\"service-subscription\" type=\"inventory.aai.onap.org.v11.ServiceSubscription\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("</java-type>\n");
- }
- private void addServiceSubscription(StringBuilder sb){
- sb.append("<java-type name=\"ServiceSubscription\">\n");
- sb.append("<xml-root-element name=\"service-subscription\" />\n");
- sb.append("<java-attributes>\n");
- sb.append("<xml-element java-attribute=\"serviceType\" name=\"service-type\" required=\"true\" type=\"java.lang.String\" xml-key=\"true\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Value defined by orchestration to identify this service across ECOMP.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"tempUbSubAccountId\" name=\"temp-ub-sub-account-id\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"This property will be deleted from A&amp;AI in the near future. Only stop gap solution.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"resourceVersion\" name=\"resource-version\" type=\"java.lang.String\">\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</xml-element>\n");
- sb.append("<xml-element java-attribute=\"relationshipList\" name=\"relationship-list\" type=\"inventory.aai.onap.org.v11.RelationshipList\" />\n");
- sb.append("</java-attributes>\n");
- sb.append("<xml-properties>\n");
- sb.append("<xml-property name=\"description\" value=\"Object that group service instances.\" />\n");
- sb.append("<xml-property name=\"indexedProps\" value=\"service-type\" />\n");
- sb.append("<xml-property name=\"dependentOn\" value=\"customer\" />\n");
- sb.append("<xml-property name=\"container\" value=\"service-subscriptions\" />\n");
- sb.append("<xml-property name=\"crossEntityReference\" value=\"service-instance,service-type\" />\n");
- sb.append("</xml-properties>\n");
- sb.append("</java-type>\n");
- }
-
- private void addEndOfXML(StringBuilder sb){
- sb.append("</java-types>\n");
- sb.append("</xml-bindings>\n");
- }
-
-
@Test
- public void test_processOxmFile() {
+ public void test_generateSwaggerFromOxmFile( ) {
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String fileContent = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ fileContent = swagger.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug(fileContent);
+ assertThat(fileContent, is(new YAMLfromOXMTest().YAMLresult()));
+ }
-
- GenerateXsd generateXsd = new GenerateXsd();
-
- //GenerateXsd generateXsdSpy = PowerMockito.spy(generateXsd);
-
- //generateXsdSpy.processOxmFile(null, Version.getLatest(), testXML);
-
- String xsdResult = generateXsd.processOxmFile(null, Version.getLatest(), testXML);
+ @Test
+ public void test_generateXSDFromOxmFile( ) {
- String relationshipListExpected = " <xs:element name=\"relationship-list\">\n <xs:complexType>\n <xs:sequence>\n <xs:element ref=\"tns:relationship\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>";
- String relatedToPropertyExpected = " <xs:element name=\"related-to-property\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"property-key\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Key part of a key/value pair\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n </xs:element>\n"
- + " <xs:element name=\"property-value\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Value part of a key/value pair\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>";
- assertNotNull(xsdResult);
+ Version v = Version.v11;
+ String fileContent = null;
+ try {
+ HTMLfromOXM xsd = new HTMLfromOXM(testXML, v);
+ fileContent = xsd.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug(fileContent);
+ assertThat(fileContent, is(new HTMLfromOXMTest().HTMLresult()));
}
+
@Test
- public void test_generateSwaggerFromOxmFile( ) {
-
+ public void testGetAPIVersion() {
+ GenerateXsd.apiVersion=Version.v11.name();
+ assertThat(GenerateXsd.getAPIVersion(),is("v11"));
+ }
- GenerateXsd generateXsd = new GenerateXsd();
+ @Test
+ public void testGetYamlDir() {
+ assertThat(GenerateXsd.getYamlDir(),is("../aai-schema/src/main/resources/aai_swagger_yaml"));
+ }
- String customerOperation = " /business/customers/customer/{global-customer-id}:\n get:\n tags:\n - Business\n summary: returns customer";
- String relationshipListDefinition = " relationship-list:\n properties:\n relationship:\n type: array\n items: \n $ref: \"#/definitions/relationship\"";
- String swaggerResult = generateXsd.generateSwaggerFromOxmFile(null, testXML);
- assertNotNull(swaggerResult);
+ @Test
+ public void testGetResponsesUrl() {
+ assertNull(GenerateXsd.getResponsesUrl());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
new file mode 100644
index 00000000..d9fd1d6b
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
@@ -0,0 +1,71 @@
+/**
+ * ============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.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.junit.Test;
+import org.onap.aai.restcore.JettyObfuscationConversionCommandLineUtil;
+
+public class JettyObfuscationConversionCommandLineUtilTest {
+
+ private final ByteArrayOutputStream testOut = new ByteArrayOutputStream();
+
+ /**
+ * Test.
+ */
+ @Test
+ public void test() {
+ //setup, this will catch main's print statements for evaluation
+ System.setOut(new PrintStream(testOut));
+
+ /* ------ TEST OBFUSCATION ----*/
+ JettyObfuscationConversionCommandLineUtil.main(new String[]{"-e", "hello world"});
+ /*
+ * testOut was also catching any logging statements which interfered with result checking.
+ * This regex business was the workaround - it tries to find the expected value in
+ * the results and asserts against that.
+ */
+ String obfResult = testOut.toString();
+ String obfExpected = "OBF:1thf1ugo1x151wfw1ylz11tr1ymf1wg21x1h1uh21th7";
+ Pattern obfExpectPat = Pattern.compile(obfExpected);
+ Matcher obfMatch = obfExpectPat.matcher(obfResult);
+ assertTrue(obfMatch.find());
+
+ testOut.reset(); //clear out previous result
+
+ /* ------ TEST DEOBFUSCATION ----- */
+ JettyObfuscationConversionCommandLineUtil.main(new String[]{"-d", obfExpected});
+ String deobfResult = testOut.toString();
+ String deobfExpected = "hello world";
+ Pattern deobfExpectPat = Pattern.compile(deobfExpected);
+ Matcher deobfMatch = deobfExpectPat.matcher(deobfResult);
+ assertTrue(deobfMatch.find());
+
+ //clean up, resets to stdout
+ System.setOut(null);
+ }
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
index 5bd7984a..d3725f48 100644
--- a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
@@ -112,7 +112,7 @@ public class StoreNotificationEventTest extends AAISetup {
eh.setSourceName("source");
eh.setSequenceNumber("23");
eh.setSeverity("ALERT");
- eh.setVersion("v11");
+ eh.setVersion("v12");
String res = sne.storeEvent(eh, object);
@@ -126,7 +126,7 @@ public class StoreNotificationEventTest extends AAISetup {
assertTrue(res.contains("\"sequence-number\" : \"23\""));
assertTrue(res.contains("\"severity\" : \"ALERT\""));
assertTrue(res.contains("\"event-type\" : \"surprise\""));
- assertTrue(res.contains("\"version\" : \"v11\""));
+ assertTrue(res.contains("\"version\" : \"v12\""));
assertTrue(res.contains("\"action\" : \"action!\""));
assertTrue(res.contains("\"entity-link\" : \"entity-link\""));
assertTrue(res.contains("\"entity\""));
@@ -140,20 +140,20 @@ public class StoreNotificationEventTest extends AAISetup {
public void testStoreDynamicEventNullObj() throws AAIException {
DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
DynamicJAXBContext notificationJaxbContext = Mockito.mock(DynamicJAXBContext.class);
- sne.storeDynamicEvent(notificationJaxbContext, "v11", eventHeader, null);
+ sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, null);
}
- @Test(expected = AAIException.class)
+ @Test(expected = Exception.class)
public void testStoreDynamicEventAAIException() throws Exception {
DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
DynamicEntity obj = Mockito.mock(DynamicEntity.class);
DynamicJAXBContext notificationJaxbContext = Mockito.mock(DynamicJAXBContext.class);
ClassLoader cl = getClass().getClassLoader();
- InputStream is = cl.getResourceAsStream("oxm/aai_oxm_v11.xml");
+ InputStream is = cl.getResourceAsStream("oxm/aai_oxm_v12.xml");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, is);
DynamicJAXBContext notificationJaxbContextReal = DynamicJAXBContextFactory.createContextFromOXM(cl, properties);
- DynamicType dtReal = notificationJaxbContextReal.getDynamicType("inventory.aai.onap.org.v11.NotificationEvent");
+ DynamicType dtReal = notificationJaxbContextReal.getDynamicType("inventory.aai.onap.org.v12.NotificationEvent");
DynamicType dt = Mockito.mock(DynamicType.class);
DynamicEntity notificationEventReal = dtReal.newDynamicEntity();
JAXBMarshaller marshaller = Mockito.mock(JAXBMarshaller.class);
@@ -163,7 +163,7 @@ public class StoreNotificationEventTest extends AAISetup {
Mockito.when(notificationJaxbContext.createMarshaller()).thenReturn(marshaller);
Mockito.doNothing().when(marshaller).marshal(Mockito.any(DynamicJAXBContext.class), Mockito.any(StringWriter.class));
- sne.storeDynamicEvent(notificationJaxbContext, "v11", eventHeader, obj);
+ sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, obj);
}
@Test(expected = AAIException.class)
@@ -174,7 +174,7 @@ public class StoreNotificationEventTest extends AAISetup {
@Test
public void testStoreEventIntrospector() throws Exception {
- Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v11);
+ Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v12);
Introspector eventHeader = loader.introspectorFromName("notification-event-header");
eventHeader.setValue("id", "123");
eventHeader.setValue("timestamp", "current-time");
@@ -185,7 +185,7 @@ public class StoreNotificationEventTest extends AAISetup {
eventHeader.setValue("source-name", "source");
eventHeader.setValue("sequence-number", "23");
eventHeader.setValue("severity", "ALERT");
- eventHeader.setValue("version", "v11");
+ eventHeader.setValue("version", "v12");
Introspector obj = loader.introspectorFromName("notification-event");
@@ -201,7 +201,7 @@ public class StoreNotificationEventTest extends AAISetup {
assertTrue(res.contains("\"sequence-number\":\"23\""));
assertTrue(res.contains("\"severity\":\"ALERT\""));
assertTrue(res.contains("\"event-type\":\"surprise\""));
- assertTrue(res.contains("\"version\":\"v11\""));
+ assertTrue(res.contains("\"version\":\"v12\""));
assertTrue(res.contains("\"action\":\"action!\""));
assertTrue(res.contains("\"entity-link\":\"entity-link\""));
assertTrue(res.contains("\"notification-event\""));
@@ -209,7 +209,7 @@ public class StoreNotificationEventTest extends AAISetup {
@Test
public void testStoreEventIntrospectorEmptyEventHeader() throws Exception {
- Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v11);
+ Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v12);
Introspector eventHeader = loader.introspectorFromName("notification-event-header");
Introspector obj = loader.introspectorFromName("notification-event");
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
new file mode 100644
index 00000000..3c1e825d
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteFootnoteSetTest.java
@@ -0,0 +1,83 @@
+/**
+ * ============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.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+@RunWith(Parameterized.class)
+public class DeleteFootnoteSetTest {
+ String targetNode;
+ String flavor;
+ String result;
+ DeleteFootnoteSet footnotes = null;
+
+ @Parameters
+ public static Collection<String[]> 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
new file mode 100644
index 00000000..501babe3
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/DeleteOperationTest.java
@@ -0,0 +1,82 @@
+/**
+ * ============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.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@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<String []> 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"},
+ {"CloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver","vserver","CloudInfrastructure","/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}"," - name: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__\n"," delete:\n tags:\n - CloudInfrastructure\n summary: delete an existing vserver\n description: delete an existing vserver\n operationId: deleteCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver\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: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-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
new file mode 100644
index 00000000..d57dc4aa
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeDescriptionTest.java
@@ -0,0 +1,392 @@
+/**
+ * ============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 com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.assertThat;
+
+public class EdgeDescriptionTest {
+ private DocumentContext jsonContext;
+ private EdgeRuleSet edgeSet;
+ private Collection<EdgeDescription>edges;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+
+ }
+
+ @Before
+ public void setUp() 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\": \"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\": \"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\":\"\""
+ + " },"
+*/
+ + " ]}";
+ jsonContext = JsonPath.parse(json);
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ String nodeName = "availability-zone";
+ edges = edgeSet.getEdgeRules(nodeName);
+ }
+
+ @Test
+ public void testGetDeleteOtherV() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"NONE";
+ for (EdgeDescription ed : edges) {
+ String modResult = ed.getRuleKey() + "-" + ed.getDeleteOtherV();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetDeleteOtherV() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"IN";
+ for (EdgeDescription ed : edges) {
+ ed.setDeleteOtherV("IN");
+ String modResult = ed.getRuleKey() + "-" + ed.getDeleteOtherV();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetPreventDelete() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"IN";
+ for (EdgeDescription ed : edges) {
+ String modResult = ed.getRuleKey() + "-" + ed.getPreventDelete();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetPreventDelete() {
+ for (EdgeDescription ed : edges) {
+ String target = "availability-zone"+"|"+"complex"+"-"+"OUT";
+ ed.setPreventDelete("OUT");
+ String modResult = ed.getRuleKey() + "-" + ed.getPreventDelete();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetAlsoDeleteFootnote() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"";
+ 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() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"complex";
+ for (EdgeDescription ed : edges) {
+ String modResult = ed.getRuleKey() + "-" + ed.getTo();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetTo() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"jazz";
+ for (EdgeDescription ed : edges) {
+ ed.setTo("jazz");
+ String modResult = ed.getRuleKey() + "-" + ed.getTo();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetFrom() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"availability-zone";
+ for (EdgeDescription ed : edges) {
+ String modResult = ed.getRuleKey() + "-" + ed.getFrom();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetFrom() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"jazz";
+ for (EdgeDescription ed : edges) {
+ ed.setFrom("jazz");
+ String modResult = ed.getRuleKey() + "-" + ed.getFrom();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetRuleKey() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo();
+ String modResult = ed.getRuleKey();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetMultiplicity() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"MANY2ONE";
+ for (EdgeDescription ed : edges) {
+ String modResult = ed.getRuleKey() + "-" + ed.getMultiplicity();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetDirection() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"OUT";
+ String modResult = ed.getRuleKey() + "-" + ed.getDirection();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetDescription() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"this description";
+ String modResult = ed.getRuleKey() + "-" + ed.getDescription();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetRuleKey() {
+ for (EdgeDescription ed : edges) {
+ ed.setRuleKey("A|B");
+ String target = "A|B";
+ String modResult = ed.getRuleKey();
+ assertThat(modResult, is(target));
+ } }
+
+ @Test
+ public void testSetType() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"CHILD";
+ for (EdgeDescription ed : edges) {
+ ed.setType(EdgeDescription.LineageType.CHILD);
+ String modResult = ed.getRuleKey() + "-" + ed.getType();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetDirection() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"IN";
+ for (EdgeDescription ed : edges) {
+ ed.setDirection("IN");
+ String modResult = ed.getRuleKey() + "-" + ed.getDirection();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetMultiplicity() {
+ String target = "availability-zone"+"|"+"complex"+"-"+"ONE2MANY";
+ for (EdgeDescription ed : edges) {
+ ed.setTo("ONE2MANY");
+ String modResult = ed.getRuleKey() + "-" + ed.getTo();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetDescription() {
+ for (EdgeDescription ed : edges) {
+ ed.setDescription("a new description");
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"a new description";
+ String modResult = ed.getRuleKey() + "-" + ed.getDescription();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetRelationshipDescription() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"( availability-zone LocatedIn complex, MANY2ONE)\n this description";
+ String modResult = ed.getRuleKey() + "-" + ed.getRelationshipDescription("FROM",ed.getTo());
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetType() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"UNRELATED";
+ String modResult = ed.getRuleKey() + "-" + ed.getType();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetLabel() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"org.onap.relationships.inventory.LocatedIn";
+ String modResult = ed.getRuleKey() + "-" + ed.getLabel();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testGetShortLabel() {
+ for (EdgeDescription ed : edges) {
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+"LocatedIn";
+ String modResult = ed.getRuleKey() + "-" + ed.getShortLabel();
+ assertThat(modResult, is(target));
+ }
+ }
+
+ @Test
+ public void testSetLabel() {
+ String newLabel = "New label";
+ for (EdgeDescription ed : edges) {
+ ed.setLabel(newLabel);
+ String target = ed.getFrom()+"|"+ed.getTo()+"-"+newLabel;
+ String modResult = ed.getRuleKey() + "-" + ed.getLabel();
+ assertThat(modResult, not(equalTo("org.onap.relationships.inventory.LocatedIn")));
+ assertThat(modResult, is(target));
+ }
+ }
+
+}
diff --git a/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeRuleSetTest.java b/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeRuleSetTest.java
new file mode 100644
index 00000000..3668cf36
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/EdgeRuleSetTest.java
@@ -0,0 +1,243 @@
+/**
+ * ============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 com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class EdgeRuleSetTest {
+ private static File edgesFile = new File("edges.json");
+ private static String nodeName = "availability-zone";
+ private DocumentContext jsonContext;
+ private String json;
+ private EdgeRuleSet edgeSet;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ 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\":\"\""
+ + " },"
+ + " ]}";
+ FileWriter file = new FileWriter(edgesFile);
+ file.write(json);
+ file.flush();
+ file.close();
+ jsonContext = JsonPath.parse(json);
+
+ }
+
+ @Test
+ public void testEdgeRuleSetFile() throws FileNotFoundException, IOException {
+ this.edgeSet = new EdgeRuleSet(edgesFile);
+ Collection<EdgeDescription>edges = edgeSet.getEdgeRules(nodeName);
+ assertThat(edges.size(), is(8));
+ }
+
+ @Test
+ public void testEdgeRuleSetDocumentContext() {
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ Collection<EdgeDescription>edges = edgeSet.getEdgeRules(nodeName);
+ assertThat(edges.size(), is(8));
+ }
+
+ @Test
+ public void testGetEdgeRules() {
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ Collection<EdgeDescription>edges = edgeSet.getEdgeRules(nodeName);
+ assertThat(edges.size(), is(8));
+ }
+
+ @Test
+ public void testGetEdgeRulesTO() {
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ Collection<EdgeDescription>edges = edgeSet.getEdgeRulesTO(nodeName);
+ assertThat(edges.size(), is(5));
+ }
+
+ @Test
+ public void testGetEdgeRulesFROM() {
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ Collection<EdgeDescription>edges = edgeSet.getEdgeRulesFROM(nodeName);
+ assertThat(edges.size(), is(3));
+ }
+
+ @Test
+ public void testGetEdgeRulesFromJson() {
+ String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]";
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ Collection<EdgeDescription> edges = edgeSet.getEdgeRulesFromJson( fromRulesPath, true );
+ assertThat(edges.size(), is(3));
+ }
+
+ @Test
+ public void testPreventDeleteRules() {
+ String target = "AVAILABILITY-ZONE cannot be deleted if related to CTAG-POOL,DVS-SWITCH,GENERIC-VNF,PSERVER,VCE\n";
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ String fromDeleteRules = edgeSet.preventDeleteRules(nodeName);
+ assertThat(fromDeleteRules, is(target));
+ }
+
+ @Test
+ public void testFromDeleteRules() {
+ String target = "VF-MODULE cannot be deleted if related to VNFC\n";
+ this.edgeSet = new EdgeRuleSet(jsonContext);
+ String fromDeleteRules = edgeSet.fromDeleteRules("vf-module");
+ assertThat(fromDeleteRules, is(target));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ edgesFile.delete();
+ }
+
+}
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
new file mode 100644
index 00000000..79a243d9
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/GetOperationTest.java
@@ -0,0 +1,107 @@
+/**
+ * ============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.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 java.util.Arrays;
+import java.util.Collection;
+import java.util.Vector;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@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<String []> 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__"},
+ {"CloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver","vserver","CloudInfrastructure","/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}"," - name: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__"," /cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}:\n get:\n tags:\n - CloudInfrastructure\n summary: returns vserver\n description: returns vserver\n operationId: getCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/getDefinitions/vserver\"\n \"default\":\n null parameters:\n - name: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-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<String> containerProps = new Vector<String>();
+ 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<String> queryProps = new Vector<String>();
+ 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
new file mode 100644
index 00000000..a3cba5eb
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/HTMLfromOXMTest.java
@@ -0,0 +1,278 @@
+/**
+ * ============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.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.aai.introspection.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+
+import java.io.BufferedWriter;
+import java.io.File;
+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 static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class HTMLfromOXMTest {
+ private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXMTest.class");
+ private String testXML;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ XSDElementTest x = new XSDElementTest();
+ x.setUp();
+ testXML = x.testXML;
+ }
+
+ @Test
+ public void testGetDocumentHeader() {
+ Version v = Version.v11;
+ String header = null;
+ try {
+ HTMLfromOXM swagger = new HTMLfromOXM(testXML, v);
+ header = swagger.getDocumentHeader();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug("Header:");
+ logger.debug(header);
+ assertThat(header, is(HTMLheader()));
+ }
+
+ @Test
+ public void testProcess() {
+ Version v = Version.v11;
+ String fileContent = null;
+ try {
+ HTMLfromOXM xsd = new HTMLfromOXM(testXML, v);
+ fileContent = xsd.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug("FileContent-I:");
+ logger.debug(fileContent);
+ assertThat(fileContent, is(HTMLresult()));
+ }
+
+ @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();
+ Version v = Version.v11;
+ String fileContent = null;
+ try {
+ HTMLfromOXM xsd = new HTMLfromOXM(testXML, v);
+ fileContent = xsd.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ XMLfile.delete();
+ logger.debug("FileContent-I:");
+ logger.debug(fileContent);
+ assertThat(fileContent, is(HTMLresult()));
+ }
+
+ @Test
+ public void testHTMLfromOXMStringVersion() {
+ Version v = Version.v11;
+ String fileContent = null;
+ try {
+ HTMLfromOXM xsd = new HTMLfromOXM(testXML, v);
+ fileContent = xsd.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug("FileContent-II:");
+ logger.debug(fileContent);
+ assertThat(fileContent, is(HTMLresult()));
+ }
+
+ @Test
+ public void testProcessJavaTypeElement() {
+ String target = "Element=java-type/Customer";
+ Version v = Version.v11;
+ Element customer = null;
+ try {
+ HTMLfromOXM xsd = new HTMLfromOXM(testXML, v);
+ xsd.process();
+ customer = xsd.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() {
+ StringBuilder sb = new StringBuilder(32368);
+ sb.append(HTMLheader());
+ sb.append(HTMLdefs());
+ return sb.toString();
+ }
+
+ public String HTMLheader() {
+ StringBuilder sb = new StringBuilder(1500);
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
+ sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://org.openecomp.aai.inventory/v11\" xmlns:tns=\"http://org.openecomp.aai.inventory/v11\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\nxmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\"\r\n");
+ sb.append(" jaxb:version=\"2.1\"\r\n");
+ sb.append(" xmlns:annox=\"http://annox.dev.java.net\"\r\n");
+ sb.append(" jaxb:extensionBindingPrefixes=\"annox\">\n\n");
+ return sb.toString();
+ }
+ public String HTMLdefs() {
+ StringBuilder sb = new StringBuilder(1500);
+ sb.append(" <xs:element name=\"service-subscription\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"class\">@org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element name=\"service-type\" type=\"xs:string\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(isKey=true,description=\"Value defined by orchestration to identify this service across ECOMP.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"temp-ub-sub-account-id\" type=\"xs:string\" minOccurs=\"0\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"This property will be deleted from A&amp;AI in the near future. Only stop gap solution.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"resource-version\" type=\"xs:string\" minOccurs=\"0\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"service-subscriptions\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"class\">@org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element ref=\"tns:service-subscription\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"customer\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"class\">@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\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element name=\"global-customer-id\" type=\"xs:string\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(isKey=true,description=\"Global customer id used across ECOMP to uniquely identify customer.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"subscriber-name\" type=\"xs:string\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Subscriber name, an alternate way to retrieve a customer.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"subscriber-type\" type=\"xs:string\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"resource-version\" type=\"xs:string\" minOccurs=\"0\">\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"field\">@org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element ref=\"tns:service-subscriptions\" minOccurs=\"0\"/>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"customers\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"class\">@org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element ref=\"tns:customer\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"business\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:annotation>\r\n");
+ sb.append(" <xs:appinfo>\r\n");
+ sb.append(" <annox:annotate target=\"class\">@org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")</annox:annotate>\r\n");
+ sb.append(" </xs:appinfo>\r\n");
+ sb.append(" </xs:annotation>\r\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element ref=\"tns:customers\" minOccurs=\"0\"/>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append(" <xs:element name=\"inventory\">\n");
+ sb.append(" <xs:complexType>\n");
+ sb.append(" <xs:sequence>\n");
+ sb.append(" <xs:element ref=\"tns:business\" minOccurs=\"0\"/>\n");
+ sb.append(" </xs:sequence>\n");
+ sb.append(" </xs:complexType>\n");
+ sb.append(" </xs:element>\n");
+ sb.append("</xs:schema>\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
new file mode 100644
index 00000000..7bfaebf5
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/PatchOperationTest.java
@@ -0,0 +1,82 @@
+/**
+ * ============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.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@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<String []> 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 - 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 updated.\n required: true\n schema:\n $ref: \"#/patchDefinitions/generic-vnf\"\n"},
+ {"CloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver","vserver","CloudInfrastructure","/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}"," - name: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__"," patch:\n tags:\n - CloudInfrastructure\n summary: update an existing vserver\n description: |\n Update an existing vserver\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: UpdateCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver\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: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__ - name: body\n in: body\n description: vserver object that needs to be updated.\n required: true\n schema:\n $ref: \"#/patchDefinitions/vserver\"\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
new file mode 100644
index 00000000..b7cced06
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/PutOperationTest.java
@@ -0,0 +1,84 @@
+/**
+ * ============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.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.introspection.Version;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@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 Version v = Version.getLatest();
+
+ @Parameters
+ public static Collection<String []> 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.name()+"/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"},
+ {"CloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver","vserver","CloudInfrastructure","/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}"," - name: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__"," put:\n tags:\n - CloudInfrastructure\n summary: create or update an existing vserver\n description: |\n Create or update an existing vserver.\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: createOrUpdateCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver\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: cloud-owner\n in: path\n description: Identifies the vendor and cloud name, e.g., att-aic. First part of composite key should be formatted as vendor-cloudname\n required: true\n type: string\n example: __CLOUD-OWNER__\n - name: cloud-region-id\n in: path\n description: Identifier used by the vendor for the region. Second part of composite key\n required: true\n type: string\n example: __CLOUD-REGION-ID__\n - name: tenant-id\n in: path\n description: Unique id relative to the cloud-region.\n required: true\n type: string\n example: __TENANT-ID__\n - name: vserver-id\n in: path\n description: Unique identifier for this vserver relative to its tenant\n required: true\n type: string\n example: __VSERVER-ID__ - name: body\n in: body\n description: vserver object that needs to be created or updated. [Valid relationship examples shown here](apidocs/relations/"+v.name()+"/CloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserver.json)\n required: true\n schema:\n $ref: \"#/definitions/vserver\"\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, Version.getLatest());
+ 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
new file mode 100644
index 00000000..6b8750fb
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/PutRelationPathSetTest.java
@@ -0,0 +1,223 @@
+/**
+ * ============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 com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.aai.introspection.Version;
+import org.onap.aai.util.GenerateXsd;
+
+import java.io.File;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+public class PutRelationPathSetTest {
+ private DocumentContext jsonContext;
+ private String json;
+ private EdgeRuleSet edgeRuleSet;
+ private Version v = Version.getLatest();
+ private File relationsFile = new File(GenerateXsd.getYamlDir() + "/relations/" + v.name()+"/createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZone.json");
+ 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;
+
+
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ 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\":\"\""
+ + " },"
+ + " ]}";
+ jsonContext = JsonPath.parse(json);
+ this.edgeRuleSet = new EdgeRuleSet(jsonContext);
+ 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);
+ }
+
+ @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(edgeRuleSet);
+ 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(edgeRuleSet);
+ 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
new file mode 100644
index 00000000..ccae8578
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDElementTest.java
@@ -0,0 +1,564 @@
+/**
+ * ============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.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;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.*;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.collection.IsIn.in;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.hamcrest.core.Every.everyItem;
+import static org.junit.Assert.assertThat;
+
+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 {
+ StringBuilder sb = new StringBuilder(maxSizeForXml);
+ addNamespace(sb);
+ addBusiness(sb);
+ addCustomers(sb);
+ addCustomer(sb);
+ addServiceSubscriptions(sb);
+ addServiceSubscription(sb);
+ addEndOfXML(sb);
+ testXML = sb.toString();
+ init();
+ }
+
+ private void addNamespace(StringBuilder sb){
+ sb.append("<xml-bindings xmlns=\"http://www.eclipse.org/eclipselink/xsds/persistence/oxm\" package-name=\"inventory.aai.onap.org.v11\" xml-mapping-metadata-complete=\"true\">\n");
+ sb.append("<xml-schema element-form-default=\"QUALIFIED\">\n");
+ sb.append("<xml-ns namespace-uri=\"http://org.onap.aai.inventory/v11\" />\n");
+ sb.append("</xml-schema>\n");
+ sb.append("<java-types>\n");
+ sb.append("<java-type name=\"Inventory\">\n");
+ sb.append("<xml-root-element name=\"inventory\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"business\" name=\"business\" type=\"inventory.aai.onap.org.v11.Business\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addBusiness(StringBuilder sb){
+ sb.append("<java-type name=\"Business\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Namespace for business related constructs\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("<xml-root-element name=\"business\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"customers\" name=\"customers\" type=\"inventory.aai.onap.org.v11.Customers\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addCustomers(StringBuilder sb){
+ sb.append("<java-type name=\"Customers\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Collection of customer identifiers to provide linkage back to BSS information.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("<xml-root-element name=\"customers\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"customer\" name=\"customer\" type=\"inventory.aai.onap.org.v11.Customer\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"maximumDepth\" value=\"0\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addCustomer(StringBuilder sb){
+ sb.append("<java-type name=\"Customer\">\n");
+ sb.append("<xml-root-element name=\"customer\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"globalCustomerId\" name=\"global-customer-id\" required=\"true\" type=\"java.lang.String\" xml-key=\"true\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Global customer id used across ECOMP to uniquely identify customer.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"subscriberName\" name=\"subscriber-name\" required=\"true\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Subscriber name, an alternate way to retrieve a customer.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"subscriberType\" name=\"subscriber-type\" required=\"true\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Subscriber type, a way to provide VID with only the INFRA customers.\" />\n");
+ sb.append("<xml-property name=\"defaultValue\" value=\"CUST\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"resourceVersion\" name=\"resource-version\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"serviceSubscriptions\" name=\"service-subscriptions\" type=\"inventory.aai.onap.org.v11.ServiceSubscriptions\" />\n");
+// sb.append("<xml-element java-attribute=\"relationshipList\" name=\"relationship-list\" type=\"inventory.aai.onap.org.v11.RelationshipList\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"customer identifiers to provide linkage back to BSS information.\" />\n");
+ sb.append("<xml-property name=\"nameProps\" value=\"subscriber-name\" />\n");
+ sb.append("<xml-property name=\"indexedProps\" value=\"subscriber-name,global-customer-id,subscriber-type\" />\n");
+ sb.append("<xml-property name=\"searchable\" value=\"global-customer-id,subscriber-name\" />\n");
+ sb.append("<xml-property name=\"uniqueProps\" value=\"global-customer-id\" />\n");
+ sb.append("<xml-property name=\"container\" value=\"customers\" />\n");
+ sb.append("<xml-property name=\"namespace\" value=\"business\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addServiceSubscriptions(StringBuilder sb){
+ sb.append("<java-type name=\"ServiceSubscriptions\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Collection of objects that group service instances.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("<xml-root-element name=\"service-subscriptions\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"serviceSubscription\" name=\"service-subscription\" type=\"inventory.aai.onap.org.v11.ServiceSubscription\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+ private void addServiceSubscription(StringBuilder sb){
+ sb.append("<java-type name=\"ServiceSubscription\">\n");
+ sb.append("<xml-root-element name=\"service-subscription\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"serviceType\" name=\"service-type\" required=\"true\" type=\"java.lang.String\" xml-key=\"true\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Value defined by orchestration to identify this service across ECOMP.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"tempUbSubAccountId\" name=\"temp-ub-sub-account-id\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"This property will be deleted from A&amp;AI in the near future. Only stop gap solution.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"resourceVersion\" name=\"resource-version\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+// sb.append("<xml-element java-attribute=\"relationshipList\" name=\"relationship-list\" type=\"inventory.aai.onap.org.v11.RelationshipList\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Object that group service instances.\" />\n");
+ sb.append("<xml-property name=\"indexedProps\" value=\"service-type\" />\n");
+ sb.append("<xml-property name=\"dependentOn\" value=\"customer\" />\n");
+ sb.append("<xml-property name=\"container\" value=\"service-subscriptions\" />\n");
+ sb.append("<xml-property name=\"crossEntityReference\" value=\"service-instance,service-type\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addRelationshipList(StringBuilder sb ) {
+ sb.append("<java-type name=\"RelationshipList\">\n");
+ sb.append("<xml-root-element name=\"relationship-list\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relationship\" name=\"relationship\" type=\"inventory.aai.onap.org.v11.Relationship\" />/n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addRelationship(StringBuilder sb ) {
+ sb.append("<java-type name=\"Relationship\">\n");
+ sb.append("<xml-root-element name=\"relationship\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"relatedTo\" name=\"related-to\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"A keyword provided by A&amp;AI to indicate type of node.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"relatedLink\" name=\"related-link\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"URL to the object in A&amp;AI.\" />");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relationshipData\" name=\"relationship-data\" type=\"inventory.aai.onap.org.v11.RelationshipData\" />\n");
+ sb.append("<xml-element container-type=\"java.util.ArrayList\" java-attribute=\"relatedToProperty\" name=\"related-to-property\" type=\"inventory.aai.onap.org.v11.RelatedToProperty\" />\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addRelatedToProperty(StringBuilder sb) {
+ sb.append("<java-type name=\"RelatedToProperty\">\n");
+ sb.append("<xml-root-element name=\"related-to-property\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"propertyKey\" name=\"property-key\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Key part of a key/value pair\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"propertyValue\" name=\"property-value\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Value part of a key/value pair\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+ private void addRelationshipData(StringBuilder sb){
+ sb.append("<java-type name=\"RelationshipData\">\n");
+ sb.append("<xml-root-element name=\"relationship-data\" />\n");
+ sb.append("<java-attributes>\n");
+ sb.append("<xml-element java-attribute=\"relationshipKey\" name=\"relationship-key\" required=\"true\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"A keyword provided by A&amp;AI to indicate an attribute.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("<xml-element java-attribute=\"relationshipValue\" name=\"relationship-value\" required=\"true\" type=\"java.lang.String\">\n");
+ sb.append("<xml-properties>\n");
+ sb.append("<xml-property name=\"description\" value=\"Value of the attribute.\" />\n");
+ sb.append("</xml-properties>\n");
+ sb.append("</xml-element>\n");
+ sb.append("</java-attributes>\n");
+ sb.append("</java-type>\n");
+ }
+
+
+ private void addEndOfXML(StringBuilder sb){
+ sb.append("</java-types>\n");
+ sb.append("</xml-bindings>\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 <binding-nodes> in XML");
+ }
+
+ bindingElement = (Element) bindingsNodes.item(0);
+ javaTypesNodes = bindingElement.getElementsByTagName("java-types");
+ if ( javaTypesNodes.getLength() < 1 ) {
+ throw new AAIException("OXM file error: missing <binding-nodes><java-types> in XML");
+ }
+ javaTypesElement = (Element) javaTypesNodes.item(0);
+
+ javaTypeNodes = javaTypesElement.getElementsByTagName("java-type");
+ if ( javaTypeNodes.getLength() < 1 ) {
+ throw new AAIException("OXM file error: missing <binding-nodes><java-types><java-type> in XML");
+ }
+ logger.debug(testXML);
+ }
+ @Test
+ public void testXSDElement() {
+ // repeat of testGetIndexedProps() which uses the constructor
+ ArrayList<String> target = new ArrayList<String>();
+ target.add("subscriber-name");
+ target.add("global-customer-id");
+ target.add("subscriber-type");
+ target.add("service-type");
+
+ Vector<String> indexedProps = new Vector<String>();
+ 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<String> target = new ArrayList<String>();
+ target.add("ServiceSubscriptions");
+ target.add("ServiceSubscription");
+ target.add("Inventory");
+ target.add("Business");
+ target.add("Customers");
+ target.add("Customer");
+ ArrayList<String> names = new ArrayList<String>();
+ 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<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
+ HashMap<String,ArrayList<String>> target = new HashMap<String,ArrayList<String>>();
+ 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<String> addTypes = new ArrayList<String>();
+ 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<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
+ ArrayList<String> target = new ArrayList<String>();
+ 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<String> requiredItems = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ 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<String> descs = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ target.add("subscriber-name");
+ target.add("global-customer-id");
+ target.add("subscriber-type");
+ target.add("service-type");
+
+ Vector<String> indexedProps = new Vector<String>();
+ 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<String> target = new ArrayList<String>();
+ target.add("service-subscriptions");
+ target.add("customers");
+ List<String> containers = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ 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<String> indexedProps = new Vector<String>();
+ 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<String> containerProps = new Vector<String>();
+ 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<String> queryParams = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ 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<String> pathParams = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ target.add(" <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"Business\">@org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n");
+ target.add(" <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"Customers\">@org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n");
+ target.add(" <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"Customer\">@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\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n");
+ target.add(" <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"ServiceSubscriptions\">@org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n");
+ target.add(" <xs:annotation>\r\n <xs:appinfo>\r\n <annox:annotate target=\"ServiceSubscription\">@org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")</annox:annotate>\r\n </xs:appinfo>\r\n </xs:annotation>\r\n");
+ List<String> annotes = new ArrayList<String>();
+ 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<String> target = new ArrayList<String>();
+ 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<String> types = new ArrayList<String>();
+ 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<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
+ HashMap<String,ArrayList<String>> target = new HashMap<String,ArrayList<String>>();
+ 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<String> addTypes = new ArrayList<String>();
+ 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
new file mode 100644
index 00000000..7a2f9be9
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/XSDJavaTypeTest.java
@@ -0,0 +1,101 @@
+/**
+ * ============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.Before;
+import org.junit.Test;
+import org.w3c.dom.Element;
+
+import java.util.HashMap;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+public class XSDJavaTypeTest extends XSDElementTest {
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ }
+
+ @Test
+ public void testXSDJavaTypeElement() {
+ HashMap<String,String> map = new HashMap<String,String>();
+ HashMap<String,String> target = new HashMap<String,String>();
+ 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<String,String> map = new HashMap<String,String>();
+ HashMap<String,String> target = new HashMap<String,String>();
+ 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<String,String> map = new HashMap<String,String>();
+ HashMap<String,String> target = new HashMap<String,String>();
+ 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
new file mode 100644
index 00000000..665c770b
--- /dev/null
+++ b/aai-core/src/test/java/org/onap/aai/util/genxsd/YAMLfromOXMTest.java
@@ -0,0 +1,826 @@
+/**
+ * ============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.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.aai.introspection.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+
+import java.io.BufferedWriter;
+import java.io.File;
+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 static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class YAMLfromOXMTest {
+ private static final Logger logger = LoggerFactory.getLogger("YAMLfromOXMTest.class");
+ private String testXML;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ XSDElementTest x = new XSDElementTest();
+ x.setUp();
+ testXML = x.testXML;
+ logger.debug(testXML);
+ }
+
+ @Test
+ public void testGetDocumentHeader() {
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String header = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ swagger.process();
+ header = swagger.getDocumentHeader();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ assertThat("Header:\n"+header,header, is(YAMLheader()));
+ }
+
+ @Test
+ public void testProcess() {
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String fileContent = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ fileContent = swagger.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();
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String fileContent = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(XMLfile, v, edgeRuleFile);
+ fileContent = swagger.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ XMLfile.delete();
+ assertThat("FileContent-OXMFileVersionFile:\n"+fileContent,fileContent, is(YAMLresult()));
+ }
+
+ @Test
+ public void testYAMLfromOXMStringVersionFile() {
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String fileContent = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ fileContent = swagger.process();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ assertThat("FileContent-OXMStringVersionFile:\n"+fileContent,fileContent, is(YAMLresult()));
+ }
+
+ @Test
+ public void testAppendDefinitions() {
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String definitions = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ swagger.process();
+ definitions = swagger.appendDefinitions();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ assertThat("Definitions:\n"+definitions,definitions, is(YAMLdefs()+YAMLpatchDefs()+YAMLgetDefs()));
+ }
+
+ @Test
+ public void testGetXMLRootElementName() {
+ String target = "RootElement=customer";
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ Element customer = null;
+ String root = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ swagger.process();
+ customer = swagger.getJavaTypeElementSwagger("Customer");
+ root = swagger.getXMLRootElementName(customer);
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ assertThat("RootElement="+root, is(target));
+ }
+
+ @Test
+ public void testGetXmlRootElementName() {
+ String target = "RootElement=customer";
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ String root = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ swagger.process();
+ root = swagger.getXmlRootElementName("Customer");
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ assertThat("RootElement="+root, is(target));
+ }
+
+ @Test
+ public void testGetJavaTypeElementSwagger() {
+ String target = "Element=java-type/Customer";
+ Version v = Version.v11;
+ String apiVersion = v.toString();
+ Element customer = null;
+ File edgeRuleFile = new File("../aai-core" + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
+ try {
+ YAMLfromOXM swagger = new YAMLfromOXM(testXML, v, edgeRuleFile);
+ swagger.process();
+ customer = swagger.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 &copy; 2017 AT&amp;T Intellectual Property. All rights reserved.\n");
+ sb.append("\n");
+ sb.append(" Licensed under the Creative Commons License, Attribution 4.0 Intl. (the &quot;License&quot;); 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 &quot;AS IS&quot; 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(" ECOMP and OpenECOMP are trademarks and service marks of AT&amp;T Intellectual Property.\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 ECOMP 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 across ECOMP.\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 ECOMP 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 across ECOMP.\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(" - 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 ECOMP 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 across ECOMP.\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 ECOMP 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 across ECOMP.\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 ECOMP 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 ECOMP 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 ECOMP 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(" - 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 ECOMP 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 ECOMP 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( 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 ECOMP 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( service-subscription BelongsTo customer, MANY2ONE)(4)\n");
+ sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n");
+ sb.append(" - FROM service-instance( 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 across ECOMP.\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( 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 ECOMP 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( service-subscription BelongsTo customer, MANY2ONE)(4)\n");
+ sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n");
+ sb.append(" - FROM service-instance( 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 across ECOMP.\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( 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 ECOMP 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( service-subscription BelongsTo customer, MANY2ONE)(4)\n");
+ sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n");
+ sb.append(" - FROM service-instance( 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 across ECOMP.\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();
+ }
+}