From 7343beeaf260747aef6a6b9c22acd91de67c5ca0 Mon Sep 17 00:00:00 2001 From: Fiete Ostkamp Date: Mon, 19 Sep 2022 16:55:36 +0200 Subject: [PATCH] Add instructions to invoke the linter and code formatter plugins to the README and invoke the formatter Issue-ID: AAI-3526 Signed-off-by: Fiete Ostkamp Change-Id: Ibd383994732cea6460153704a1153beb530dc6c3 --- README.md | 17 +- .../java/org/onap/aai/annotations/Metadata.java | 72 +- .../org/onap/aai/schema/enums/ObjectMetadata.java | 218 +-- .../onap/aai/schema/enums/PropertyMetadata.java | 116 +- .../org/onap/aai/annotations/AnnotationsTest.java | 6 +- .../org/onap/aai/queries/CustomQueryConfig.java | 62 +- .../org/onap/aai/queries/GetCustomQueryConfig.java | 196 ++- .../onap/aai/queries/GremlinServerSingleton.java | 77 +- .../test/java/org/onap/aai/queries/AAISetup.java | 90 +- .../java/org/onap/aai/queries/OnapQueryTest.java | 269 ++-- .../aai/queries/VnfToEsrSystemInfoQueryTest.java | 140 +- .../org/onap/aai/schemagen/AutoGenerateHtml.java | 43 +- .../java/org/onap/aai/schemagen/GenerateXsd.java | 476 +++--- .../onap/aai/schemagen/SchemaConfiguration.java | 12 +- .../org/onap/aai/schemagen/SpringContextAware.java | 27 +- .../schemagen/SwaggerGenerationConfiguration.java | 15 +- .../schemagen/genxsd/ConfigTranslatorForDocs.java | 93 +- .../aai/schemagen/genxsd/DeleteFootnoteSet.java | 65 +- .../onap/aai/schemagen/genxsd/DeleteOperation.java | 14 +- .../onap/aai/schemagen/genxsd/EdgeDescription.java | 35 +- .../onap/aai/schemagen/genxsd/GetOperation.java | 36 +- .../org/onap/aai/schemagen/genxsd/HTMLfromOXM.java | 39 +- .../aai/schemagen/genxsd/NodeGetOperation.java | 17 +- .../aai/schemagen/genxsd/NodesYAMLfromOXM.java | 43 +- .../aai/schemagen/genxsd/OxmFileProcessor.java | 13 +- .../onap/aai/schemagen/genxsd/PatchOperation.java | 14 +- .../onap/aai/schemagen/genxsd/PutOperation.java | 16 +- .../aai/schemagen/genxsd/PutRelationPathSet.java | 26 +- .../org/onap/aai/schemagen/genxsd/XSDElement.java | 39 +- .../org/onap/aai/schemagen/genxsd/XSDJavaType.java | 21 +- .../org/onap/aai/schemagen/genxsd/YAMLfromOXM.java | 62 +- .../java/org/onap/aai/schemagen/swagger/Api.java | 1 + .../org/onap/aai/schemagen/swagger/Definition.java | 2 +- .../aai/schemagen/swagger/GenerateSwagger.java | 482 +++--- .../org/onap/aai/schemagen/GenerateXsdTest.java | 193 ++- .../schemagen/genxsd/DeleteFootnoteSetTest.java | 100 +- .../aai/schemagen/genxsd/DeleteOperationTest.java | 105 +- .../aai/schemagen/genxsd/EdgeDescriptionTest.java | 564 +++---- .../aai/schemagen/genxsd/GetOperationTest.java | 146 +- .../onap/aai/schemagen/genxsd/HTMLfromOXMTest.java | 664 ++++---- .../aai/schemagen/genxsd/NodeGetOperationTest.java | 152 +- .../aai/schemagen/genxsd/NodesYAMLfromOXMTest.java | 798 +++++----- .../aai/schemagen/genxsd/PatchOperationTest.java | 107 +- .../aai/schemagen/genxsd/PutOperationTest.java | 109 +- .../schemagen/genxsd/PutRelationPathSetTest.java | 388 +++-- .../onap/aai/schemagen/genxsd/XSDElementTest.java | 1285 +++++++++------- .../onap/aai/schemagen/genxsd/XSDJavaTypeTest.java | 129 +- .../onap/aai/schemagen/genxsd/YAMLfromOXMTest.java | 1599 ++++++++++---------- .../onap/aai/schemagen/swagger/DefinitionTest.java | 9 +- .../TestUtilConfigTranslatorforBusiness.java | 73 +- .../TestUtilConfigTranslatorforDataLink.java | 69 +- .../TestUtilConfigTranslatorforEdges.java | 77 +- .../java/org/onap/aai/schemaservice/Profiles.java | 3 +- .../onap/aai/schemaservice/SchemaServiceApp.java | 44 +- .../schemaservice/config/AAIConfigTranslator.java | 133 +- .../config/AuthorizationConfiguration.java | 5 +- .../aai/schemaservice/config/ConfigTranslator.java | 61 +- .../aai/schemaservice/config/ErrorHandler.java | 14 +- .../schemaservice/config/JettyPasswordDecoder.java | 3 +- .../aai/schemaservice/config/PasswordDecoder.java | 3 +- .../config/PropertyPasswordConfiguration.java | 15 +- .../schemaservice/config/SchemaConfiguration.java | 15 +- .../schemaservice/config/SchemaLocationsBean.java | 219 +-- .../onap/aai/schemaservice/edges/EdgeResource.java | 51 +- .../org/onap/aai/schemaservice/edges/EdgeRule.java | 21 +- .../onap/aai/schemaservice/edges/EdgeRules.java | 9 +- .../onap/aai/schemaservice/edges/EdgeService.java | 52 +- .../schemaservice/healthcheck/EchoResource.java | 46 +- .../interceptors/AAIContainerFilter.java | 7 +- .../interceptors/AAIHeaderProperties.java | 3 +- .../schemaservice/interceptors/package-info.java | 5 +- .../post/AAIResponseFilterPriority.java | 3 +- .../interceptors/post/InvalidResponseStatus.java | 20 +- .../post/ResponseHeaderManipulation.java | 7 +- .../post/ResponseTransactionLogging.java | 35 +- .../interceptors/pre/AAIRequestFilterPriority.java | 3 +- .../interceptors/pre/HeaderValidation.java | 38 +- .../interceptors/pre/HttpHeaderInterceptor.java | 16 +- .../interceptors/pre/OneWaySslAuthorization.java | 32 +- .../pre/RequestHeaderManipulation.java | 17 +- .../pre/RequestTransactionLogging.java | 21 +- .../schemaservice/logging/LocalHostAccessLog.java | 11 +- .../aai/schemaservice/nodeschema/NodeIngestor.java | 55 +- .../nodeschema/NodeSchemaResource.java | 42 +- .../nodeschema/NodeSchemaService.java | 33 +- .../schemaservice/nodeschema/SchemaVersion.java | 30 +- .../schemaservice/nodeschema/SchemaVersions.java | 72 +- .../validation/AAISchemaValidationException.java | 9 +- .../validation/CheckEverythingStrategy.java | 67 +- ...ultDuplicateNodeDefinitionValidationModule.java | 119 +- .../validation/DefaultVersionValidationModule.java | 71 +- .../DuplicateNodeDefinitionValidationModule.java | 25 +- .../nodeschema/validation/FailFastStrategy.java | 59 +- .../nodeschema/validation/NodeValidator.java | 56 +- .../nodeschema/validation/SchemaErrorStrategy.java | 63 +- .../validation/VersionValidationModule.java | 18 +- .../nodeschema/validation/VersionValidator.java | 37 +- .../aai/schemaservice/query/QueryResource.java | 11 +- .../onap/aai/schemaservice/query/QueryService.java | 22 +- .../service/AuthorizationService.java | 54 +- .../onap/aai/schemaservice/versions/Version.java | 41 +- .../schemaservice/versions/VersionResource.java | 12 +- .../aai/schemaservice/versions/VersionService.java | 10 +- .../aai/schemaservice/web/JerseyConfiguration.java | 35 +- .../onap/aai/schemaservice/SchemaServiceTest.java | 83 +- .../SchemaServiceTestConfiguration.java | 55 +- .../org/onap/aai/schema/ValidateEdgeRulesTest.java | 74 +- .../java/org/onap/aai/schema/ValidateOXMTest.java | 571 +++---- 108 files changed, 6251 insertions(+), 5806 deletions(-) diff --git a/README.md b/README.md index a504159..6b8bcab 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,20 @@ # AAI Schema Service +## Development ### Local setup - In order to start the service locally, here is what needs to be done - -``` -> mvn clean install +``` bash +mvn clean install ``` -Above command only needs to be run the first time +Above command only needs to be run the first time. The command below actually starts the microservice - +``` bash +mvn -pl aai-schema-service -PrunAjsc ``` -> mvn -pl aai-schema-service -PrunAjsc + +### Run code formatter +``` bash +mvn formatter:format spotless:apply process-sources ``` diff --git a/aai-annotations/src/main/java/org/onap/aai/annotations/Metadata.java b/aai-annotations/src/main/java/org/onap/aai/annotations/Metadata.java index 53ffa5a..142cac9 100644 --- a/aai-annotations/src/main/java/org/onap/aai/annotations/Metadata.java +++ b/aai-annotations/src/main/java/org/onap/aai/annotations/Metadata.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.annotations; import static java.lang.annotation.RetentionPolicy.RUNTIME; @@ -29,29 +30,52 @@ import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD}) public @interface Metadata { - boolean isKey() default false; - String description() default ""; - String nameProps() default ""; - String indexedProps() default ""; - String dependentOn() default ""; - String container() default ""; - String namespace() default ""; - String defaultValue() default ""; - String searchable() default ""; - String uniqueProps() default ""; - String requiredProps() default ""; - String uriTemplate() default ""; - String extendsFrom() default ""; - String isAbstract() default ""; - String alternateKeys1() default ""; - String maximumDepth() default ""; - String crossEntityReference() default ""; - String requires() default ""; - String dbAlias() default ""; - String dataLocation() default ""; - String containsSuggestibleProps() default ""; - String suggestionAliases() default ""; - String sourceOfTruthType() default ""; + boolean isKey() default false; + + String description() default ""; + + String nameProps() default ""; + + String indexedProps() default ""; + + String dependentOn() default ""; + + String container() default ""; + + String namespace() default ""; + + String defaultValue() default ""; + + String searchable() default ""; + + String uniqueProps() default ""; + + String requiredProps() default ""; + + String uriTemplate() default ""; + + String extendsFrom() default ""; + + String isAbstract() default ""; + + String alternateKeys1() default ""; + + String maximumDepth() default ""; + + String crossEntityReference() default ""; + + String requires() default ""; + + String dbAlias() default ""; + + String dataLocation() default ""; + + String containsSuggestibleProps() default ""; + + String suggestionAliases() default ""; + + String sourceOfTruthType() default ""; + String dslStartNodeProps() default ""; } diff --git a/aai-annotations/src/main/java/org/onap/aai/schema/enums/ObjectMetadata.java b/aai-annotations/src/main/java/org/onap/aai/schema/enums/ObjectMetadata.java index a4a5de9..406800f 100644 --- a/aai-annotations/src/main/java/org/onap/aai/schema/enums/ObjectMetadata.java +++ b/aai-annotations/src/main/java/org/onap/aai/schema/enums/ObjectMetadata.java @@ -8,7 +8,7 @@ * 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, @@ -17,122 +17,130 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schema.enums; public enum ObjectMetadata { - /** - * description of object - */ - DESCRIPTION("description"), - /** - * names of properties to appear in relationship-lists - * and parent objects in DMaaP messages - *
comma separated list - */ - NAME_PROPS("nameProps"), - /** - * names of properties to be indexed in the - * db schema - *
comma separated list - */ - INDEXED_PROPS("indexedProps"), - /** - * name of the object this one depends on - */ - DEPENDENT_ON("dependentOn"), - /** - * name of the object which contains this object - */ - CONTAINER("container"), - /** - * the top level namespace to which this object belongs
- * only valid on top level objects - */ - NAMESPACE("namespace"), - /** - * properties which are searchable via the GUI - *
comma separated list - */ - SEARCHABLE("searchable"), - /** - * properties marked as unique in the db schema - *
comma separated list - */ - UNIQUE_PROPS("uniqueProps"), - /** - * properties marked as required - *
comma separated list - */ - REQUIRED_PROPS("requiredProps"), - /** - * uri template for this object - */ - URI_TEMPLATE("uriTemplate"), - /** - * abstract type from which this object extends - */ - EXTENDS("extends"), - /** - * comma separated list of objects who inherit this object
- * only valid on abstract objects - */ - INHERITORS("inheritors"), - /** - * a value of true marks this object as abstract - * abstract objects cannot be read/written directly - * they resolve to "or queries" when used in queries - */ - ABSTRACT("abstract"), - /** - * comma separated list of properties which are alternate ways - * to identify this object - */ - ALTERNATE_KEYS_1("alternateKeys1"), - /** - * the maximum allowable retrievable depth - */ - MAXIMUM_DEPTH("maximumDepth"), - /** - * collection of other objects to retrieve along with this one - *
comma separated list - */ - CROSS_ENTITY_REFERENCE("crossEntityReference"), - /** - * Marks that this object can be linked to via dataLink - */ - CAN_BE_LINKED("canBeLinked"), - /** - * The entity contains properties that are suggestible - */ - CONTAINS_SUGGESTIBLE_PROPS("containsSuggestibleProps"), - /** - * A list of aliases for the entity name (for AAI UI searches) - */ - SUGGESTION_ALIASES("suggestionAliases"), - /** - * a value of true allows this object to be read directly - */ - ALLOW_DIRECT_READ("allowDirectRead"), - /** - * a value of true allows this object to be written directly - */ - ALLOW_DIRECT_WRITE("allowDirectWrite"), + /** + * description of object + */ + DESCRIPTION("description"), + /** + * names of properties to appear in relationship-lists + * and parent objects in DMaaP messages + *
+ * comma separated list + */ + NAME_PROPS("nameProps"), + /** + * names of properties to be indexed in the + * db schema + *
+ * comma separated list + */ + INDEXED_PROPS("indexedProps"), + /** + * name of the object this one depends on + */ + DEPENDENT_ON("dependentOn"), + /** + * name of the object which contains this object + */ + CONTAINER("container"), + /** + * the top level namespace to which this object belongs
+ * only valid on top level objects + */ + NAMESPACE("namespace"), + /** + * properties which are searchable via the GUI + *
+ * comma separated list + */ + SEARCHABLE("searchable"), + /** + * properties marked as unique in the db schema + *
+ * comma separated list + */ + UNIQUE_PROPS("uniqueProps"), + /** + * properties marked as required + *
+ * comma separated list + */ + REQUIRED_PROPS("requiredProps"), + /** + * uri template for this object + */ + URI_TEMPLATE("uriTemplate"), + /** + * abstract type from which this object extends + */ + EXTENDS("extends"), + /** + * comma separated list of objects who inherit this object
+ * only valid on abstract objects + */ + INHERITORS("inheritors"), + /** + * a value of true marks this object as abstract + * abstract objects cannot be read/written directly + * they resolve to "or queries" when used in queries + */ + ABSTRACT("abstract"), + /** + * comma separated list of properties which are alternate ways + * to identify this object + */ + ALTERNATE_KEYS_1("alternateKeys1"), + /** + * the maximum allowable retrievable depth + */ + MAXIMUM_DEPTH("maximumDepth"), + /** + * collection of other objects to retrieve along with this one + *
+ * comma separated list + */ + CROSS_ENTITY_REFERENCE("crossEntityReference"), + /** + * Marks that this object can be linked to via dataLink + */ + CAN_BE_LINKED("canBeLinked"), + /** + * The entity contains properties that are suggestible + */ + CONTAINS_SUGGESTIBLE_PROPS("containsSuggestibleProps"), + /** + * A list of aliases for the entity name (for AAI UI searches) + */ + SUGGESTION_ALIASES("suggestionAliases"), + /** + * a value of true allows this object to be read directly + */ + ALLOW_DIRECT_READ("allowDirectRead"), + /** + * a value of true allows this object to be written directly + */ + ALLOW_DIRECT_WRITE("allowDirectWrite"), /** * properties that are allowed to be in start node in a DSL - *
comma separated list + *
+ * comma separated list */ DSL_START_NODE_PROPS("dslStartNodeProps"); - private final String name; - private ObjectMetadata(String name) { - this.name = name; + private ObjectMetadata(String name) { + this.name = name; } - @Override public String toString() { - return name; + @Override + public String toString() { + return name; } - + } diff --git a/aai-annotations/src/main/java/org/onap/aai/schema/enums/PropertyMetadata.java b/aai-annotations/src/main/java/org/onap/aai/schema/enums/PropertyMetadata.java index b392721..559501a 100644 --- a/aai-annotations/src/main/java/org/onap/aai/schema/enums/PropertyMetadata.java +++ b/aai-annotations/src/main/java/org/onap/aai/schema/enums/PropertyMetadata.java @@ -8,7 +8,7 @@ * 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, @@ -17,68 +17,70 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schema.enums; public enum PropertyMetadata { - /** - * description of property - */ - DESCRIPTION("description"), - /** - * default value of property - */ - DEFAULT_VALUE("defaultValue"), - /** - * sets the property name used when writing to the db - */ - DB_ALIAS("dbAlias"), - /** - * a URI which describes the location of a value to be - * written on a PUT - */ - DATA_COPY("dataCopy"), - /** - * a URI which describes another object which backs this value - */ - DATA_LINK("dataLink"), - /** - * controls the visibility of a field based on context - */ - VISIBILITY("visibility"), - /** - * specifies a field which must be populated to pass validation - */ - REQUIRES("requires"), - /** - * automatically creates an id for the property if not specified - */ - AUTO_GENERATE_UUID("autoGenerateUuid"), - /** - * Property is used for VNF searches in AAI UI - */ - SUGGESTIBLE_ON_SEARCH("suggestibleOnSearch"), - /** - * An identifier that indicates which system is the master of this property data - */ - SOURCE_OF_TRUTH_TYPE("sourceOfTruthType"), - /** - * makes property read only by version - */ - READ_ONLY("readOnly"), - /** - * Add a private edge between two objects based on the uri provided by user which should provide - * the appropriate information from the url similar to dataCopy - */ - PRIVATE_EDGE("privateEdge"); - - private final String name; + /** + * description of property + */ + DESCRIPTION("description"), + /** + * default value of property + */ + DEFAULT_VALUE("defaultValue"), + /** + * sets the property name used when writing to the db + */ + DB_ALIAS("dbAlias"), + /** + * a URI which describes the location of a value to be + * written on a PUT + */ + DATA_COPY("dataCopy"), + /** + * a URI which describes another object which backs this value + */ + DATA_LINK("dataLink"), + /** + * controls the visibility of a field based on context + */ + VISIBILITY("visibility"), + /** + * specifies a field which must be populated to pass validation + */ + REQUIRES("requires"), + /** + * automatically creates an id for the property if not specified + */ + AUTO_GENERATE_UUID("autoGenerateUuid"), + /** + * Property is used for VNF searches in AAI UI + */ + SUGGESTIBLE_ON_SEARCH("suggestibleOnSearch"), + /** + * An identifier that indicates which system is the master of this property data + */ + SOURCE_OF_TRUTH_TYPE("sourceOfTruthType"), + /** + * makes property read only by version + */ + READ_ONLY("readOnly"), + /** + * Add a private edge between two objects based on the uri provided by user which should provide + * the appropriate information from the url similar to dataCopy + */ + PRIVATE_EDGE("privateEdge"); + + private final String name; - private PropertyMetadata(String name) { - this.name = name; + private PropertyMetadata(String name) { + this.name = name; } - @Override public String toString() { - return name; + @Override + public String toString() { + return name; } } diff --git a/aai-annotations/src/test/java/org/onap/aai/annotations/AnnotationsTest.java b/aai-annotations/src/test/java/org/onap/aai/annotations/AnnotationsTest.java index 5a2ab8b..9ff262d 100644 --- a/aai-annotations/src/test/java/org/onap/aai/annotations/AnnotationsTest.java +++ b/aai-annotations/src/test/java/org/onap/aai/annotations/AnnotationsTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.annotations; import static org.junit.Assert.assertTrue; @@ -28,7 +29,8 @@ public class AnnotationsTest { public AnnotationsTest() { } - @Metadata(isKey = false, + @Metadata( + isKey = false, description = "", nameProps = "", indexedProps = "", diff --git a/aai-queries/src/main/java/org/onap/aai/queries/CustomQueryConfig.java b/aai-queries/src/main/java/org/onap/aai/queries/CustomQueryConfig.java index 664c9ca..1b9e833 100644 --- a/aai-queries/src/main/java/org/onap/aai/queries/CustomQueryConfig.java +++ b/aai-queries/src/main/java/org/onap/aai/queries/CustomQueryConfig.java @@ -8,7 +8,7 @@ * 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, @@ -17,37 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.queries; import java.util.List; public class CustomQueryConfig { - public CustomQueryConfig() { - // used by GetCustomQueryConfig - } - - - private String query; - private List queryOptionalProperties; - private List queryRequiredProperties; - - public void setQuery(String query) { - this.query = query; - } - public String getQuery() { - return this.query; - } - - public void setQueryOptionalProperties( List queryOptionalProperties) { - this.queryOptionalProperties = queryOptionalProperties; - } - public List getQueryOptionalProperties( ) { - return queryOptionalProperties; - } - public void setQueryRequiredProperties( List queryRequiredProperties) { - this.queryRequiredProperties = queryRequiredProperties; - } - public List getQueryRequiredProperties( ) { - return queryRequiredProperties; - } + public CustomQueryConfig() { + // used by GetCustomQueryConfig + } + + private String query; + private List queryOptionalProperties; + private List queryRequiredProperties; + + public void setQuery(String query) { + this.query = query; + } + + public String getQuery() { + return this.query; + } + + public void setQueryOptionalProperties(List queryOptionalProperties) { + this.queryOptionalProperties = queryOptionalProperties; + } + + public List getQueryOptionalProperties() { + return queryOptionalProperties; + } + + public void setQueryRequiredProperties(List queryRequiredProperties) { + this.queryRequiredProperties = queryRequiredProperties; + } + + public List getQueryRequiredProperties() { + return queryRequiredProperties; + } } diff --git a/aai-queries/src/main/java/org/onap/aai/queries/GetCustomQueryConfig.java b/aai-queries/src/main/java/org/onap/aai/queries/GetCustomQueryConfig.java index c726c76..07f7724 100644 --- a/aai-queries/src/main/java/org/onap/aai/queries/GetCustomQueryConfig.java +++ b/aai-queries/src/main/java/org/onap/aai/queries/GetCustomQueryConfig.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.queries; import com.google.gson.*; @@ -28,122 +29,119 @@ import java.util.List; public class GetCustomQueryConfig { - private JsonArray storedQueries = null; - private CustomQueryConfig customQueryConfig; + private JsonArray storedQueries = null; + private CustomQueryConfig customQueryConfig; + private final static String QUERY_CONFIG = "query"; + private final static String REQUIRED_CONFIG = "required-properties"; + private final static String OPTIONAL_CONFIG = "optional-properties"; + private final static String STORED_QUERIES_CONFIG = "stored-queries"; + private final static String STORED_QUERY_CONFIG = "stored-query"; - private final static String QUERY_CONFIG = "query"; - private final static String REQUIRED_CONFIG = "required-properties"; - private final static String OPTIONAL_CONFIG = "optional-properties"; - private final static String STORED_QUERIES_CONFIG = "stored-queries"; - private final static String STORED_QUERY_CONFIG = "stored-query"; + // public static final String AAI_HOME_ETC_QUERY_JSON = AAIConstants.AAI_HOME_ETC + "query" + + // AAIConstants.AAI_FILESEP + "stored-queries.json"; -// public static final String AAI_HOME_ETC_QUERY_JSON = AAIConstants.AAI_HOME_ETC + "query" + AAIConstants.AAI_FILESEP + "stored-queries.json"; + public GetCustomQueryConfig(String customQueryJson) { + init(customQueryJson); + } - public GetCustomQueryConfig(String customQueryJson ) { - init(customQueryJson); - } + private void init(String customQueryJson) { + JsonParser parser = new JsonParser(); + JsonObject queriesObject = parser.parse(customQueryJson).getAsJsonObject(); + if (queriesObject.has(STORED_QUERIES_CONFIG)) { - private void init( String customQueryJson) { - JsonParser parser = new JsonParser(); - JsonObject queriesObject = parser.parse(customQueryJson).getAsJsonObject(); - if (queriesObject.has(STORED_QUERIES_CONFIG)) { + storedQueries = queriesObject.getAsJsonArray(STORED_QUERIES_CONFIG); + } + } - storedQueries = queriesObject.getAsJsonArray(STORED_QUERIES_CONFIG); + private List toStringList(JsonArray array) { + Gson converter = new Gson(); + Type listType = new TypeToken>() {}.getType(); + return converter.fromJson(array, listType); } - } - - private List toStringList(JsonArray array) { - Gson converter = new Gson(); - Type listType = new TypeToken>() {}.getType(); - return converter.fromJson(array, listType); - } - - private List getPropertyList(JsonObject configObject, String config ) { - JsonElement subqueryConfig; - JsonArray props; - - if ( configObject.has(config)) { - subqueryConfig = configObject.get(config); - if ( subqueryConfig != null && !subqueryConfig.isJsonNull() ) { - props = subqueryConfig.getAsJsonArray(); - if ( props != null ) { - return toStringList(props); + + private List getPropertyList(JsonObject configObject, String config) { + JsonElement subqueryConfig; + JsonArray props; + + if (configObject.has(config)) { + subqueryConfig = configObject.get(config); + if (subqueryConfig != null && !subqueryConfig.isJsonNull()) { + props = subqueryConfig.getAsJsonArray(); + if (props != null) { + return toStringList(props); + } + } } - } + return toStringList(null); } - return toStringList(null); - } - private String getPropertyString(JsonObject configObject, String config) { - JsonElement subqueryConfig; + private String getPropertyString(JsonObject configObject, String config) { + JsonElement subqueryConfig; - if ( configObject.has(config)) { - subqueryConfig = configObject.get(config); - if ( subqueryConfig != null && !subqueryConfig.isJsonNull() ) { - return subqueryConfig.getAsString(); - } - } - return null; - } - - private void getStoredQueryBlock( JsonObject configObject, String config ) { - if ( !configObject.has(config)) { - customQueryConfig.setQueryRequiredProperties( new ArrayList() ); - customQueryConfig.setQueryOptionalProperties( new ArrayList() ); - return; + if (configObject.has(config)) { + subqueryConfig = configObject.get(config); + if (subqueryConfig != null && !subqueryConfig.isJsonNull()) { + return subqueryConfig.getAsString(); + } + } + return null; } - JsonElement queryConfig; - JsonObject subObject; - String multipleStartNodes; - List propertyList; + private void getStoredQueryBlock(JsonObject configObject, String config) { + if (!configObject.has(config)) { + customQueryConfig.setQueryRequiredProperties(new ArrayList()); + customQueryConfig.setQueryOptionalProperties(new ArrayList()); + return; + } + + JsonElement queryConfig; + JsonObject subObject; + String multipleStartNodes; + List propertyList; - queryConfig = configObject.get(config); - subObject = queryConfig.getAsJsonObject(); - propertyList = getPropertyList(subObject, REQUIRED_CONFIG); - if ( propertyList == null ) { - propertyList = new ArrayList(); - } - customQueryConfig.setQueryRequiredProperties( propertyList ); - propertyList = getPropertyList(subObject, OPTIONAL_CONFIG); - if ( propertyList == null ) { - propertyList = new ArrayList(); - } - customQueryConfig.setQueryOptionalProperties( propertyList ); - - } - - - public CustomQueryConfig getStoredQuery(String queryName ) { - - customQueryConfig = null; - JsonObject configObject; - JsonElement query; - JsonElement queryConfig; - String queryString; - - for (JsonElement storedQuery : storedQueries) { - if (storedQuery.isJsonObject()) { - JsonObject queryObject = storedQuery.getAsJsonObject(); - query = queryObject.get(queryName); - if ( query != null ) { - customQueryConfig = new CustomQueryConfig(); - configObject = query.getAsJsonObject(); - getStoredQueryBlock(configObject, QUERY_CONFIG); - if ( configObject.has(STORED_QUERY_CONFIG)) { - queryConfig = configObject.get(STORED_QUERY_CONFIG); - customQueryConfig.setQuery(queryConfig.getAsString()); - } - break; + queryConfig = configObject.get(config); + subObject = queryConfig.getAsJsonObject(); + propertyList = getPropertyList(subObject, REQUIRED_CONFIG); + if (propertyList == null) { + propertyList = new ArrayList(); } - } - } + customQueryConfig.setQueryRequiredProperties(propertyList); + propertyList = getPropertyList(subObject, OPTIONAL_CONFIG); + if (propertyList == null) { + propertyList = new ArrayList(); + } + customQueryConfig.setQueryOptionalProperties(propertyList); - return customQueryConfig; + } - } + public CustomQueryConfig getStoredQuery(String queryName) { + + customQueryConfig = null; + JsonObject configObject; + JsonElement query; + JsonElement queryConfig; + String queryString; + + for (JsonElement storedQuery : storedQueries) { + if (storedQuery.isJsonObject()) { + JsonObject queryObject = storedQuery.getAsJsonObject(); + query = queryObject.get(queryName); + if (query != null) { + customQueryConfig = new CustomQueryConfig(); + configObject = query.getAsJsonObject(); + getStoredQueryBlock(configObject, QUERY_CONFIG); + if (configObject.has(STORED_QUERY_CONFIG)) { + queryConfig = configObject.get(STORED_QUERY_CONFIG); + customQueryConfig.setQuery(queryConfig.getAsString()); + } + break; + } + } + } + return customQueryConfig; + } } diff --git a/aai-queries/src/main/java/org/onap/aai/queries/GremlinServerSingleton.java b/aai-queries/src/main/java/org/onap/aai/queries/GremlinServerSingleton.java index 509aa88..dd0db86 100644 --- a/aai-queries/src/main/java/org/onap/aai/queries/GremlinServerSingleton.java +++ b/aai-queries/src/main/java/org/onap/aai/queries/GremlinServerSingleton.java @@ -8,7 +8,7 @@ * 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, @@ -17,17 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.queries; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.aai.aaf.auth.FileWatcher; -import org.onap.aai.logging.LogFormatTools; -import org.onap.aai.util.AAIConstants; -import org.springframework.beans.factory.annotation.Value; -import javax.annotation.PostConstruct; +package org.onap.aai.queries; import java.io.File; import java.io.IOException; @@ -38,6 +29,15 @@ import java.util.Date; import java.util.Timer; import java.util.TimerTask; +import javax.annotation.PostConstruct; + +import org.onap.aai.aaf.auth.FileWatcher; +import org.onap.aai.logging.LogFormatTools; +import org.onap.aai.util.AAIConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; + public class GremlinServerSingleton { private static Logger logger = LoggerFactory.getLogger(GremlinServerSingleton.class); @@ -62,56 +62,57 @@ public class GremlinServerSingleton { @PostConstruct public void init() { - try { - String filepath = storedQueriesLocation + AAIConstants.AAI_FILESEP + "stored-queries.json"; - Path path = Paths.get(filepath); - String customQueryConfigJson = new String(Files.readAllBytes(path)); - - - queryConfig = new GetCustomQueryConfig(customQueryConfigJson); - } catch (IOException e) { - logger.error("Error occurred during the processing of query json file: " + LogFormatTools.getStackTop(e)); - } + try { + String filepath = + storedQueriesLocation + AAIConstants.AAI_FILESEP + "stored-queries.json"; + Path path = Paths.get(filepath); + String customQueryConfigJson = new String(Files.readAllBytes(path)); + queryConfig = new GetCustomQueryConfig(customQueryConfigJson); + } catch (IOException e) { + logger.error("Error occurred during the processing of query json file: " + + LogFormatTools.getStackTop(e)); + } TimerTask task = new FileWatcher(new File(storedQueriesLocation)) { @Override protected void onChange(File file) { - try { - String filepath = storedQueriesLocation; - Path path = Paths.get(filepath); - String customQueryConfigJson = new String(Files.readAllBytes(path)); - queryConfig = new GetCustomQueryConfig(customQueryConfigJson); - } catch (IOException e) { - logger.error("Error occurred during the processing of query json file: " + LogFormatTools.getStackTop(e)); - } + try { + String filepath = storedQueriesLocation; + Path path = Paths.get(filepath); + String customQueryConfigJson = new String(Files.readAllBytes(path)); + queryConfig = new GetCustomQueryConfig(customQueryConfigJson); + } catch (IOException e) { + logger.error("Error occurred during the processing of query json file: " + + LogFormatTools.getStackTop(e)); + } } }; if (!timerSet) { timerSet = true; timer = new Timer(); - timer.schedule( task , new Date(), 10000 ); + timer.schedule(task, new Date(), 10000); } } /** * Gets the query using CustomQueryConfig + * * @param key * @return */ - public String getStoredQueryFromConfig(String key){ - CustomQueryConfig customQueryConfig = queryConfig.getStoredQuery(key); - if ( customQueryConfig == null ) { - return null; - } - return customQueryConfig.getQuery(); + public String getStoredQueryFromConfig(String key) { + CustomQueryConfig customQueryConfig = queryConfig.getStoredQuery(key); + if (customQueryConfig == null) { + return null; + } + return customQueryConfig.getQuery(); } public CustomQueryConfig getCustomQueryConfig(String key) { - return queryConfig.getStoredQuery(key); + return queryConfig.getStoredQuery(key); } - } diff --git a/aai-queries/src/test/java/org/onap/aai/queries/AAISetup.java b/aai-queries/src/test/java/org/onap/aai/queries/AAISetup.java index 15943b7..2ca90ea 100644 --- a/aai-queries/src/test/java/org/onap/aai/queries/AAISetup.java +++ b/aai-queries/src/test/java/org/onap/aai/queries/AAISetup.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.queries; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -43,58 +50,43 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; - -import static org.junit.Assert.assertNotNull; - -@ContextConfiguration(classes = { - SchemaLocationsBean.class, - SchemaVersions.class, - AAIConfigTranslator.class, - EdgeIngestor.class, - EdgeSerializer.class, - NodeIngestor.class, - SpringContextAware.class, - IntrospectionConfig.class , - RestBeanConfig.class, - GremlinServerSingleton.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.ingest.file = src/test/resources/application-test.properties" -}) +@ContextConfiguration( + classes = {SchemaLocationsBean.class, SchemaVersions.class, AAIConfigTranslator.class, + EdgeIngestor.class, EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, + IntrospectionConfig.class, RestBeanConfig.class, GremlinServerSingleton.class}) +@TestPropertySource( + properties = {"schema.uri.base.path = /aai", + "schema.ingest.file = src/test/resources/application-test.properties"}) public abstract class AAISetup { - @Autowired - protected NodeIngestor nodeIngestor; + @Autowired + protected NodeIngestor nodeIngestor; - @Autowired - protected LoaderFactory loaderFactory; + @Autowired + protected LoaderFactory loaderFactory; - @Autowired - protected Map moxyLoaderInstance; + @Autowired + protected Map moxyLoaderInstance; - @Autowired - protected HttpEntry traversalHttpEntry; + @Autowired + protected HttpEntry traversalHttpEntry; - @Autowired - protected HttpEntry traversalUriHttpEntry; + @Autowired + protected HttpEntry traversalUriHttpEntry; - @Autowired - protected EdgeSerializer edgeSer; + @Autowired + protected EdgeSerializer edgeSer; - @Autowired - protected EdgeIngestor edgeIngestor; + @Autowired + protected EdgeIngestor edgeIngestor; - @Autowired - protected SchemaVersions schemaVersions; + @Autowired + protected SchemaVersions schemaVersions; - @Autowired - protected GremlinServerSingleton gremlinServerSingleton; + @Autowired + protected GremlinServerSingleton gremlinServerSingleton; - @Value("${schema.uri.base.path}") - protected String basePath; + @Value("${schema.uri.base.path}") + protected String basePath; @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @@ -111,9 +103,7 @@ public abstract class AAISetup { public String getPayload(String filename) throws IOException { - InputStream inputStream = getClass() - .getClassLoader() - .getResourceAsStream(filename); + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename); String message = String.format("Unable to find the %s in src/test/resources", filename); assertNotNull(message, inputStream); @@ -122,11 +112,3 @@ public abstract class AAISetup { return resource; } } - - - - - - - - diff --git a/aai-queries/src/test/java/org/onap/aai/queries/OnapQueryTest.java b/aai-queries/src/test/java/org/onap/aai/queries/OnapQueryTest.java index 25591e7..7c766c9 100644 --- a/aai-queries/src/test/java/org/onap/aai/queries/OnapQueryTest.java +++ b/aai-queries/src/test/java/org/onap/aai/queries/OnapQueryTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,14 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.queries; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import com.jayway.jsonpath.JsonPath; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.*; +import java.util.stream.Collectors; + import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -58,6 +70,8 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.setup.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; @@ -65,167 +79,138 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.*; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - @RunWith(Parameterized.class) -@ContextConfiguration(classes = { - SchemaLocationsBean.class, - SchemaConfigVersions.class, - AAIConfigTranslator.class, - EdgeIngestor.class, - EdgeSerializer.class, - NodeIngestor.class, - SpringContextAware.class, - GremlinServerSingleton.class, - IntrospectionConfig.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.source.name = onap", - "schema.ingest.file = src/test/resources/application-test.properties" -}) +@ContextConfiguration( + classes = {SchemaLocationsBean.class, SchemaConfigVersions.class, AAIConfigTranslator.class, + EdgeIngestor.class, EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, + GremlinServerSingleton.class, IntrospectionConfig.class}) +@TestPropertySource( + properties = {"schema.uri.base.path = /aai", "schema.source.name = onap", + "schema.ingest.file = src/test/resources/application-test.properties"}) public abstract class OnapQueryTest { - @ClassRule + @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); - protected Logger logger; - protected Graph graph; - protected GremlinGroovyShell shell; - @Mock protected TransactionalGraphEngine dbEngine; - protected final List expectedResult = new ArrayList<>(); - - @Autowired - protected EdgeIngestor edgeRules; - - @Autowired - protected EdgeSerializer rules; - - @Autowired - protected LoaderFactory loaderFactory; - - @Autowired - protected SchemaVersions schemaVersions; - - protected Loader loader; - protected GraphTraversalSource gts; - - @Autowired - protected GremlinServerSingleton gremlinServerSingleton; - - @Parameterized.Parameter(value = 0) - public SchemaVersion version; - - @Parameterized.Parameters(name = "Version.{0}") - public static Collection data() { - return Arrays.asList(new Object[][]{ - {new SchemaVersion("v11")}, - {new SchemaVersion("v12")}, - {new SchemaVersion("v13")}, - {new SchemaVersion("v14")}, - {new SchemaVersion("v15")}, - {new SchemaVersion("v16")}, - {new SchemaVersion("v17")}, - {new SchemaVersion("v18")}, - {new SchemaVersion("v19")}, - {new SchemaVersion("v20")} - }); - } - - protected String query; - - LinkedHashMap params; - - @Autowired - private Environment env; - - @BeforeClass - public static void setupBundleconfig() { - System.setProperty("AJSC_HOME", "./"); - System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/"); - } - - @Before - public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException, IOException { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); - logger = LoggerFactory.getLogger(getClass()); - MockitoAnnotations.initMocks(this); - graph = TinkerGraph.open(); - gts = graph.traversal(); - createGraph(); - shell = new GremlinGroovyShell(); - loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version); + protected Logger logger; + protected Graph graph; + protected GremlinGroovyShell shell; + @Mock + protected TransactionalGraphEngine dbEngine; + protected final List expectedResult = new ArrayList<>(); + + @Autowired + protected EdgeIngestor edgeRules; + + @Autowired + protected EdgeSerializer rules; + + @Autowired + protected LoaderFactory loaderFactory; + + @Autowired + protected SchemaVersions schemaVersions; + + protected Loader loader; + protected GraphTraversalSource gts; + + @Autowired + protected GremlinServerSingleton gremlinServerSingleton; + + @Parameterized.Parameter(value = 0) + public SchemaVersion version; + + @Parameterized.Parameters(name = "Version.{0}") + public static Collection data() { + return Arrays.asList(new Object[][] {{new SchemaVersion("v11")}, {new SchemaVersion("v12")}, + {new SchemaVersion("v13")}, {new SchemaVersion("v14")}, {new SchemaVersion("v15")}, + {new SchemaVersion("v16")}, {new SchemaVersion("v17")}, {new SchemaVersion("v18")}, + {new SchemaVersion("v19")}, {new SchemaVersion("v20")}}); + } + + protected String query; + + LinkedHashMap params; + + @Autowired + private Environment env; + + @BeforeClass + public static void setupBundleconfig() { + System.setProperty("AJSC_HOME", "./"); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/"); + } + + @Before + public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, + AmbiguousRuleChoiceException, IOException { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); + logger = LoggerFactory.getLogger(getClass()); + MockitoAnnotations.initMocks(this); + graph = TinkerGraph.open(); + gts = graph.traversal(); + createGraph(); + shell = new GremlinGroovyShell(); + loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version); setUpQuery(); - } - - - protected void setUpQuery() { - query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName()); - params = new LinkedHashMap <>(); - addParam(params); - when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal())); - logger.info("Stored query in abstraction form {}", query); - query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params); - logger.info("After converting to gremlin query {}", query); - query = "g" + query; - GraphTraversal g = graph.traversal().V(); - addStartNode(g); - params.put("g", g); - } + } - public void run() { + protected void setUpQuery() { + query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName()); + params = new LinkedHashMap<>(); + addParam(params); + when(dbEngine.getQueryBuilder(any(QueryStyle.class))) + .thenReturn(new GremlinTraversal<>(loader, graph.traversal())); + logger.info("Stored query in abstraction form {}", query); + query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params); + logger.info("After converting to gremlin query {}", query); + query = "g" + query; + GraphTraversal g = graph.traversal().V(); + addStartNode(g); + params.put("g", g); + } - GraphTraversal result = (GraphTraversal)shell.executeTraversal(query, params); + public void run() { - List vertices = result.toList(); + GraphTraversal result = + (GraphTraversal) shell.executeTraversal(query, params); - logger.info("Expected result set of vertexes [{}]", convert(expectedResult)); - logger.info("Actual Result set of vertexes [{}]", convert(vertices)); + List vertices = result.toList(); - List nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult)); - vertices = new ArrayList<>(new HashSet<>(vertices)); + logger.info("Expected result set of vertexes [{}]", convert(expectedResult)); + logger.info("Actual Result set of vertexes [{}]", convert(vertices)); - nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString())); - vertices.sort(Comparator.comparing(vertex -> vertex.id().toString())); + List nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult)); + vertices = new ArrayList<>(new HashSet<>(vertices)); + nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString())); + vertices.sort(Comparator.comparing(vertex -> vertex.id().toString())); - // Use this instead of the assertTrue as this provides more useful - // debugging information such as this when expected and actual differ: - // java.lang.AssertionError: Expected all the vertices to be found - // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]] - // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]] - assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices); + // Use this instead of the assertTrue as this provides more useful + // debugging information such as this when expected and actual differ: + // java.lang.AssertionError: Expected all the vertices to be found + // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]] + // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]] + assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices); - } + } - protected String convert(List vertices){ - return vertices - .stream() - .map(vertex -> vertex.property("aai-node-type").value().toString()) - .collect(Collectors.joining(",")); - } + protected String convert(List vertices) { + return vertices.stream().map(vertex -> vertex.property("aai-node-type").value().toString()) + .collect(Collectors.joining(",")); + } - protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException; + protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException, + EdgeRuleNotFoundException, AmbiguousRuleChoiceException; - protected abstract String getQueryName(); + protected abstract String getQueryName(); - protected abstract void addStartNode(GraphTraversal g); + protected abstract void addStartNode(GraphTraversal g); - protected abstract void addParam(Map params); + protected abstract void addParam(Map params); } diff --git a/aai-queries/src/test/java/org/onap/aai/queries/VnfToEsrSystemInfoQueryTest.java b/aai-queries/src/test/java/org/onap/aai/queries/VnfToEsrSystemInfoQueryTest.java index 6bc2705..373e251 100644 --- a/aai-queries/src/test/java/org/onap/aai/queries/VnfToEsrSystemInfoQueryTest.java +++ b/aai-queries/src/test/java/org/onap/aai/queries/VnfToEsrSystemInfoQueryTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.queries; import static org.junit.Assert.assertTrue; +import java.util.Map; + import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.T; @@ -29,71 +32,78 @@ import org.junit.Test; import org.onap.aai.exceptions.AAIException; import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; -import java.util.Map; - public class VnfToEsrSystemInfoQueryTest extends OnapQueryTest { - public VnfToEsrSystemInfoQueryTest() { - super(); - } + public VnfToEsrSystemInfoQueryTest() { + super(); + } - @Test - public void run() { - super.run(); + @Test + public void run() { + super.run(); assertTrue(true); - } - - @Override - protected void createGraph() throws AAIException, NoEdgeRuleFoundException { - - - Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1"); - Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1"); - Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01"); - Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1"); - Vertex esr = graph.addVertex(T.label, "esr-system-info", T.id, "6", "aai-node-type", "esr-system-info", "esr-system-info-id", "esr-system-info-1"); - - Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2"); - Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", "vserver-id", "vserver-id-2","vserver-name","vserver-name-2"); - Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02"); - Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2"); - Vertex esr1 = graph.addVertex(T.label, "esr-system-info", T.id, "12", "aai-node-type", "esr-system-info", "esr-system-info-id", "esr-system-info-2"); - - - - - GraphTraversalSource g = graph.traversal(); - rules.addEdge(g, gnvf, vserver); - rules.addTreeEdge(g, vserver,tenant); - rules.addTreeEdge(g, tenant,cloudregion); - rules.addTreeEdge(g, cloudregion, esr); - - //Not expected in result - rules.addEdge(g, gnvf1, vserver1); - rules.addTreeEdge(g, vserver1,tenant1); - rules.addTreeEdge(g, tenant1,cloudregion1); - rules.addTreeEdge(g, cloudregion1, esr1); - //Not expected in result - - expectedResult.add(gnvf); - expectedResult.add(vserver); - expectedResult.add(tenant); - expectedResult.add(cloudregion); - expectedResult.add(esr); - - - } - - @Override - protected String getQueryName() { - return "vnf-to-esr-system-info"; - } - @Override - protected void addStartNode(GraphTraversal g) { - g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-1"); - - } - @Override - protected void addParam(Map params) { - return; - } + } + + @Override + protected void createGraph() throws AAIException, NoEdgeRuleFoundException { + + Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", + "generic-vnf", "vnf-id", "vnf-id-1"); + Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", + "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1"); + Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", + "tenant-id", "tenantid01", "tenant-name", "tenantName01"); + Vertex cloudregion = + graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", + "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1"); + Vertex esr = graph.addVertex(T.label, "esr-system-info", T.id, "6", "aai-node-type", + "esr-system-info", "esr-system-info-id", "esr-system-info-1"); + + Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", + "generic-vnf", "vnf-id", "vnf-id-2"); + Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", + "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2"); + Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant", + "tenant-id", "tenantid02", "tenant-name", "tenantName02"); + Vertex cloudregion1 = + graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", + "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2"); + Vertex esr1 = graph.addVertex(T.label, "esr-system-info", T.id, "12", "aai-node-type", + "esr-system-info", "esr-system-info-id", "esr-system-info-2"); + + GraphTraversalSource g = graph.traversal(); + rules.addEdge(g, gnvf, vserver); + rules.addTreeEdge(g, vserver, tenant); + rules.addTreeEdge(g, tenant, cloudregion); + rules.addTreeEdge(g, cloudregion, esr); + + // Not expected in result + rules.addEdge(g, gnvf1, vserver1); + rules.addTreeEdge(g, vserver1, tenant1); + rules.addTreeEdge(g, tenant1, cloudregion1); + rules.addTreeEdge(g, cloudregion1, esr1); + // Not expected in result + + expectedResult.add(gnvf); + expectedResult.add(vserver); + expectedResult.add(tenant); + expectedResult.add(cloudregion); + expectedResult.add(esr); + + } + + @Override + protected String getQueryName() { + return "vnf-to-esr-system-info"; + } + + @Override + protected void addStartNode(GraphTraversal g) { + g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-1"); + + } + + @Override + protected void addParam(Map params) { + return; + } } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/AutoGenerateHtml.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/AutoGenerateHtml.java index 85ecfad..ae5426f 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/AutoGenerateHtml.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/AutoGenerateHtml.java @@ -4,13 +4,13 @@ * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -19,13 +19,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen; import freemarker.template.TemplateException; -import org.onap.aai.schemagen.swagger.GenerateSwagger; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; @@ -33,23 +30,25 @@ import java.util.Collections; import java.util.List; import java.util.ListIterator; +import org.onap.aai.schemagen.swagger.GenerateSwagger; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + public class AutoGenerateHtml { private static final String AAI_GENERATE_VERSION = "aai.generate.version"; public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - //if the program is run from aai-common, use this directory as default" + // if the program is run from aai-common, use this directory as default" public static final String ALT_SCHEMA_DIR = "aai-schema"; - //used to check to see if program is run from aai-schema-gen + // used to check to see if program is run from aai-schema-gen public static final String DEFAULT_RUN_DIR = "aai-schema-gen"; public static void main(String[] args) throws IOException, TemplateException { String savedProperty = System.getProperty(AAI_GENERATE_VERSION); - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( - "org.onap.aai.setup", - "org.onap.aai.schemagen" - ); - + AnnotationConfigApplicationContext ctx = + new AnnotationConfigApplicationContext("org.onap.aai.setup", "org.onap.aai.schemagen"); SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class); @@ -58,18 +57,20 @@ public class AutoGenerateHtml { Collections.reverse(versionsToGen); ListIterator versionIterator = versionsToGen.listIterator(); String schemaDir; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { + if (System.getProperty("user.dir") != null + && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { schemaDir = ALT_SCHEMA_DIR; - } - else { - schemaDir = DEFAULT_SCHEMA_DIR; - } - String release = System.getProperty("aai.release", "onap"); + } else { + schemaDir = DEFAULT_SCHEMA_DIR; + } + String release = System.getProperty("aai.release", "onap"); while (versionIterator.hasNext()) { System.setProperty(AAI_GENERATE_VERSION, versionIterator.next().toString()); - String yamlFile = schemaDir + "/src/main/resources/" + release + "/aai_swagger_yaml/aai_swagger_" + System.getProperty(AAI_GENERATE_VERSION)+ ".yaml"; + String yamlFile = + schemaDir + "/src/main/resources/" + release + "/aai_swagger_yaml/aai_swagger_" + + System.getProperty(AAI_GENERATE_VERSION) + ".yaml"; File swaggerYamlFile = new File(yamlFile); - if(swaggerYamlFile.exists()) { + if (swaggerYamlFile.exists()) { GenerateSwagger.schemaVersions = schemaVersions; GenerateSwagger.main(args); } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/GenerateXsd.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/GenerateXsd.java index 9d3f258..490e290 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/GenerateXsd.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/GenerateXsd.java @@ -8,7 +8,7 @@ * 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, @@ -17,126 +17,124 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemagen; - -import java.nio.charset.StandardCharsets; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.schemagen.genxsd.HTMLfromOXM; -import org.onap.aai.schemagen.genxsd.NodesYAMLfromOXM; -import org.onap.aai.schemagen.genxsd.YAMLfromOXM; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.w3c.dom.NodeList; +package org.onap.aai.schemagen; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; +import org.onap.aai.schemagen.genxsd.HTMLfromOXM; +import org.onap.aai.schemagen.genxsd.NodesYAMLfromOXM; +import org.onap.aai.schemagen.genxsd.YAMLfromOXM; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.w3c.dom.NodeList; + public class GenerateXsd { - private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); - protected static String apiVersion = null; - public static AnnotationConfigApplicationContext ctx = null; - static String apiVersionFmt = null; - static boolean useAnnotationsInXsd = false; - static String responsesUrl = null; - static String responsesLabel = null; - static String jsonEdges = null; - static Map generatedJavaType; - static Map appliedPaths; - static String RELEASE = System.getProperty("aai.release", "onap"); - - - static NodeList javaTypeNodes; - static Map javaTypeDefinitions = createJavaTypeDefinitions(); - private static Map createJavaTypeDefinitions() - { + private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); + protected static String apiVersion = null; + public static AnnotationConfigApplicationContext ctx = null; + static String apiVersionFmt = null; + static boolean useAnnotationsInXsd = false; + static String responsesUrl = null; + static String responsesLabel = null; + static String jsonEdges = null; + static Map generatedJavaType; + static Map appliedPaths; + static String RELEASE = System.getProperty("aai.release", "onap"); + + static NodeList javaTypeNodes; + static Map javaTypeDefinitions = createJavaTypeDefinitions(); + + private static Map createJavaTypeDefinitions() { StringBuilder aaiInternal = new StringBuilder(); - Map javaTypeDefinitions = new HashMap(); - aaiInternal.append(" aai-internal:\n"); - aaiInternal.append(" properties:\n"); - aaiInternal.append(" property-name:\n"); - aaiInternal.append(" type: string\n"); - aaiInternal.append(" property-value:\n"); - aaiInternal.append(" type: string\n"); -// javaTypeDefinitions.put("aai-internal", aaiInternal.toString()); - return javaTypeDefinitions; + Map javaTypeDefinitions = new HashMap(); + aaiInternal.append(" aai-internal:\n"); + aaiInternal.append(" properties:\n"); + aaiInternal.append(" property-name:\n"); + aaiInternal.append(" type: string\n"); + aaiInternal.append(" property-value:\n"); + aaiInternal.append(" type: string\n"); + // javaTypeDefinitions.put("aai-internal", aaiInternal.toString()); + return javaTypeDefinitions; } - public static final int VALUE_NONE = 0; - public static final int VALUE_DESCRIPTION = 1; - public static final int VALUE_INDEXED_PROPS = 2; - public static final int VALUE_CONTAINER = 3; - - private static final String GENERATE_TYPE_XSD = "xsd"; - private static final String GENERATE_TYPE_YAML = "yaml"; + 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 final static String NODE_DIR = System.getProperty("nodes.configuration.location"); - private final static String EDGE_DIR = System.getProperty("edges.configuration.location"); - private static final String BASE_ROOT = "aai-schema/"; - private static final String BASE_AUTO_GEN_ROOT = "aai-schema/"; + private static final String GENERATE_TYPE_XSD = "xsd"; + private static final String GENERATE_TYPE_YAML = "yaml"; - private static final String ROOT = BASE_ROOT + "src/main/resources"; - private static final String AUTO_GEN_ROOT = BASE_AUTO_GEN_ROOT + "src/main/resources"; + private final static String NODE_DIR = System.getProperty("nodes.configuration.location"); + private final static String EDGE_DIR = System.getProperty("edges.configuration.location"); + private static final String BASE_ROOT = "aai-schema/"; + private static final String BASE_AUTO_GEN_ROOT = "aai-schema/"; - private static final String NORMAL_START_DIR = "aai-schema-gen"; - private static final String XSD_DIR = ROOT + "/" + RELEASE +"/aai_schema"; + private static final String ROOT = BASE_ROOT + "src/main/resources"; + private static final String AUTO_GEN_ROOT = BASE_AUTO_GEN_ROOT + "src/main/resources"; - private static final String - YAML_DIR = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains( - NORMAL_START_DIR))) ? - AUTO_GEN_ROOT : - ROOT) + "/" + RELEASE + "/aai_swagger_yaml"; + private static final String NORMAL_START_DIR = "aai-schema-gen"; + private static final String XSD_DIR = ROOT + "/" + RELEASE + "/aai_schema"; - /* These three strings are for yaml auto-generation from aai-common class*/ + private static final String YAML_DIR = (((System.getProperty("user.dir") != null) + && (!System.getProperty("user.dir").contains(NORMAL_START_DIR))) ? AUTO_GEN_ROOT : ROOT) + + "/" + RELEASE + "/aai_swagger_yaml"; - private static final int SWAGGER_SUPPORT_STARTS_VERSION = 1; // minimum version to support swagger documentation + /* These three strings are for yaml auto-generation from aai-common class */ + private static final int SWAGGER_SUPPORT_STARTS_VERSION = 1; // minimum version to support + // swagger documentation - private static boolean validVersion(String versionToGen) { + private static boolean validVersion(String versionToGen) { - if ("ALL".equalsIgnoreCase(versionToGen)) { - return true; - } + if ("ALL".equalsIgnoreCase(versionToGen)) { + return true; + } - SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class); - if (schemaVersions == null) { - return false; + SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class); + if (schemaVersions == null) { + return false; + } + for (SchemaVersion v : schemaVersions.getVersions()) { + if (v.toString().equals(versionToGen)) { + return true; + } } - for (SchemaVersion v : schemaVersions.getVersions()) { - if (v.toString().equals(versionToGen)) { - return true; - } - } - return false; - } + return false; + } - private static boolean versionSupportsSwagger(String version) { + private static boolean versionSupportsSwagger(String version) { return Integer.parseInt(version.substring(1)) >= SWAGGER_SUPPORT_STARTS_VERSION; } - public static String getAPIVersion() { - return apiVersion; - } + public static String getAPIVersion() { + return apiVersion; + } + + public static String getYamlDir() { + return YAML_DIR; + } - public static String getYamlDir() { - return YAML_DIR; - } + public static String getResponsesUrl() { + return responsesUrl; + } - public static String getResponsesUrl() { - return responsesUrl; - } - public static void main(String[] args) throws IOException { - String versionToGen = System.getProperty("gen_version"); + public static void main(String[] args) throws IOException { + String versionToGen = System.getProperty("gen_version"); if (versionToGen == null) { System.err.println("Version is required, ie v or ALL."); System.exit(1); @@ -151,176 +149,172 @@ public class GenerateXsd { fileTypeToGen = fileTypeToGen.toLowerCase(); } - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( - "org.onap.aai.setup", - "org.onap.aai.schemagen" - ); + AnnotationConfigApplicationContext ctx = + new AnnotationConfigApplicationContext("org.onap.aai.setup", "org.onap.aai.schemagen"); - SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class); + SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class); - if ( !fileTypeToGen.equals(GENERATE_TYPE_XSD) && !fileTypeToGen.equals(GENERATE_TYPE_YAML)) { - System.err.println("Invalid gen_type passed. " + fileTypeToGen); - System.exit(1); - } + if (!fileTypeToGen.equals(GENERATE_TYPE_XSD) && !fileTypeToGen.equals(GENERATE_TYPE_YAML)) { + System.err.println("Invalid gen_type passed. " + fileTypeToGen); + System.exit(1); + } - String responsesLabel = System.getProperty("yamlresponses_url"); - responsesUrl = responsesLabel; + String responsesLabel = System.getProperty("yamlresponses_url"); + responsesUrl = responsesLabel; - List versionsToGen = new ArrayList<>(); - if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) { - System.err.println("Invalid version passed. " + versionToGen); - System.exit(1); - } - else if ("ALL".equalsIgnoreCase(versionToGen)) { - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - } else { - versionsToGen.add(new SchemaVersion(versionToGen)); - } - - //process file type System property - if ( fileTypeToGen.equals(GENERATE_TYPE_YAML) ) { - if ( responsesUrl == null || responsesUrl.length() < 1 - || responsesLabel == null || responsesLabel.length() < 1 ) { - System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" ); - System.exit(1); - } else { - responsesUrl = "description: "+ "Response codes found in [response codes]("+responsesLabel+ ").\n"; - } - } - /* - * TODO: Oxm Path is config driveb - */ - String oxmPath; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains( - NORMAL_START_DIR)) { - oxmPath = BASE_AUTO_GEN_ROOT + NODE_DIR; - } - else { - oxmPath = BASE_ROOT + NODE_DIR; - } + List versionsToGen = new ArrayList<>(); + if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") + && !validVersion(versionToGen)) { + System.err.println("Invalid version passed. " + versionToGen); + System.exit(1); + } else if ("ALL".equalsIgnoreCase(versionToGen)) { + versionsToGen = schemaVersions.getVersions(); + Collections.sort(versionsToGen); + Collections.reverse(versionsToGen); + } else { + versionsToGen.add(new SchemaVersion(versionToGen)); + } - String outfileName = null; - File outfile; - String nodesfileName = null; - File nodesfile; - String fileContent = null; - String nodesContent = null; - - - for (SchemaVersion v : versionsToGen) { - apiVersion = v.toString(); - logger.debug("YAMLdir = "+ YAML_DIR); - logger.debug("Generating " + apiVersion + " " + fileTypeToGen); - apiVersionFmt = "." + apiVersion + "."; - generatedJavaType = new HashMap(); - appliedPaths = new HashMap(); - File edgeRuleFile = null; - String fileName = EDGE_DIR + "DbEdgeRules_" + apiVersion + ".json"; - logger.debug("user.dir = "+System.getProperty("user.dir")); - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains( - NORMAL_START_DIR)) { - fileName = BASE_AUTO_GEN_ROOT + fileName; - - } - else { - fileName = BASE_ROOT + fileName; - - } - edgeRuleFile = new File( fileName); -// Document doc = ni.getSchema(translateVersion(v)); - - if ( fileTypeToGen.equals(GENERATE_TYPE_XSD) ) { - outfileName = XSD_DIR + "/aai_schema_" + apiVersion + "." + GENERATE_TYPE_XSD; - try { - HTMLfromOXM swagger = ctx.getBean(HTMLfromOXM.class); - swagger.setVersion(v); - fileContent = swagger.process(); - if ( fileContent.startsWith("Schema format issue")) { - throw new Exception(fileContent); - } - } catch(Exception e) { - logger.error( "Exception creating output file " + outfileName); - logger.error( e.getMessage()); - System.exit(-1); + // process file type System property + if (fileTypeToGen.equals(GENERATE_TYPE_YAML)) { + if (responsesUrl == null || responsesUrl.length() < 1 || responsesLabel == null + || responsesLabel.length() < 1) { + System.err.println( + "generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties"); + System.exit(1); + } else { + responsesUrl = "description: " + "Response codes found in [response codes](" + + responsesLabel + ").\n"; + } } - } else if ( versionSupportsSwagger(apiVersion )) { - outfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + GENERATE_TYPE_YAML; - nodesfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + "nodes"+"."+ - GENERATE_TYPE_YAML; - try { - YAMLfromOXM swagger = (YAMLfromOXM) ctx.getBean(YAMLfromOXM.class); - swagger.setVersion(v); - fileContent = swagger.process(); - Map combinedJavaTypes = swagger.getCombinedJavaTypes(); - NodesYAMLfromOXM nodesSwagger = ctx.getBean(NodesYAMLfromOXM.class); - nodesSwagger.setVersion(v); - nodesSwagger.setCombinedJavaTypes(combinedJavaTypes); - nodesContent = nodesSwagger.process(); - } catch(Exception e) { - logger.error("Exception creating output file " + outfileName, e); + /* + * TODO: Oxm Path is config driveb + */ + String oxmPath; + if (System.getProperty("user.dir") != null + && !System.getProperty("user.dir").contains(NORMAL_START_DIR)) { + oxmPath = BASE_AUTO_GEN_ROOT + NODE_DIR; + } else { + oxmPath = BASE_ROOT + NODE_DIR; } - } else { - continue; - } - outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(!parentDir.exists()) { + + String outfileName = null; + File outfile; + String nodesfileName = null; + File nodesfile; + String fileContent = null; + String nodesContent = null; + + for (SchemaVersion v : versionsToGen) { + apiVersion = v.toString(); + logger.debug("YAMLdir = " + YAML_DIR); + logger.debug("Generating " + apiVersion + " " + fileTypeToGen); + apiVersionFmt = "." + apiVersion + "."; + generatedJavaType = new HashMap(); + appliedPaths = new HashMap(); + File edgeRuleFile = null; + String fileName = EDGE_DIR + "DbEdgeRules_" + apiVersion + ".json"; + logger.debug("user.dir = " + System.getProperty("user.dir")); + if (System.getProperty("user.dir") != null + && !System.getProperty("user.dir").contains(NORMAL_START_DIR)) { + fileName = BASE_AUTO_GEN_ROOT + fileName; + + } else { + fileName = BASE_ROOT + fileName; + + } + edgeRuleFile = new File(fileName); + // Document doc = ni.getSchema(translateVersion(v)); + + if (fileTypeToGen.equals(GENERATE_TYPE_XSD)) { + outfileName = XSD_DIR + "/aai_schema_" + apiVersion + "." + GENERATE_TYPE_XSD; + try { + HTMLfromOXM swagger = ctx.getBean(HTMLfromOXM.class); + swagger.setVersion(v); + fileContent = swagger.process(); + if (fileContent.startsWith("Schema format issue")) { + throw new Exception(fileContent); + } + } catch (Exception e) { + logger.error("Exception creating output file " + outfileName); + logger.error(e.getMessage()); + System.exit(-1); + } + } else if (versionSupportsSwagger(apiVersion)) { + outfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + GENERATE_TYPE_YAML; + nodesfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + "nodes" + "." + + GENERATE_TYPE_YAML; + try { + YAMLfromOXM swagger = (YAMLfromOXM) ctx.getBean(YAMLfromOXM.class); + swagger.setVersion(v); + fileContent = swagger.process(); + Map combinedJavaTypes = swagger.getCombinedJavaTypes(); + NodesYAMLfromOXM nodesSwagger = ctx.getBean(NodesYAMLfromOXM.class); + nodesSwagger.setVersion(v); + nodesSwagger.setCombinedJavaTypes(combinedJavaTypes); + nodesContent = nodesSwagger.process(); + } catch (Exception e) { + logger.error("Exception creating output file " + outfileName, e); + } + } else { + continue; + } + outfile = new File(outfileName); + File parentDir = outfile.getParentFile(); + if (!parentDir.exists()) { parentDir.mkdirs(); } - if(nodesfileName != null) { - BufferedWriter nodesBW = null; - nodesfile = new File(nodesfileName); - parentDir = nodesfile.getParentFile(); - if(!parentDir.exists()){ + if (nodesfileName != null) { + BufferedWriter nodesBW = null; + nodesfile = new File(nodesfileName); + parentDir = nodesfile.getParentFile(); + if (!parentDir.exists()) { parentDir.mkdirs(); } - try { - if(!nodesfile.createNewFile()) { - logger.error( "File {} already exist", nodesfileName); + try { + if (!nodesfile.createNewFile()) { + logger.error("File {} already exist", nodesfileName); } - } catch (IOException e) { - logger.error( "Exception creating output file " + nodesfileName, e); - } - try { - Charset charset = StandardCharsets.UTF_8; - Path path = Paths.get(nodesfileName); - nodesBW = Files.newBufferedWriter(path, charset); - nodesBW.write(nodesContent); - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName, e); - } finally { - if ( nodesBW != null ) { - nodesBW.close(); - } + } catch (IOException e) { + logger.error("Exception creating output file " + nodesfileName, e); + } + try { + Charset charset = StandardCharsets.UTF_8; + Path path = Paths.get(nodesfileName); + nodesBW = Files.newBufferedWriter(path, charset); + nodesBW.write(nodesContent); + } catch (IOException e) { + logger.error("Exception writing output file " + outfileName, e); + } finally { + if (nodesBW != null) { + nodesBW.close(); + } + } } - } - try { - if(!outfile.createNewFile()) { - logger.error( "File {} already exist", outfileName); + try { + if (!outfile.createNewFile()) { + logger.error("File {} already exist", outfileName); } - } catch (IOException e) { - logger.error( "Exception creating output file " + outfileName, e); - } - BufferedWriter bw = null; - try { - Charset charset = StandardCharsets.UTF_8; - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(fileContent); - } catch ( IOException e) { - logger.error( "Exception writing output file " + outfileName, e); - } finally { - if ( bw != null ) { - bw.close(); + } catch (IOException e) { + logger.error("Exception creating output file " + outfileName, e); } - } - logger.debug( "GeneratedXSD successful, saved in " + outfileName); - } + BufferedWriter bw = null; + try { + Charset charset = StandardCharsets.UTF_8; + Path path = Paths.get(outfileName); + bw = Files.newBufferedWriter(path, charset); + bw.write(fileContent); + } catch (IOException e) { + logger.error("Exception writing output file " + outfileName, e); + } finally { + if (bw != null) { + bw.close(); + } + } + logger.debug("GeneratedXSD successful, saved in " + outfileName); + } - } + } } - diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SchemaConfiguration.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SchemaConfiguration.java index 26ff4b6..4657862 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SchemaConfiguration.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SchemaConfiguration.java @@ -10,7 +10,7 @@ * 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, @@ -19,6 +19,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen; import org.onap.aai.edges.EdgeIngestor; @@ -34,8 +35,10 @@ import org.springframework.context.annotation.Configuration; public class SchemaConfiguration { @Bean - public EdgeIngestor edgeIngestor(SchemaLocationsBean schemaLocationsBean, SchemaVersions schemaVersions){ - return new EdgeIngestor(configTranslator(schemaLocationsBean, schemaVersions), schemaVersions); + public EdgeIngestor edgeIngestor(SchemaLocationsBean schemaLocationsBean, + SchemaVersions schemaVersions) { + return new EdgeIngestor(configTranslator(schemaLocationsBean, schemaVersions), + schemaVersions); } @Bean(name = "nodeIngestor") @@ -44,7 +47,8 @@ public class SchemaConfiguration { } @Bean(name = "configTranslator") - public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean, SchemaVersions schemaVersions) { + public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean, + SchemaVersions schemaVersions) { return new AAIConfigTranslator(schemaLocationsBean, schemaVersions); } } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SpringContextAware.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SpringContextAware.java index d91cf81..4bdc05b 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SpringContextAware.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SpringContextAware.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemagen; +package org.onap.aai.schemagen; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; @@ -31,31 +31,30 @@ public class SpringContextAware implements ApplicationContextAware { private static ApplicationContext context = null; public static ApplicationContext getApplicationContext() { - return context; + return context; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - context = applicationContext; + context = applicationContext; } - - public static T getBean(String beanName, Class requiredType) { - if(context != null){ - return context.getBean(beanName, requiredType); - } + public static T getBean(String beanName, Class requiredType) { + if (context != null) { + return context.getBean(beanName, requiredType); + } return null; - } + } - public static T getBean(Class clazz){ - if(context != null){ + public static T getBean(Class clazz) { + if (context != null) { return context.getBean(clazz); } return null; } - public static Object getBean(String bean){ - if(context != null){ + public static Object getBean(String bean) { + if (context != null) { return context.getBean(bean); } return null; diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SwaggerGenerationConfiguration.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SwaggerGenerationConfiguration.java index e479328..0370e8b 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SwaggerGenerationConfiguration.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/SwaggerGenerationConfiguration.java @@ -10,7 +10,7 @@ * 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, @@ -19,15 +19,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemagen; +package org.onap.aai.schemagen; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.setup.SchemaVersions; import org.onap.aai.schemagen.genxsd.HTMLfromOXM; import org.onap.aai.schemagen.genxsd.NodesYAMLfromOXM; import org.onap.aai.schemagen.genxsd.YAMLfromOXM; +import org.onap.aai.setup.SchemaVersions; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; @@ -45,19 +45,22 @@ public class SwaggerGenerationConfiguration { @Bean @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public NodesYAMLfromOXM nodesYamlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { + public NodesYAMLfromOXM nodesYamlFromOXM(SchemaVersions schemaVersions, + NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { return new NodesYAMLfromOXM(basePath, schemaVersions, nodeIngestor, edgeIngestor); } @Bean @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public HTMLfromOXM htmlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { + public HTMLfromOXM htmlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, + EdgeIngestor edgeIngestor) { return new HTMLfromOXM(maxOccurs, schemaVersions, nodeIngestor, edgeIngestor); } @Bean @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public YAMLfromOXM yamlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, EdgeIngestor edgeIngestor) { + public YAMLfromOXM yamlFromOXM(SchemaVersions schemaVersions, NodeIngestor nodeIngestor, + EdgeIngestor edgeIngestor) { return new YAMLfromOXM(basePath, schemaVersions, nodeIngestor, edgeIngestor); } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/ConfigTranslatorForDocs.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/ConfigTranslatorForDocs.java index c4db6f9..87ba528 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/ConfigTranslatorForDocs.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/ConfigTranslatorForDocs.java @@ -8,7 +8,7 @@ * 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, @@ -20,62 +20,63 @@ package org.onap.aai.schemagen.genxsd; +import java.io.File; +import java.io.FilenameFilter; +import java.util.*; + import org.onap.aai.setup.ConfigTranslator; import org.onap.aai.setup.SchemaLocationsBean; import org.onap.aai.setup.SchemaVersion; import org.onap.aai.setup.SchemaVersions; -import java.io.File; -import java.io.FilenameFilter; -import java.util.*; - public class ConfigTranslatorForDocs extends ConfigTranslator { - public ConfigTranslatorForDocs(SchemaLocationsBean bean, SchemaVersions schemaVersions) { - super(bean, schemaVersions); - } + public ConfigTranslatorForDocs(SchemaLocationsBean bean, SchemaVersions schemaVersions) { + super(bean, schemaVersions); + } - @Override - public Map> getNodeFiles() { - List versionsToGen = new ArrayList<>(); - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - Map> mp = new TreeMap<>(); - for (SchemaVersion v : versionsToGen) { - File dir = new File(bean.getNodeDirectory() + File.separator + v.toString().toLowerCase()); - File [] fileSet = dir.listFiles(); - List files = new ArrayList<>(); - for(File f: fileSet ) { - files.add(f.getAbsolutePath()); - } + @Override + public Map> getNodeFiles() { + List versionsToGen = new ArrayList<>(); + versionsToGen = schemaVersions.getVersions(); + Collections.sort(versionsToGen); + Collections.reverse(versionsToGen); + Map> mp = new TreeMap<>(); + for (SchemaVersion v : versionsToGen) { + File dir = + new File(bean.getNodeDirectory() + File.separator + v.toString().toLowerCase()); + File[] fileSet = dir.listFiles(); + List files = new ArrayList<>(); + for (File f : fileSet) { + files.add(f.getAbsolutePath()); + } - mp.put(v, files); + mp.put(v, files); + } + return mp; } - return mp; - } - @Override - public Map> getEdgeFiles() { - List versionsToGen = new ArrayList<>(); - versionsToGen = schemaVersions.getVersions(); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - Map> mp = new TreeMap<>(); - for (SchemaVersion v : versionsToGen) { - File dir = new File(bean.getEdgeDirectory()); - File [] fileSet = dir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.contains("_"+v.toString().toLowerCase()); + @Override + public Map> getEdgeFiles() { + List versionsToGen = new ArrayList<>(); + versionsToGen = schemaVersions.getVersions(); + Collections.sort(versionsToGen); + Collections.reverse(versionsToGen); + Map> mp = new TreeMap<>(); + for (SchemaVersion v : versionsToGen) { + File dir = new File(bean.getEdgeDirectory()); + File[] fileSet = dir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.contains("_" + v.toString().toLowerCase()); + } + }); + List files = new ArrayList<>(); + for (File f : fileSet) { + files.add(f.getAbsolutePath()); + } + mp.put(v, files); } - }); - List files = new ArrayList<>(); - for(File f: fileSet ) { - files.add(f.getAbsolutePath()); - } - mp.put(v, files); + return mp; } - return mp; - } } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSet.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSet.java index a570d6f..969bdf9 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSet.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSet.java @@ -8,7 +8,7 @@ * 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, @@ -17,41 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; import java.util.Set; import java.util.TreeSet; public class DeleteFootnoteSet { - protected Set footnotes = new TreeSet<>(); - protected String targetNode = ""; - public DeleteFootnoteSet(String targetNode) { - super(); - this.targetNode = targetNode == null ? "" : targetNode; - } + protected Set footnotes = new TreeSet<>(); + protected String targetNode = ""; + + public DeleteFootnoteSet(String targetNode) { + super(); + this.targetNode = targetNode == null ? "" : targetNode; + } - public void add(String s ) { - String fullnote=null; - if("(1)".equals(s)) { - fullnote = s+" IF this "+targetNode.toUpperCase()+" node is deleted, this FROM node is DELETED also"; - } else if("(2)".equals(s)) { - fullnote = s+" IF this "+targetNode.toUpperCase()+" node is deleted, this TO node is DELETED also"; - } else if("(3)".equals(s)) { - fullnote = s+" IF this FROM node is deleted, this "+targetNode.toUpperCase()+" is DELETED also"; - } else if("(4)".equals(s)) { - fullnote = s+" IF this TO node is deleted, this "+targetNode.toUpperCase()+" is DELETED also"; - } else if(s.contains(targetNode.toUpperCase())) { - fullnote = s; - } else { - return; + 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); } - 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(); - } + 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-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteOperation.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteOperation.java index c59e8f0..8c7ecce 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteOperation.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/DeleteOperation.java @@ -22,6 +22,7 @@ package org.onap.aai.schemagen.genxsd; import java.util.HashMap; import java.util.StringTokenizer; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.schemagen.GenerateXsd; @@ -35,7 +36,7 @@ public class DeleteOperation { public static HashMap deletePaths = new HashMap(); public DeleteOperation(String useOpId, String xmlRootElementName, String tag, String path, - String pathParams) { + String pathParams) { super(); this.useOpId = useOpId; this.xmlRootElementName = xmlRootElementName; @@ -48,7 +49,7 @@ public class DeleteOperation { public String toString() { StringTokenizer st; st = new StringTokenizer(path, "/"); - //a valid tag is necessary + // a valid tag is necessary if (StringUtils.isEmpty(tag)) { return ""; } @@ -61,9 +62,9 @@ public class DeleteOperation { 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 + // 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 ""; @@ -72,8 +73,7 @@ public class DeleteOperation { pathSb.append(" delete:\n"); pathSb.append(" tags:\n"); pathSb.append(" - ").append(tag).append("\n"); - pathSb.append(" summary: delete an existing ").append(xmlRootElementName) - .append("\n"); + pathSb.append(" summary: delete an existing ").append(xmlRootElementName).append("\n"); pathSb.append(" description: delete an existing ").append(xmlRootElementName) .append("\n"); diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/EdgeDescription.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/EdgeDescription.java index 5bdb87e..585e14e 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/EdgeDescription.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/EdgeDescription.java @@ -40,17 +40,17 @@ public class EdgeDescription { public EdgeDescription(EdgeRule ed) { super(); - if (ed.getDirection().toString().equals(ed.getContains()) && - AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { + if (ed.getDirection().toString().equals(ed.getContains()) + && AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { this.lineageType = LineageType.PARENT; - } else if (AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) && - ed.getDirection().toString().equals(ed.getContains())) { + } else if (AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) + && ed.getDirection().toString().equals(ed.getContains())) { this.lineageType = LineageType.CHILD; - } else if (AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getContains())) && - AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getDirection()))) { + } else if (AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getContains())) + && AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getDirection()))) { this.lineageType = LineageType.PARENT; - } else if (AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) && - AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { + } else if (AAIDirection.getValue("IN").equals(AAIDirection.getValue(ed.getContains())) + && AAIDirection.getValue("OUT").equals(AAIDirection.getValue(ed.getDirection()))) { this.lineageType = LineageType.PARENT; } else { this.lineageType = LineageType.UNRELATED; @@ -153,21 +153,18 @@ public class EdgeDescription { } } if (result.length() == 0) { - result = String - .join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo() + ",", - this.getMultiplicity()); + result = String.join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo() + ",", + this.getMultiplicity()); } } else { if (LineageType.PARENT == lineageType) { result = " (PARENT of " + otherNodeName; - result = String - .join(" ", result + ",", ed.getFrom(), this.getShortLabel(), ed.getTo() + ",", - this.getMultiplicity()); + result = String.join(" ", result + ",", ed.getFrom(), this.getShortLabel(), + ed.getTo() + ",", this.getMultiplicity()); } if (result.length() == 0) { - result = String - .join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo() + ",", - this.getMultiplicity()); + result = String.join(" ", "(", ed.getFrom(), this.getShortLabel(), ed.getTo() + ",", + this.getMultiplicity()); } } @@ -187,8 +184,8 @@ public class EdgeDescription { */ public boolean hasDelTarget() { - return StringUtils.isNotEmpty(ed.getDeleteOtherV()) && - (!"NONE".equalsIgnoreCase(ed.getDeleteOtherV())); + return StringUtils.isNotEmpty(ed.getDeleteOtherV()) + && (!"NONE".equalsIgnoreCase(ed.getDeleteOtherV())); } /** diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/GetOperation.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/GetOperation.java index f9d1799..6228f86 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/GetOperation.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/GetOperation.java @@ -24,6 +24,7 @@ import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.schemagen.GenerateXsd; @@ -31,8 +32,7 @@ public class GetOperation { static Map> containers = new HashMap>(); public static void addContainerProps(String container, Vector containerProps) { - containers.put(container, containerProps); - ; + containers.put(container, containerProps);; } private String useOpId; @@ -43,23 +43,23 @@ public class GetOperation { private String queryParams; public GetOperation(String useOpId, String xmlRootElementName, String tag, String path, - String pathParams) { + String pathParams) { super(); this.useOpId = useOpId; this.xmlRootElementName = xmlRootElementName; this.tag = tag; this.path = path; this.pathParams = pathParams; -// StringBuilder p = new StringBuilder(); + // 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(); + // for(String param : containers.get(xmlRootElementName)) { + // p.append(param); + // } + // this.queryParams = p.toString(); } } @@ -67,13 +67,13 @@ public class GetOperation { 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 + // Path has to be longer than one element + /* + * if ( st.countTokens() <= 1) { + * return ""; + * } + */ + // a valid tag is necessary if (StringUtils.isEmpty(tag)) { return ""; } @@ -116,9 +116,9 @@ public class GetOperation { if (StringUtils.isNotEmpty(pathParams)) { pathSb.append(pathParams); } -// if ( StringUtils.isNotEmpty(pathParams) && StringUtils.isNotEmpty(queryParams)) { -// pathSb.append("\n"); -// } + // if ( StringUtils.isNotEmpty(pathParams) && StringUtils.isNotEmpty(queryParams)) { + // pathSb.append("\n"); + // } if (StringUtils.isNotEmpty(queryParams)) { pathSb.append(queryParams); } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/HTMLfromOXM.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/HTMLfromOXM.java index 01598a0..980a3f3 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/HTMLfromOXM.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/HTMLfromOXM.java @@ -26,7 +26,9 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; + import javax.xml.parsers.ParserConfigurationException; + import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; import org.onap.aai.nodes.NodeIngestor; @@ -47,7 +49,7 @@ public class HTMLfromOXM extends OxmFileProcessor { private String maxOccurs; public HTMLfromOXM(String maxOccurs, SchemaVersions schemaVersions, NodeIngestor ni, - EdgeIngestor ei) { + EdgeIngestor ei) { super(schemaVersions, ni, ei); this.maxOccurs = maxOccurs; } @@ -67,7 +69,6 @@ public class HTMLfromOXM extends OxmFileProcessor { this.v = v; } - @Override public String getDocumentHeader() { StringBuilder sb = new StringBuilder(); @@ -86,15 +87,13 @@ public class HTMLfromOXM extends OxmFileProcessor { .append(LINE_SEPARATOR).append("xmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\"") .append(LINE_SEPARATOR).append(" jaxb:version=\"2.1\"").append(LINE_SEPARATOR) .append(" xmlns:annox=\"http://annox.dev.java.net\"").append(LINE_SEPARATOR) - .append(" jaxb:extensionBindingPrefixes=\"annox\">") - .append(DOUBLE_LINE_SEPARATOR); + .append(" jaxb:extensionBindingPrefixes=\"annox\">").append(DOUBLE_LINE_SEPARATOR); return sb.toString(); } @Override - public String process() - throws ParserConfigurationException, SAXException, IOException, FileNotFoundException, - EdgeRuleNotFoundException { + public String process() throws ParserConfigurationException, SAXException, IOException, + FileNotFoundException, EdgeRuleNotFoundException { StringBuilder sb = new StringBuilder(); try { @@ -119,7 +118,7 @@ public class HTMLfromOXM extends OxmFileProcessor { elem = getJavaTypeElement(javaTypeName, false); } XSDElement javaTypeElement = new XSDElement(elem, maxOccurs); - //javaTypeName = javaTypeElement.name(); + // javaTypeName = javaTypeElement.name(); if (javaTypeName == null) { String msg = "Invalid OXM file: has no name attribute in " + oxmFile; logger.error(msg); @@ -129,8 +128,8 @@ public class HTMLfromOXM extends OxmFileProcessor { logger.debug("skipping Nodes entry (temporary feature)"); continue; } - logger.debug(getXmlRootElementName(javaTypeName) + " vs " + javaTypeName + ":" + - generatedJavaType.containsKey(getXmlRootElementName(javaTypeName))); + logger.debug(getXmlRootElementName(javaTypeName) + " vs " + javaTypeName + ":" + + generatedJavaType.containsKey(getXmlRootElementName(javaTypeName))); if (!"Inventory".equals(javaTypeName)) { generatedJavaType.put(javaTypeName, null); @@ -154,15 +153,14 @@ public class HTMLfromOXM extends OxmFileProcessor { } protected boolean skipCheck(String javaAttribute) { - if (javaAttribute.equals("model") - || javaAttribute.equals("eventHeader")) { + if (javaAttribute.equals("model") || javaAttribute.equals("eventHeader")) { return true; } return false; } public String processJavaTypeElement(String javaTypeName, Element javaType_Element, - StringBuilder sbInventory) { + StringBuilder sbInventory) { String xmlRootElementName = getXMLRootElementName(javaType_Element); NodeList parentNodes = javaType_Element.getElementsByTagName("java-attributes"); @@ -203,13 +201,14 @@ public class HTMLfromOXM extends OxmFileProcessor { XSDElement xmlElementElement = new XSDElement((Element) xmlElementNodes.item(i), maxOccurs); -// String elementName = xmlElementElement.getAttribute("name"); + // String elementName = xmlElementElement.getAttribute("name"); String elementType = xmlElementElement.getAttribute("type"); - //No simple types; only AAI custom types - String addType = elementType.contains("." + v.toString() + ".") ? - elementType.substring(elementType.lastIndexOf('.') + 1) : null; - if (elementType.contains("." + v.toString() + ".") && - !generatedJavaType.containsKey(addType)) { + // No simple types; only AAI custom types + String addType = elementType.contains("." + v.toString() + ".") + ? elementType.substring(elementType.lastIndexOf('.') + 1) + : null; + if (elementType.contains("." + v.toString() + ".") + && !generatedJavaType.containsKey(addType)) { generatedJavaType.put(addType, elementType); javatypeElement = getJavaTypeElement(addType, processingInventory); sb.append(processJavaTypeElement(addType, javatypeElement, null)); @@ -218,7 +217,7 @@ public class HTMLfromOXM extends OxmFileProcessor { logger.trace("Skipping nodes, temporary testing"); continue; } - //assembles the basic + // assembles the basic sb1.append(xmlElementElement.getHTMLElement(v, true, this)); } if (!processingInventory) { diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodeGetOperation.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodeGetOperation.java index bdfdfd6..24c34d9 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodeGetOperation.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodeGetOperation.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.schemagen.GenerateXsd; @@ -55,7 +56,7 @@ public class NodeGetOperation { private String queryParams; public NodeGetOperation(String useOpId, String xmlRootElementName, String tag, String path, - String pathParams) { + String pathParams) { super(); this.useOpId = useOpId; this.xmlRootElementName = xmlRootElementName; @@ -89,13 +90,13 @@ public class NodeGetOperation { public String toString() { StringTokenizer st; st = new StringTokenizer(CRUDpath, "/"); - //Path has to be longer than one element - /* - if ( st.countTokens() <= 1) { - return ""; - } - */ - //a valid tag is necessary + // Path has to be longer than one element + /* + * if ( st.countTokens() <= 1) { + * return ""; + * } + */ + // a valid tag is necessary if (StringUtils.isEmpty(tag)) { return ""; } diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXM.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXM.java index c42aaed..8bceb5c 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXM.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXM.java @@ -21,6 +21,7 @@ package org.onap.aai.schemagen.genxsd; import com.google.common.collect.Multimap; + import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; @@ -39,7 +40,9 @@ import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; + import javax.xml.parsers.ParserConfigurationException; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.EdgeRule; @@ -69,7 +72,7 @@ public class NodesYAMLfromOXM extends OxmFileProcessor { private final String basePath; public NodesYAMLfromOXM(String basePath, SchemaVersions schemaVersions, NodeIngestor ni, - EdgeIngestor ei) { + EdgeIngestor ei) { super(schemaVersions, ni, ei); this.basePath = basePath; } @@ -95,14 +98,18 @@ public class NodesYAMLfromOXM extends OxmFileProcessor { sb.append("\n\n [Differences versus the previous schema version](" + "apidocs") .append(basePath).append("/aai_swagger_").append(v.toString()).append(".diff)"); } - sb.append(DOUBLE_LINE_SEPARATOR).append( - " Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.") - .append(OxmFileProcessor.DOUBLE_LINE_SEPARATOR).append( - " Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.") - .append(DOUBLE_LINE_SEPARATOR).append( - " You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)") - .append(DOUBLE_LINE_SEPARATOR).append( - " Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.") + sb.append(DOUBLE_LINE_SEPARATOR) + .append( + " Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.") + .append(OxmFileProcessor.DOUBLE_LINE_SEPARATOR) + .append( + " Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.") + .append(DOUBLE_LINE_SEPARATOR) + .append( + " You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)") + .append(DOUBLE_LINE_SEPARATOR) + .append( + " Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.") .append(OxmFileProcessor.DOUBLE_LINE_SEPARATOR) .append(" This document is best viewed with Firefox or Chrome. "); sb.append( @@ -201,9 +208,8 @@ public class NodesYAMLfromOXM extends OxmFileProcessor { if (namespaceFilter != null && (!namespaceFilter.contains(entry.getKey()))) { continue; } - logger.debug( - "Key: " + entry.getKey() + "Test: " + - ("relationship-dict".equals(entry.getKey()) ? "true" : "false")); + logger.debug("Key: " + entry.getKey() + "Test: " + + ("relationship-dict".equals(entry.getKey()) ? "true" : "false")); if (entry.getKey().matches("relationship-dict")) { String jb = entry.getValue(); logger.debug("Value: " + jb); @@ -235,8 +241,7 @@ public class NodesYAMLfromOXM extends OxmFileProcessor { return dictSb.toString(); } - private String processJavaTypeElementSwagger( - String javaTypeName, Element javaTypeElement, + private String processJavaTypeElementSwagger(String javaTypeName, Element javaTypeElement, StringBuilder pathSb, StringBuilder definitionsSb, String path, String tag, String opId, String getItemName, StringBuilder pathParams, String validEdges) { @@ -650,18 +655,16 @@ public class NodesYAMLfromOXM extends OxmFileProcessor { private void writeYAMLfile(String outfileName, String fileContent) { outfileName = (StringUtils.isEmpty(outfileName)) ? "aai_swagger" : outfileName; - outfileName = (outfileName.lastIndexOf(File.separator) == -1) - ? YAML_DIR + File.separator + outfileName + "_" + v.toString() + "." + - GENERATE_TYPE_YAML - : outfileName; + outfileName = (outfileName.lastIndexOf(File.separator) == -1) ? YAML_DIR + File.separator + + outfileName + "_" + v.toString() + "." + GENERATE_TYPE_YAML : outfileName; File outfile = new File(outfileName); File parentDir = outfile.getParentFile(); if (parentDir != null && !parentDir.exists()) { parentDir.mkdirs(); } try { - if(!outfile.createNewFile()) { - logger.error( "File {} already exist", outfileName); + if (!outfile.createNewFile()) { + logger.error("File {} already exist", outfileName); } } catch (IOException e) { logger.error("Exception creating output file " + outfileName, e); diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/OxmFileProcessor.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/OxmFileProcessor.java index 224192a..fde0877 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/OxmFileProcessor.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/OxmFileProcessor.java @@ -24,6 +24,7 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; +import java.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -31,10 +32,12 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; + import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; + import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException; import org.onap.aai.nodes.NodeIngestor; @@ -49,16 +52,6 @@ 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.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.StringReader; -import java.util.*; - public abstract class OxmFileProcessor { public static final String LINE_SEPARATOR = System.getProperty("line.separator"); diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PatchOperation.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PatchOperation.java index b52e34b..652117d 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PatchOperation.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PatchOperation.java @@ -21,6 +21,7 @@ package org.onap.aai.schemagen.genxsd; import java.util.StringTokenizer; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.schemagen.GenerateXsd; import org.onap.aai.setup.SchemaVersion; @@ -36,7 +37,7 @@ public class PatchOperation { private String basePath; public PatchOperation(String useOpId, String xmlRootElementName, String tag, String path, - String pathParams, SchemaVersion v, String basePath) { + String pathParams, SchemaVersion v, String basePath) { super(); this.useOpId = useOpId; this.xmlRootElementName = xmlRootElementName; @@ -55,7 +56,7 @@ public class PatchOperation { public String toString() { StringTokenizer st; st = new StringTokenizer(path, "/"); - //a valid tag is necessary + // a valid tag is necessary if (StringUtils.isEmpty(tag)) { return ""; } @@ -68,7 +69,7 @@ public class PatchOperation { if (path.startsWith("/search")) { return ""; } - //No Patch operation paths end with "relationship" + // No Patch operation paths end with "relationship" if (path.endsWith("/relationship")) { return ""; @@ -95,8 +96,7 @@ public class PatchOperation { pathSb.append(" summary: update an existing ").append(xmlRootElementName) .append("\n"); pathSb.append(" description: |\n"); - pathSb.append(" Update an existing ").append(xmlRootElementName) - .append("\n"); + pathSb.append(" Update an existing ").append(xmlRootElementName).append("\n"); pathSb.append(" #\n"); pathSb.append( " Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); @@ -126,8 +126,8 @@ public class PatchOperation { pathSb.append(" - name: body\n"); pathSb.append(" in: body\n"); pathSb.append(" description: ").append(xmlRootElementName) - .append(" object that needs to be updated.") - .append(relationshipExamplesSb.toString()).append("\n"); + .append(" object that needs to be updated.").append(relationshipExamplesSb.toString()) + .append("\n"); pathSb.append(" required: true\n"); pathSb.append(" schema:\n"); pathSb.append(" $ref: \"#/definitions/").append(prefixForPatch) diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutOperation.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutOperation.java index d1e7ca5..a4c6a51 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutOperation.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutOperation.java @@ -37,7 +37,7 @@ public class PutOperation { private String basePath; public PutOperation(String useOpId, String xmlRootElementName, String tag, String path, - String pathParams, SchemaVersion v, String basePath) { + String pathParams, SchemaVersion v, String basePath) { super(); this.useOpId = useOpId; this.xmlRootElementName = xmlRootElementName; @@ -50,13 +50,13 @@ public class PutOperation { @Override public String toString() { - //a valid tag is necessary + // 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 + // 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 ""; } @@ -81,11 +81,11 @@ public class PutOperation { if (path.endsWith("/" + RELATIONSHIP)) { pathSb.append(" summary: see node definition for valid relationships\n"); } else { - pathSb.append(" summary: create or update an existing ") - .append(xmlRootElementName).append("\n"); + pathSb.append(" summary: create or update an existing ").append(xmlRootElementName) + .append("\n"); pathSb.append(" description: |\n Create or update an existing ") .append(xmlRootElementName).append( - ".\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"); + ".\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") .append(basePath).append("/relations/").append(version.toString()).append("/") diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutRelationPathSet.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutRelationPathSet.java index 43abb1e..fff28fc 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutRelationPathSet.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/PutRelationPathSet.java @@ -21,6 +21,7 @@ package org.onap.aai.schemagen.genxsd; import com.google.common.collect.Multimap; + import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; @@ -28,6 +29,7 @@ import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; + import org.apache.commons.text.similarity.LevenshteinDistance; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.EdgeRule; @@ -61,9 +63,8 @@ public class PutRelationPathSet { this.opId = opId; this.version = v; objectName = DeleteOperation.deletePaths.get(apiPath); - logger.debug( - "II-apiPath: " + apiPath + "\nPath: " + path + "\nopId=" + opId + "\nobjectName=" + - objectName); + logger.debug("II-apiPath: " + apiPath + "\nPath: " + path + "\nopId=" + opId + + "\nobjectName=" + objectName); } private void process(EdgeIngestor edgeIngestor) { @@ -140,15 +141,15 @@ public class PutRelationPathSet { } private void writeRelationsFile() { - File examplefilePath = new File( - GenerateXsd.getYamlDir() + "/relations/" + version.toString() + "/" + - opId.replace("RelationshipListRelationship", "") + ".json"); + File examplefilePath = + new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString() + "/" + + opId.replace("RelationshipListRelationship", "") + ".json"); logger.debug(String.join("exampleFilePath: ", examplefilePath.toString())); try { if (!examplefilePath.exists()) { examplefilePath.getParentFile().mkdirs(); - if(!examplefilePath.createNewFile()) { + if (!examplefilePath.createNewFile()) { logger.debug("examplefilePath create file error"); } } @@ -199,12 +200,14 @@ public class PutRelationPathSet { int targetMaxScore = 0; for (Map.Entry p : DeleteOperation.deletePaths.entrySet()) { if (p.getValue().equals(obj)) { - targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ? - proximity.apply(apiPath, p.getKey()) : targetScore; + 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; + 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); } @@ -238,4 +241,3 @@ public class PutRelationPathSet { } } - diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/XSDElement.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/XSDElement.java index bbdcd70..205d16c 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/XSDElement.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/genxsd/XSDElement.java @@ -21,10 +21,12 @@ package org.onap.aai.schemagen.genxsd; import com.google.common.base.Joiner; + import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; + import org.apache.commons.lang3.StringUtils; import org.onap.aai.setup.SchemaVersion; import org.w3c.dom.Attr; @@ -131,9 +133,9 @@ public class XSDElement implements Element { .equals(this.xmlElementElement.getAttribute("name"))) { continue; } -// This stopped working, replaced with above - should figure out why... -// if ( !xmlPropElement.getParentNode().isSameNode(this.xmlElementElement)) -// 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) { @@ -158,7 +160,7 @@ public class XSDElement implements Element { } } if (pathDescriptionProperty != null) { - //suppress non-printable characters in a description + // suppress non-printable characters in a description String replaceDescription = pathDescriptionProperty.replaceAll("[^\\p{ASCII}]", ""); return replaceDescription; } @@ -189,8 +191,8 @@ public class XSDElement implements Element { } if (needValue == VALUE_INDEXED_PROPS && attrValue.equals("indexedProps")) { useValue = VALUE_INDEXED_PROPS; - } else if (needValue == VALUE_DSLSTARTNODE && - attrValue.equals("dslStartNodeProps")) { + } else if (needValue == VALUE_DSLSTARTNODE + && attrValue.equals("dslStartNodeProps")) { useValue = VALUE_DSLSTARTNODE; } if (useValue != VALUE_NONE && attrName.equals("value")) { @@ -262,8 +264,8 @@ public class XSDElement implements Element { StringBuilder sbParameter = new StringBuilder(); sbParameter.append(" - name: ").append(this.getAttribute("name")).append("\n"); sbParameter.append((" in: query\n")); - if (this.getAttribute("description") != null && - this.getAttribute("description").length() > 0) { + if (this.getAttribute("description") != null + && this.getAttribute("description").length() > 0) { sbParameter.append(" description: ").append(this.getAttribute("description")) .append("\n"); } else { @@ -330,8 +332,9 @@ public class XSDElement implements Element { String elementType = this.getAttribute("type"); String elementContainerType = this.getAttribute("container-type"); String elementIsRequired = this.getAttribute("required"); - String addType = elementType.contains("." + v.toString() + ".") ? - elementType.substring(elementType.lastIndexOf('.') + 1) : null; + String addType = elementType.contains("." + v.toString() + ".") + ? elementType.substring(elementType.lastIndexOf('.') + 1) + : null; if (addType != null) { sbElement.append(" " + OxmFileProcessor.LINE_SEPARATOR : ""); sbElement.append(annotation); - sbElement.append(StringUtils.isNotEmpty(annotation) ? - " " + OxmFileProcessor.LINE_SEPARATOR : - "/>" + OxmFileProcessor.LINE_SEPARATOR); + sbElement.append(StringUtils.isNotEmpty(annotation) + ? " " + OxmFileProcessor.LINE_SEPARATOR + : "/>" + OxmFileProcessor.LINE_SEPARATOR); } else { sbElement.append("/>").append(OxmFileProcessor.LINE_SEPARATOR); } return this.getHTMLElementWrapper(sbElement.toString(), v, useAnnotation); -// return sbElement.toString(); + // return sbElement.toString(); } public String getHTMLElementWrapper(String unwrappedElement, SchemaVersion v, - boolean useAnnotation) { + boolean useAnnotation) { NodeList childNodes = this.getElementsByTagName("xml-element-wrapper"); @@ -392,8 +395,9 @@ public class XSDElement implements Element { sbElement.append(" 0) { definitionsLocalPatchSb.append(" " + patchDefinePrefix).append(xmlRootElementName) .append(":\n"); - if (StringUtils.isNotEmpty(pathDescriptionProperty) || - StringUtils.isNotEmpty(validEdges)) { + if (StringUtils.isNotEmpty(pathDescriptionProperty) + || StringUtils.isNotEmpty(validEdges)) { definitionsLocalPatchSb.append(" description: |\n"); } if (pathDescriptionProperty != null) { @@ -721,8 +728,8 @@ public class YAMLfromOXM extends OxmFileProcessor { parentDir.mkdirs(); } try { - if(!outfile.createNewFile()) { - logger.error( "File {} already exist", outfileName); + if (!outfile.createNewFile()) { + logger.error("File {} already exist", outfileName); } } catch (IOException e) { logger.error("Exception creating output file " + outfileName, e); @@ -747,4 +754,3 @@ public class YAMLfromOXM extends OxmFileProcessor { } } - diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Api.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Api.java index a3adcd8..1dad255 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Api.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Api.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.swagger; import java.util.List; diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Definition.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Definition.java index 9df9842..8919857 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Definition.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/Definition.java @@ -17,7 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.aai.schemagen.swagger; import java.util.List; diff --git a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/GenerateSwagger.java b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/GenerateSwagger.java index 6663dc4..39b1e83 100644 --- a/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/GenerateSwagger.java +++ b/aai-schema-gen/src/main/java/org/onap/aai/schemagen/swagger/GenerateSwagger.java @@ -8,7 +8,7 @@ * 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, @@ -17,75 +17,80 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.swagger; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor; + import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; -import org.onap.aai.setup.SchemaVersions; import java.io.*; import java.util.*; import java.util.stream.Collectors; +import org.onap.aai.setup.SchemaVersions; + public class GenerateSwagger { public static final String LINE_SEPARATOR = System.getProperty("line.separator"); public static final String DEFAULT_WIKI = ""; public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - //if the program is run from aai-common, use this directory as default" + // if the program is run from aai-common, use this directory as default" public static final String ALT_SCHEMA_DIR = "aai-schema"; - //used to check to see if program is run from aai-schema-gen + // used to check to see if program is run from aai-schema-gen public static final String DEFAULT_RUN_DIR = "aai-schema-gen"; - public static SchemaVersions schemaVersions; + public static SchemaVersions schemaVersions; public SchemaVersions getSchemaVersions() { - return schemaVersions; - } - - - - public static void main(String[] args) throws IOException, TemplateException { - - + return schemaVersions; + } + public static void main(String[] args) throws IOException, TemplateException { - // SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class); - String CURRENT_VERSION = schemaVersions.getDefaultVersion().toString(); - String schemaDir = System.getProperty("aai.schema.dir"); + // SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class); + String CURRENT_VERSION = schemaVersions.getDefaultVersion().toString(); + String schemaDir = System.getProperty("aai.schema.dir"); String versionToGenerate = System.getProperty("aai.generate.version"); String wikiLink = System.getProperty("aai.wiki.link"); - String release = System.getProperty("aai.release", "onap"); - - if(schemaDir == null){ - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { - System.out.println("Warning: Schema directory is not set so using default schema dir: " + ALT_SCHEMA_DIR); - schemaDir = ALT_SCHEMA_DIR; - } - else { - System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR); - schemaDir = DEFAULT_SCHEMA_DIR; - } + String release = System.getProperty("aai.release", "onap"); + + if (schemaDir == null) { + if (System.getProperty("user.dir") != null + && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { + System.out + .println("Warning: Schema directory is not set so using default schema dir: " + + ALT_SCHEMA_DIR); + schemaDir = ALT_SCHEMA_DIR; + } else { + System.out + .println("Warning: Schema directory is not set so using default schema dir: " + + DEFAULT_SCHEMA_DIR); + schemaDir = DEFAULT_SCHEMA_DIR; + } } - if(versionToGenerate == null){ - System.out.println("Warning: Version to generate is not set so using default versionToGenerate " + CURRENT_VERSION); + if (versionToGenerate == null) { + System.out.println( + "Warning: Version to generate is not set so using default versionToGenerate " + + CURRENT_VERSION); versionToGenerate = CURRENT_VERSION; } - if(wikiLink == null){ + if (wikiLink == null) { System.out.println("Warning: aai.wiki.link property is not set so using default"); wikiLink = DEFAULT_WIKI; } - String yamlFile = schemaDir + "/src/main/resources/" + release + "/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; + String yamlFile = schemaDir + "/src/main/resources/" + release + + "/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; File swaggerYamlFile = new File(yamlFile); - if(!swaggerYamlFile.exists()){ + if (!swaggerYamlFile.exists()) { System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile); System.exit(1); } @@ -93,21 +98,23 @@ public class GenerateSwagger { Yaml yaml = new Yaml(new SafeConstructor()); Map swaggerMap = null; - try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){ + try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))) { swaggerMap = (Map) yaml.load(reader); - } catch(Exception ex){ - System.err.println("Unable load yaml file: " + swaggerYamlFile + " : " + ex.getMessage()); + } catch (Exception ex) { + System.err + .println("Unable load yaml file: " + swaggerYamlFile + " : " + ex.getMessage()); throw new IOException(); } Map map = (Map) swaggerMap.get("paths"); - Map schemaDefinitionmap = (Map) swaggerMap.get("definitions"); + Map schemaDefinitionmap = + (Map) swaggerMap.get("definitions"); Map infoMap = (Map) swaggerMap.get("info"); Map> tagMap = new LinkedHashMap<>(); List apis = convertToApi(map); apis.forEach((api) -> { - if(!tagMap.containsKey(api.getTag())){ + if (!tagMap.containsKey(api.getTag())) { List newApis = new ArrayList<>(); newApis.add(api); tagMap.put(api.getTag(), newApis); @@ -125,8 +132,9 @@ public class GenerateSwagger { List definitionList = convertToDefinition(schemaDefinitionmap); - definitionList = definitionList - .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList()); + definitionList = + definitionList.stream().sorted(Comparator.comparing(Definition::getDefinitionName)) + .collect(Collectors.toList()); resultMap.put("aaiApis", tagMap); resultMap.put("sortedAaiApis", sortedTagMap); @@ -136,23 +144,22 @@ public class GenerateSwagger { if (infoMap.containsKey("description")) { String infoDescription = infoMap.get("description").toString(); - infoDescription = Arrays.stream(infoDescription.split("\n")) - .map(line -> { - line = line.trim(); - String hyperLink = ""; - if(line.trim().contains("Differences versus")) { - return ""; - } - if(line.trim().contains("https://")){ - int startIndex = line.indexOf("https://"); - int endIndex = line.lastIndexOf("/"); - hyperLink = line.substring(startIndex, endIndex); - return String.format("%s
", hyperLink, line); - } - return String.format("%s
", line); - }) + infoDescription = Arrays.stream(infoDescription.split("\n")).map(line -> { + line = line.trim(); + String hyperLink = ""; + if (line.trim().contains("Differences versus")) { + return ""; + } + if (line.trim().contains("https://")) { + int startIndex = line.indexOf("https://"); + int endIndex = line.lastIndexOf("/"); + hyperLink = line.substring(startIndex, endIndex); + return String.format("%s
", hyperLink, line); + } + return String.format("%s
", line); + }) - .collect(Collectors.joining(LINE_SEPARATOR)); + .collect(Collectors.joining(LINE_SEPARATOR)); resultMap.put("description", infoDescription); } @@ -160,11 +167,12 @@ public class GenerateSwagger { Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading(Api.class, "/"); String resourcePath = "src/main/resources"; - if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { - configuration.setDirectoryForTemplateLoading(new File(DEFAULT_RUN_DIR + "/" + resourcePath)); - } - else { - configuration.setDirectoryForTemplateLoading(new File(resourcePath)); + if (System.getProperty("user.dir") != null + && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) { + configuration + .setDirectoryForTemplateLoading(new File(DEFAULT_RUN_DIR + "/" + resourcePath)); + } else { + configuration.setDirectoryForTemplateLoading(new File(resourcePath)); } Template template = configuration.getTemplate("swagger.html.ftl"); @@ -172,29 +180,31 @@ public class GenerateSwagger { File outputDir = new File(outputDirStr); - if(!outputDir.exists()){ + if (!outputDir.exists()) { boolean resp = outputDir.mkdir(); - if(!resp){ + if (!resp) { System.err.println("Unable to create the directory: " + outputDirStr); System.exit(1); } - } else if(outputDir.isFile()){ - System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists"); + } else if (outputDir.isFile()) { + System.err.println("Unable to create the directory: " + outputDirStr + + " since a filename with that string exists"); System.exit(1); } - Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); + Writer file = + new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); template.process(resultMap, file); } - public static List convertToApi(Map pathMap){ + public static List convertToApi(Map pathMap) { - if(pathMap == null) + if (pathMap == null) throw new IllegalArgumentException(); List apis = new ArrayList<>(); - pathMap.forEach( (pathKey, pathValue) -> { + pathMap.forEach((pathKey, pathValue) -> { Api api = new Api(); Map httpVerbMap = (Map) pathValue; @@ -206,83 +216,85 @@ public class GenerateSwagger { Api.HttpVerb httpVerb = new Api.HttpVerb(); - Map httpVerbValueMap = (Map)httpVerbValue; + Map httpVerbValueMap = (Map) httpVerbValue; httpVerb.setType(httpVerbKey); - if(httpVerbValueMap.containsKey("tags")){ - httpVerb.setTags((List)httpVerbValueMap.get("tags")); + if (httpVerbValueMap.containsKey("tags")) { + httpVerb.setTags((List) httpVerbValueMap.get("tags")); } - if(httpVerbValueMap.containsKey("summary")){ - httpVerb.setSummary((String)httpVerbValueMap.get("summary")); + if (httpVerbValueMap.containsKey("summary")) { + httpVerb.setSummary((String) httpVerbValueMap.get("summary")); } - if(httpVerbValueMap.containsKey("operationId")){ - httpVerb.setOperationId((String)httpVerbValueMap.get("operationId")); + if (httpVerbValueMap.containsKey("operationId")) { + httpVerb.setOperationId((String) httpVerbValueMap.get("operationId")); } - if(httpVerbValueMap.containsKey("consumes")){ - httpVerb.setConsumes((List)httpVerbValueMap.get("consumes")); - if(httpVerb.getConsumes() != null){ + if (httpVerbValueMap.containsKey("consumes")) { + httpVerb.setConsumes((List) httpVerbValueMap.get("consumes")); + if (httpVerb.getConsumes() != null) { httpVerb.setConsumerEnabled(true); } } - if(httpVerbValueMap.containsKey("produces")){ - httpVerb.setProduces((List)httpVerbValueMap.get("produces")); + if (httpVerbValueMap.containsKey("produces")) { + httpVerb.setProduces((List) httpVerbValueMap.get("produces")); } - if(httpVerbValueMap.containsKey("parameters")){ - List> parameters = (List>) httpVerbValueMap.get("parameters"); - List> requestParameters = parameters - .stream() - .filter((parameter) -> !parameter.get("name").equals("body")) - .collect(Collectors.toList()); + if (httpVerbValueMap.containsKey("parameters")) { + List> parameters = + (List>) httpVerbValueMap.get("parameters"); + List> requestParameters = parameters.stream() + .filter((parameter) -> !parameter.get("name").equals("body")) + .collect(Collectors.toList()); httpVerb.setParameters(requestParameters); - if(httpVerb.getParameters() != null){ + if (httpVerb.getParameters() != null) { httpVerb.setParametersEnabled(true); } - List> requestBodyList = parameters - .stream() - .filter((parameter) -> parameter.get("name").equals("body")) - .collect(Collectors.toList()); + List> requestBodyList = parameters.stream() + .filter((parameter) -> parameter.get("name").equals("body")) + .collect(Collectors.toList()); Map requestBody = null; - if(requestBodyList != null && requestBodyList.size() == 1){ + if (requestBodyList != null && requestBodyList.size() == 1) { requestBody = requestBodyList.get(0); - for(String key : requestBody.keySet()) { - //Filter out all the relationship links that appear in the YAML - if(key.equals("description")) { - String reqBody=(String)requestBody.get(key); - if(!reqBody.replaceAll("\\[.*.json\\)", "").equals(reqBody)) { - requestBody.put(key, reqBody.replaceAll("\\[.*.json\\)", "")); + for (String key : requestBody.keySet()) { + // Filter out all the relationship links that appear in the YAML + if (key.equals("description")) { + String reqBody = (String) requestBody.get(key); + if (!reqBody.replaceAll("\\[.*.json\\)", "").equals(reqBody)) { + requestBody.put(key, reqBody.replaceAll("\\[.*.json\\)", "")); + } } - } - //Filter out all the patchDefinition links that appear in the YAML - if(key.equals("schema")) { - LinkedHashMap reqBody = (LinkedHashMap)requestBody.get(key); - String schema=reqBody.get("$ref"); - String schemaNopatch = schema.replace("patchDefinitions", "definitions"); - - if(! schema.equals(schemaNopatch)) { - reqBody.put("$ref", schemaNopatch); - requestBody.put(key, reqBody); + // Filter out all the patchDefinition links that appear in the YAML + if (key.equals("schema")) { + LinkedHashMap reqBody = + (LinkedHashMap) requestBody.get(key); + String schema = reqBody.get("$ref"); + String schemaNopatch = + schema.replace("patchDefinitions", "definitions"); + + if (!schema.equals(schemaNopatch)) { + reqBody.put("$ref", schemaNopatch); + requestBody.put(key, reqBody); + } } - } } httpVerb.setBodyParametersEnabled(true); httpVerb.setBodyParameters(requestBody); - if(requestBody != null && requestBody.containsKey("schema")){ - Map schemaMap = (Map)requestBody.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ + if (requestBody != null && requestBody.containsKey("schema")) { + Map schemaMap = + (Map) requestBody.get("schema"); + if (schemaMap != null && schemaMap.containsKey("$ref")) { String schemaLink = schemaMap.get("$ref").toString(); httpVerb.setSchemaLink(schemaLink); int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ + if (retCode != -1 && retCode != schemaLink.length()) { httpVerb.setSchemaType(schemaLink.substring(retCode)); } } @@ -290,19 +302,19 @@ public class GenerateSwagger { } } - if(httpVerbValueMap.containsKey("responses")){ + if (httpVerbValueMap.containsKey("responses")) { List responses = new ArrayList(); - Map responsesMap = (Map) httpVerbValueMap.get("responses"); + Map responsesMap = + (Map) httpVerbValueMap.get("responses"); - responsesMap - .entrySet() - .stream() + responsesMap.entrySet().stream() .filter((res) -> !"default".equalsIgnoreCase(res.getKey())) .forEach((responseMap) -> { - Map responseValueMap = (Map)responseMap.getValue(); + Map responseValueMap = + (Map) responseMap.getValue(); Api.HttpVerb.Response response = new Api.HttpVerb.Response(); @@ -310,23 +322,27 @@ public class GenerateSwagger { response.setDescription((String) responseValueMap.get("description")); response.setVersion((String) responseValueMap.get("version")); - if(responseValueMap != null && responseValueMap.containsKey("schema")){ - Map schemaMap = (Map)responseValueMap.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ + if (responseValueMap != null + && responseValueMap.containsKey("schema")) { + Map schemaMap = + (Map) responseValueMap.get("schema"); + if (schemaMap != null && schemaMap.containsKey("$ref")) { String schemaLink = schemaMap.get("$ref").toString(); httpVerb.setHasReturnSchema(true); - //Filter out all the getDefinition links that appear in the YAML - httpVerb.setReturnSchemaLink(schemaLink.replace("getDefinitions", "definitions")); + // Filter out all the getDefinition links that appear in the + // YAML + httpVerb.setReturnSchemaLink( + schemaLink.replace("getDefinitions", "definitions")); int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setReturnSchemaObject(schemaLink.substring(retCode)); + if (retCode != -1 && retCode != schemaLink.length()) { + httpVerb + .setReturnSchemaObject(schemaLink.substring(retCode)); } } } responses.add(response); - } - ); + }); httpVerb.setResponses(responses); } @@ -343,145 +359,132 @@ public class GenerateSwagger { public static List convertToDefinition(Map definitionMap) { - if(definitionMap == null) + if (definitionMap == null) throw new IllegalArgumentException(); List defintionsList = new ArrayList<>(); - definitionMap - .entrySet() - .forEach((entry) -> { + definitionMap.entrySet().forEach((entry) -> { - Definition definition = new Definition(); - String key = entry.getKey(); - Map valueMap = (Map) entry.getValue(); + Definition definition = new Definition(); + String key = entry.getKey(); + Map valueMap = (Map) entry.getValue(); - definition.setDefinitionName(key); + definition.setDefinitionName(key); - if(valueMap.containsKey("description")){ - String description = valueMap.get("description").toString(); - description = formatDescription(description); - definition.setDefinitionDescription(description); - definition.setHasDescription(true); - } + if (valueMap.containsKey("description")) { + String description = valueMap.get("description").toString(); + description = formatDescription(description); + definition.setDefinitionDescription(description); + definition.setHasDescription(true); + } - List definitionProperties = new ArrayList<>(); + List definitionProperties = new ArrayList<>(); - List requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List) valueMap.get("required"); + List requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() + : (List) valueMap.get("required"); - Set requiredPropsSet = new HashSet<>(requiredProperties); + Set requiredPropsSet = new HashSet<>(requiredProperties); - valueMap - .entrySet() - .stream() - .filter( (e) -> "properties".equals(e.getKey())) - .forEach((propertyEntries) -> { - Map propertyRealEntries = (Map) propertyEntries.getValue(); - propertyRealEntries - .forEach((propertyKey, value) -> { - Definition.Property definitionProperty = new Definition.Property(); - if (requiredPropsSet.contains(propertyKey)) { - definitionProperty.setRequired(true); - } - definitionProperty.setPropertyName(propertyKey); - Map definitionPropertyMap = - (Map) value; - - if (definitionPropertyMap.containsKey("description")) { - definitionProperty.setPropertyDescription( - definitionPropertyMap.get("description").toString()); - definitionProperty.setHasPropertyDescription(true); - } - if (definitionPropertyMap.containsKey("type")) { - String type = definitionPropertyMap.get("type").toString(); - definitionProperty.setPropertyType(type); - definitionProperty.setHasType(true); - if ("array".equals(type)) { - definitionProperty.setPropertyType("object[]"); - if (!definitionPropertyMap.containsKey("items")) { - throw new RuntimeException( - "Unable to find the property items even though the type is array for " + - propertyKey); - } else { - Map itemMap = - (Map) definitionPropertyMap - .get("items"); - if (itemMap.containsKey("$ref")) { - definitionProperty.setHasPropertyReference(true); - String refItem = itemMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if (retCode != -1 && retCode != refItem.length()) { - definitionProperty - .setPropertyReferenceObjectName( - refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } else { - if (definitionPropertyMap.containsKey("$ref")) { - definitionProperty.setHasPropertyReference(true); - String refItem = - definitionPropertyMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if (retCode != -1 && retCode != refItem.length()) { - definitionProperty.setPropertyReferenceObjectName( - refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); + valueMap.entrySet().stream().filter((e) -> "properties".equals(e.getKey())) + .forEach((propertyEntries) -> { + Map propertyRealEntries = + (Map) propertyEntries.getValue(); + propertyRealEntries.forEach((propertyKey, value) -> { + Definition.Property definitionProperty = new Definition.Property(); + if (requiredPropsSet.contains(propertyKey)) { + definitionProperty.setRequired(true); + } + definitionProperty.setPropertyName(propertyKey); + Map definitionPropertyMap = (Map) value; + + if (definitionPropertyMap.containsKey("description")) { + definitionProperty.setPropertyDescription( + definitionPropertyMap.get("description").toString()); + definitionProperty.setHasPropertyDescription(true); + } + if (definitionPropertyMap.containsKey("type")) { + String type = definitionPropertyMap.get("type").toString(); + definitionProperty.setPropertyType(type); + definitionProperty.setHasType(true); + if ("array".equals(type)) { + definitionProperty.setPropertyType("object[]"); + if (!definitionPropertyMap.containsKey("items")) { + throw new RuntimeException( + "Unable to find the property items even though the type is array for " + + propertyKey); + } else { + Map itemMap = + (Map) definitionPropertyMap.get("items"); + if (itemMap.containsKey("$ref")) { + definitionProperty.setHasPropertyReference(true); + String refItem = itemMap.get("$ref").toString(); + int retCode = refItem.lastIndexOf('/'); + if (retCode != -1 && retCode != refItem.length()) { + definitionProperty.setPropertyReferenceObjectName( + refItem.substring(retCode + 1)); } + definitionProperty.setPropertyReference(refItem); } } - definitionProperties.add(definitionProperty); - }); + } else { + if (definitionPropertyMap.containsKey("$ref")) { + definitionProperty.setHasPropertyReference(true); + String refItem = definitionPropertyMap.get("$ref").toString(); + int retCode = refItem.lastIndexOf('/'); + if (retCode != -1 && retCode != refItem.length()) { + definitionProperty.setPropertyReferenceObjectName( + refItem.substring(retCode + 1)); + } + definitionProperty.setPropertyReference(refItem); + } + } + } + definitionProperties.add(definitionProperty); }); + }); - definition.setPropertyList(definitionProperties); + definition.setPropertyList(definitionProperties); - List schemaProperties = definitionProperties. - stream() - .filter(Definition.Property::isHasPropertyReference) - .collect(Collectors.toList()); + List schemaProperties = definitionProperties.stream() + .filter(Definition.Property::isHasPropertyReference).collect(Collectors.toList()); - List regularProperties = definitionProperties. - stream() - .filter((o) -> !o.isHasPropertyReference()) - .collect(Collectors.toList()); + List regularProperties = definitionProperties.stream() + .filter((o) -> !o.isHasPropertyReference()).collect(Collectors.toList()); - definition.setRegularPropertyList(regularProperties); - definition.setSchemaPropertyList(schemaProperties); + definition.setRegularPropertyList(regularProperties); + definition.setSchemaPropertyList(schemaProperties); - defintionsList.add(definition); - }); + defintionsList.add(definition); + }); return defintionsList; } - public static String formatDescription(String description){ + public static String formatDescription(String description) { - description = Arrays.stream(description.split("\n")) - .map((line) -> { + description = Arrays.stream(description.split("\n")).map((line) -> { + line = line.trim(); + if (line.contains("######")) { + line = line.replaceAll("#", ""); line = line.trim(); - if(line.contains("######")){ - line = line.replaceAll("#", ""); - line = line.trim(); - String headerId = line.toLowerCase().replaceAll("\\s", "-"); - - if(line.contains("Related Nodes")){ - return String.format("
%s
%s
    ", headerId, line, LINE_SEPARATOR); - } else { - return String.format("
    %s
    ", headerId, line); - } - } else if(line.startsWith("-")){ - line = line.replaceFirst("-", ""); - line = line.trim(); - return String.format("
  • %s
  • ", line); + String headerId = line.toLowerCase().replaceAll("\\s", "-"); + + if (line.contains("Related Nodes")) { + return String.format("
    %s
    %s
      ", headerId, line, + LINE_SEPARATOR); } else { - return String.format("

      %s

      ", line); + return String.format("
      %s
      ", headerId, line); } - }) - .collect(Collectors.joining(LINE_SEPARATOR)); + } else if (line.startsWith("-")) { + line = line.replaceFirst("-", ""); + line = line.trim(); + return String.format("
    • %s
    • ", line); + } else { + return String.format("

      %s

      ", line); + } + }).collect(Collectors.joining(LINE_SEPARATOR)); - if(description.contains("
        ")){ + if (description.contains("
          ")) { description = description + "
        "; } @@ -489,4 +492,3 @@ public class GenerateSwagger { } } - diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/GenerateXsdTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/GenerateXsdTest.java index c6d2dde..0b99454 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/GenerateXsdTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/GenerateXsdTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; + +import java.io.BufferedWriter; +import java.io.FileWriter; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -26,10 +34,10 @@ import org.junit.runner.RunWith; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.schemagen.genxsd.*; +import org.onap.aai.schemagen.testutils.TestUtilConfigTranslatorforBusiness; import org.onap.aai.setup.SchemaLocationsBean; import org.onap.aai.setup.SchemaVersion; import org.onap.aai.setup.SchemaVersions; -import org.onap.aai.schemagen.testutils.TestUtilConfigTranslatorforBusiness; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -38,111 +46,98 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.BufferedWriter; -import java.io.FileWriter; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaLocationsBean.class, - TestUtilConfigTranslatorforBusiness.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class, - SchemaVersions.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) +@ContextConfiguration( + classes = {SchemaLocationsBean.class, TestUtilConfigTranslatorforBusiness.class, + EdgeIngestor.class, NodeIngestor.class, SwaggerGenerationConfiguration.class, + SchemaVersions.class}) +@TestPropertySource(properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000"}) public class GenerateXsdTest { - private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - - @Autowired + private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class"); + private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; + private static final String EDGEFILENAME = + "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; + public static AnnotationConfigApplicationContext ctx = null; + private static String testXML; + + @Autowired YAMLfromOXM yamlFromOxm; - @Autowired + @Autowired HTMLfromOXM htmlFromOxm; - @Autowired + @Autowired SchemaVersions schemaVersions; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.getTestXML(); - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(YAMLfromOXMTest.EdgeDefs()); - bw1.close(); - - } - - @Before - public void setUp() throws Exception { - //PowerMockito.mockStatic(GenerateXsd.class); - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.getTestXML(); -// logger.info(testXML); - } - - @Test - public void test_generateSwaggerFromOxmFile( ) { - - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @BeforeClass + public static void setUpBeforeClass() throws Exception { + XSDElementTest x = new XSDElementTest(); + x.setUp(); + testXML = x.getTestXML(); + logger.debug(testXML); + BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + bw.write(testXML); + bw.close(); + BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw1.write(YAMLfromOXMTest.EdgeDefs()); + bw1.close(); + } - assertThat(fileContent, is(new YAMLfromOXMTest().YAMLresult())); - } - - @Test - public void test_generateXSDFromOxmFile( ) { - - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + + @Before + public void setUp() throws Exception { + // PowerMockito.mockStatic(GenerateXsd.class); + XSDElementTest x = new XSDElementTest(); + x.setUp(); + testXML = x.getTestXML(); + // logger.info(testXML); + } + + @Test + public void test_generateSwaggerFromOxmFile() { + + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + + yamlFromOxm.setXmlVersion(testXML, v); + fileContent = yamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat(fileContent, is(new YAMLfromOXMTest().YAMLresult())); } -// logger.debug(fileContent); - assertThat(fileContent, is(new HTMLfromOXMTest().HTMLresult())); - } - - @Test - public void testGetAPIVersion() { - GenerateXsd.apiVersion = schemaVersions.getAppRootVersion().toString(); - assertThat(GenerateXsd.getAPIVersion(),is("v11")); - } - - @Test - public void testGetYamlDir() { - assertThat(GenerateXsd.getYamlDir(),is("aai-schema/src/main/resources/onap/aai_swagger_yaml")); - } - - @Test - public void testGetResponsesUrl() { - assertNull(GenerateXsd.getResponsesUrl()); - } -} + @Test + public void test_generateXSDFromOxmFile() { + + SchemaVersion v = schemaVersions.getAppRootVersion(); + String fileContent = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + fileContent = htmlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + // logger.debug(fileContent); + assertThat(fileContent, is(new HTMLfromOXMTest().HTMLresult())); + } + + @Test + public void testGetAPIVersion() { + GenerateXsd.apiVersion = schemaVersions.getAppRootVersion().toString(); + assertThat(GenerateXsd.getAPIVersion(), is("v11")); + } + + @Test + public void testGetYamlDir() { + assertThat(GenerateXsd.getYamlDir(), + is("aai-schema/src/main/resources/onap/aai_swagger_yaml")); + } + + @Test + public void testGetResponsesUrl() { + assertNull(GenerateXsd.getResponsesUrl()); + } +} diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSetTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSetTest.java index fe1aa6f..4729af4 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSetTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteFootnoteSetTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,67 +17,73 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.Arrays; +import java.util.Collection; + 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; + String targetNode; + String flavor; + String result; + DeleteFootnoteSet footnotes = null; - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"vserver","(1)", "\n -(1) IF this VSERVER node is deleted, this FROM node is DELETED also\n"}, - {"ctag-pool","(2)", "\n -(2) IF this CTAG-POOL node is deleted, this TO node is DELETED also\n"}, - {"pserver","(3)", "\n -(3) IF this FROM node is deleted, this PSERVER is DELETED also\n"}, - {"oam-network","(4)", "\n -(4) IF this TO node is deleted, this OAM-NETWORK is DELETED also\n"}, - {"dvs-switch","(1)", "\n -(1) IF this DVS-SWITCH node is deleted, this FROM node is DELETED also\n"}, - {"availability-zone","(3)", "\n -(3) IF this FROM node is deleted, this AVAILABILITY-ZONE is DELETED also\n"} - }; - return (Arrays.asList(inputs)); - } + @Parameters + public static Collection testConditions() { + String inputs[][] = { + {"vserver", "(1)", + "\n -(1) IF this VSERVER node is deleted, this FROM node is DELETED also\n"}, + {"ctag-pool", "(2)", + "\n -(2) IF this CTAG-POOL node is deleted, this TO node is DELETED also\n"}, + {"pserver", "(3)", + "\n -(3) IF this FROM node is deleted, this PSERVER is DELETED also\n"}, + {"oam-network", "(4)", + "\n -(4) IF this TO node is deleted, this OAM-NETWORK is DELETED also\n"}, + {"dvs-switch", "(1)", + "\n -(1) IF this DVS-SWITCH node is deleted, this FROM node is DELETED also\n"}, + {"availability-zone", "(3)", + "\n -(3) IF this FROM node is deleted, this AVAILABILITY-ZONE is DELETED also\n"}}; + return (Arrays.asList(inputs)); + } - public DeleteFootnoteSetTest(String targetNode, String flavor, String result) { - super(); - this.targetNode = targetNode; - this.flavor = flavor; - this.result=result; - } + 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); - } + @Before + public void setUp() throws Exception { + footnotes = new DeleteFootnoteSet(this.targetNode); + } - @Test - public void testDeleteFootnoteSet() { - assertThat(footnotes.targetNode, is(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 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)); - } + @Test + public void testToString() { + footnotes.add(this.flavor); + assertThat(footnotes.toString(), is(this.result)); + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteOperationTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteOperationTest.java index 0f44954..08f5c81 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteOperationTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/DeleteOperationTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,65 +17,76 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; + import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import 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; + private String useOpId; + private String xmlRootElementName; + private String tag; + private String path; + private String pathParams; + private String result; + + @Parameters + public static Collection testConditions() { + String inputs[][] = {{"NetworkGenericVnfsGenericVnf", "generic-vnf", "Network", + "/network/generic-vnfs/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n", + " delete:\n tags:\n - Network\n summary: delete an existing generic-vnf\n description: delete an existing generic-vnf\n operationId: deleteNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n - name: resource-version\n in: query\n description: resource-version for concurrency\n required: true\n type: string\n"}, + // if ( StringUtils.isEmpty(tag) ) + {"GenericVnf", "generic-vnf", "", "/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n", + ""}, + // Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) + {"CloudInfrastructurePserversPserverPInterfaces", "p-interfaces", "CloudInfrastructure", + "/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces", + " - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__", + ""}, + // {"","ctag-pool","","","",""}, + // {"","pserver","","","",""}, + // {"","oam-network","","","",""}, + // {"","dvs-switch","","","",""}, + // {"","availability-zone","","","",""} + }; + return Arrays.asList(inputs); + } - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n"," delete:\n tags:\n - Network\n summary: delete an existing generic-vnf\n description: delete an existing generic-vnf\n operationId: deleteNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n - name: resource-version\n in: query\n description: resource-version for concurrency\n required: true\n type: string\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__\n",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, -// {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } + public DeleteOperationTest(String useOpId, String xmlRootElementName, String tag, String path, + String pathParams, String result) { + super(); + this.useOpId = useOpId; + this.xmlRootElementName = xmlRootElementName; + this.tag = tag; + this.path = path; + this.pathParams = pathParams; + this.result = result; + } - 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 { + @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)); - } + @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-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/EdgeDescriptionTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/EdgeDescriptionTest.java index b17901f..1469272 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/EdgeDescriptionTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/EdgeDescriptionTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,9 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + import com.google.common.collect.Multimap; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.*; + import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; @@ -38,311 +49,314 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.*; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {SchemaVersions.class, SchemaLocationsBean.class, TestUtilConfigTranslatorforEdges.class, EdgeIngestor.class}) -@TestPropertySource(properties = {"schemaIngestPropLoc = src/test/resources/schemaIngest/schemaIngestTest.properties"}) - +@ContextConfiguration( + classes = {SchemaVersions.class, SchemaLocationsBean.class, + TestUtilConfigTranslatorforEdges.class, EdgeIngestor.class}) +@TestPropertySource( + properties = { + "schemaIngestPropLoc = src/test/resources/schemaIngest/schemaIngestTest.properties"}) -public class EdgeDescriptionTest { - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - @Autowired +public class EdgeDescriptionTest { + private static final String EDGEFILENAME = + "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; + @Autowired ConfigTranslator ct; - @Autowired + @Autowired EdgeIngestor edgeIngestor; - String nodeName = "availability-zone"; - String toNode = "complex"; - SchemaVersion v10 = new SchemaVersion("v10"); - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String json = "{" - + " \"rules\": [" - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"complex\"," - + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"this description\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"service-capability\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"cloud-region\"," - + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"!${direction}\"," - + " \"delete-other-v\": \"!${direction}\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"NONE\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"ctag-pool\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"${direction}\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"dvs-switch\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"generic-vnf\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"pserver\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vce\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " ]}"; - BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw.write(json); - bw.close(); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - File edges = new File(EDGEFILENAME); - edges.delete(); - } - @Before - public void setUp() throws Exception { + String nodeName = "availability-zone"; + String toNode = "complex"; + SchemaVersion v10 = new SchemaVersion("v10"); - } - @Test - public void test() { + @BeforeClass + public static void setUpBeforeClass() throws Exception { + String json = "{" + " \"rules\": [" + " {" + " \"from\": \"availability-zone\"," + + " \"to\": \"complex\"," + + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"this description\"" + + " }," + " {" + " \"from\": \"availability-zone\"," + + " \"to\": \"service-capability\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " {" + + " \"from\": \"availability-zone\"," + " \"to\": \"cloud-region\"," + + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"!${direction}\"," + + " \"delete-other-v\": \"!${direction}\"," + " \"SVC-INFRA\": \"NONE\"," + + " \"prevent-delete\": \"NONE\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"ctag-pool\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"${direction}\"," + + " \"delete-other-v\": \"NONE\"," + " \"SVC-INFRA\": \"NONE\"," + + " \"prevent-delete\": \"!${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"dvs-switch\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " {" + + " \"from\": \"generic-vnf\"," + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.Uses\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"${direction}\"," + + " \"prevent-delete\": \"!${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"pserver\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"${direction}\"," + + " \"prevent-delete\": \"!${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"vce\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.Uses\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " ]}"; + BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw.write(json); + bw.close(); + } - Map> edges = ct.getEdgeFiles(); - assertTrue(edges.containsKey(v10)); - assertTrue(1 == edges.get(v10).size()); - assertTrue("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json".equals(edges.get(v10).get(0))); - } - @Test - public void testGetDeleteOtherV() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"NONE"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDeleteOtherV(), is(target)); } ); + @AfterClass + public static void tearDownAfterClass() throws Exception { + File edges = new File(EDGEFILENAME); + edges.delete(); } - } - @Test - public void testGetPreventDelete() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"IN"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getPreventDelete(), is(target)); } ); + @Before + public void setUp() throws Exception { + } - } - @Test - public void testGetAlsoDeleteFootnote() throws EdgeRuleNotFoundException { -// String toNode="cloud-region"; -// String target = "availability-zone"+"|"+toNode+"-"+"(4)"; - List notedTypes = Arrays.asList("cloud-region", "ctag-pool"); - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals("availability-zone") && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); String target = ed.getRuleKey()+"-"+(notedTypes.contains(ed.getTo()) ? "(4)" : ""); assertThat(ed.getRuleKey()+"-"+ed.getAlsoDeleteFootnote(ed.getFrom()), is(target)); } ); + @Test + public void test() { + + Map> edges = ct.getEdgeFiles(); + assertTrue(edges.containsKey(v10)); + assertTrue(1 == edges.get(v10).size()); + assertTrue("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json" + .equals(edges.get(v10).get(0))); } -/* - 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 testGetDeleteOtherV() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "NONE"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getDeleteOtherV(), is(target)); + }); + } } -*/ - } - @Test - public void testGetTo() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+toNode; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getTo(), is(target)); } ); + @Test + public void testGetPreventDelete() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "IN"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getPreventDelete(), is(target)); + }); + } } - } - @Test - public void testGetFrom() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"availability-zone"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getFrom(), is(target)); } ); + @Test + public void testGetAlsoDeleteFootnote() throws EdgeRuleNotFoundException { + // String toNode="cloud-region"; + // String target = "availability-zone"+"|"+toNode+"-"+"(4)"; + List notedTypes = Arrays.asList("cloud-region", "ctag-pool"); + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals("availability-zone") && (!i.isPrivateEdge()))) + .forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + String target = + ed.getRuleKey() + "-" + (notedTypes.contains(ed.getTo()) ? "(4)" : ""); + assertThat(ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()), + is(target)); + }); + } + /* + * for (EdgeDescription ed : edges) { + * String modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); + * assertThat(modResult, is(target)); + * ed.setDeleteOtherV("IN"); + * target = "availability-zone"+"|"+"complex"+"-"+"(4)"; + * modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); + * assertThat(modResult, is(target)); + * target = "availability-zone"+"|"+"complex"+"-"+"(1)"; + * modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getTo()); + * assertThat(modResult, is(target)); + * ed.setDeleteOtherV("OUT"); + * target = "availability-zone"+"|"+"complex"+"-"+"(2)"; + * modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getFrom()); + * assertThat(modResult, is(target)); + * target = "availability-zone"+"|"+"complex"+"-"+"(3)"; + * modResult = ed.getRuleKey() + "-" + ed.getAlsoDeleteFootnote(ed.getTo()); + * assertThat(modResult, is(target)); + * } + */ } - } - @Test - public void testGetRuleKey() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey(), is(target)); } ); + @Test + public void testGetTo() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + toNode; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getTo(), is(target)); + }); + } } - } - @Test - public void testGetMultiplicity() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"MANY2ONE"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getMultiplicity(), is(target)); } ); + @Test + public void testGetFrom() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "availability-zone"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getFrom(), is(target)); + }); + } } - } - @Test - public void testGetDirection() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"OUT"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDirection(), is(target)); } ); + @Test + public void testGetRuleKey() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey(), is(target)); + }); + } } - } - @Test - public void testGetDescription() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"this description"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDescription(), is(target)); } ); + @Test + public void testGetMultiplicity() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "MANY2ONE"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getMultiplicity(), is(target)); + }); + } } - } - @Test - public void testGetRelationshipDescription() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"this description"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getDescription(), is(target)); } ); + @Test + public void testGetDirection() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "OUT"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getDirection(), is(target)); + }); + } } - } - @Test - public void testGetType() throws EdgeRuleNotFoundException { - String toNode = "cloud-region"; - String target = "availability-zone"+"|"+toNode+"-"+"PARENT"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getType(), is(target)); } ); + @Test + public void testGetDescription() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "this description"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getDescription(), is(target)); + }); + } } - } - @Test - public void testGetLabel() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"org.onap.relationships.inventory.LocatedIn"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getLabel(), is(target)); } ); + @Test + public void testGetRelationshipDescription() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "this description"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getDescription(), is(target)); + }); + } } - } - @Test - public void testGetShortLabel() throws EdgeRuleNotFoundException { - String target = "availability-zone"+"|"+toNode+"-"+"LocatedIn"; - Multimap results = edgeIngestor.getAllRules(v10); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> (i.getTo().equals(toNode) && (! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); assertThat(ed.getRuleKey()+"-"+ed.getShortLabel(), is(target)); } ); + @Test + public void testGetType() throws EdgeRuleNotFoundException { + String toNode = "cloud-region"; + String target = "availability-zone" + "|" + toNode + "-" + "PARENT"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getType(), is(target)); + }); + } } - } -} + @Test + public void testGetLabel() throws EdgeRuleNotFoundException { + String target = + "availability-zone" + "|" + toNode + "-" + "org.onap.relationships.inventory.LocatedIn"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getLabel(), is(target)); + }); + } + } + @Test + public void testGetShortLabel() throws EdgeRuleNotFoundException { + String target = "availability-zone" + "|" + toNode + "-" + "LocatedIn"; + Multimap results = edgeIngestor.getAllRules(v10); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream() + .filter((i) -> (i.getTo().equals(toNode) && (!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + assertThat(ed.getRuleKey() + "-" + ed.getShortLabel(), is(target)); + }); + } + } +} diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/GetOperationTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/GetOperationTest.java index 74fa60b..aad62ce 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/GetOperationTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/GetOperationTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Vector; + import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,80 +35,82 @@ 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; + private static final Logger logger = LoggerFactory.getLogger("GetOperationTest.class"); + private String useOpId; + private String xmlRootElementName; + private String tag; + private String path; + private String pathParams; + private String result; - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," /network/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Network\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/generic-vnf\"\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__"," /cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces:\n get:\n tags:\n - CloudInfrastructure\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/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); - } + @Parameters + public static Collection testConditions() { + String inputs[][] = {{"NetworkGenericVnfsGenericVnf", "generic-vnf", "Network", + "/network/generic-vnfs/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + " /network/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Network\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/generic-vnf\"\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, + {"GenericVnf", "generic-vnf", "", "/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + ""}, + {"CloudInfrastructurePserversPserverPInterfaces", "p-interfaces", "CloudInfrastructure", + "/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces", + " - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__", + " /cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces:\n get:\n tags:\n - CloudInfrastructure\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/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; + } - public GetOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String container = "p-interfaces"; - String queryProps[] = { - " - name: interface-name\n in: query\n description:\n required: false\n type: string", - " - name: prov-status\n in: query\n description:\n required: false\n type: string" - }; - Vector containerProps = new Vector(); - for(String prop : queryProps) { - containerProps.add(prop); + @BeforeClass + public static void setUpBeforeClass() throws Exception { + String container = "p-interfaces"; + String queryProps[] = { + " - name: interface-name\n in: query\n description:\n required: false\n type: string", + " - name: prov-status\n in: query\n description:\n required: false\n type: string"}; + Vector containerProps = new Vector(); + for (String prop : queryProps) { + containerProps.add(prop); + } + GetOperation.addContainerProps(container, containerProps); } - GetOperation.addContainerProps(container, containerProps); - } - @Test - public void testAddContainerProps() { - String container = this.xmlRootElementName; - String prop = " - name: "+container+"\n in: query\n description:\n required: false\n type: string"; - Vector queryProps = new Vector(); - queryProps.add(prop); - for(String p : queryProps) { - logger.debug("qProp="+p); + @Test + public void testAddContainerProps() { + String container = this.xmlRootElementName; + String prop = " - name: " + container + + "\n in: query\n description:\n required: false\n type: string"; + Vector queryProps = new Vector(); + queryProps.add(prop); + for (String p : queryProps) { + logger.debug("qProp=" + p); + } + logger.debug("Done=" + this.xmlRootElementName); + GetOperation.addContainerProps(container, queryProps); + assertThat(GetOperation.containers.get(container).get(0), is(prop)); } - 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)); - } + @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-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/HTMLfromOXMTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/HTMLfromOXMTest.java index b5d9489..d4a6517 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/HTMLfromOXMTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/HTMLfromOXMTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -39,342 +52,383 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.w3c.dom.Element; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaVersions.class, - SchemaLocationsBean.class, - TestUtilConfigTranslatorforBusiness.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class +@ContextConfiguration( + classes = {SchemaVersions.class, SchemaLocationsBean.class, + TestUtilConfigTranslatorforBusiness.class, EdgeIngestor.class, NodeIngestor.class, + SwaggerGenerationConfiguration.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) + }) +@TestPropertySource(properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000"}) public class HTMLfromOXMTest { - private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - protected static final String SERVICE_NAME = "JUNIT"; - + private static final Logger logger = LoggerFactory.getLogger("HTMLfromOXMTest.class"); + private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; + public static AnnotationConfigApplicationContext ctx = null; + private static String testXML; + protected static final String SERVICE_NAME = "JUNIT"; - @Autowired - HTMLfromOXM htmlFromOxm; + @Autowired + HTMLfromOXM htmlFromOxm; - @Autowired + @Autowired SchemaVersions schemaVersions; - @BeforeClass - public static void setUpContext() throws Exception { + @BeforeClass + public static void setUpContext() throws Exception { - } - @BeforeClass + } + + @BeforeClass public static void setupBundleconfig() throws Exception { System.setProperty("AJSC_HOME", "."); System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); System.setProperty("aai.service.name", SERVICE_NAME); } - @Before - public void setUp() throws Exception { - setUp(0); - } + @Before + public void setUp() throws Exception { + setUp(0); + } - public void setUp(int sbopt) throws Exception - { - XSDElementTest x = new XSDElementTest(); - x.setUp(sbopt); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - } + public void setUp(int sbopt) throws Exception { + XSDElementTest x = new XSDElementTest(); + x.setUp(sbopt); + testXML = x.testXML; + logger.debug(testXML); + BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + bw.write(testXML); + bw.close(); + } - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String header = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - htmlFromOxm.setSchemaVersions(schemaVersions); - header = htmlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testGetDocumentHeader() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String header = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + htmlFromOxm.setSchemaVersions(schemaVersions); + header = htmlFromOxm.getDocumentHeader(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.debug("Header:"); + logger.debug(header); + assertThat(header, is(HTMLheader())); } - logger.debug("Header:"); - logger.debug(header); - assertThat(header, is(HTMLheader())); - } - @Test - public void testProcess() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testProcess() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String fileContent = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + fileContent = htmlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.debug("FileContent-I:"); + logger.debug(fileContent); + assertThat(fileContent, is(HTMLresult(0))); } - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - @Test - public void testProcessWithCombiningJavaTypes() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - setUp(1); - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testProcessWithCombiningJavaTypes() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String fileContent = null; + try { + setUp(1); + htmlFromOxm.setXmlVersion(testXML, v); + fileContent = htmlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.debug("FileContent-I:"); + logger.debug(fileContent); + assertThat(fileContent, is(HTMLresult(1))); } - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(1))); - } - @Test - public void testHTMLfromOXMFileVersion() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testHTMLfromOXMFileVersion() throws IOException { + String outfileName = "testXML.xml"; + File XMLfile = new File(outfileName); + XMLfile.createNewFile(); + BufferedWriter bw = null; + Charset charset = Charset.forName("UTF-8"); + Path path = Paths.get(outfileName); + bw = Files.newBufferedWriter(path, charset); + bw.write(testXML); + bw.close(); + SchemaVersion v = schemaVersions.getAppRootVersion(); + String fileContent = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + fileContent = htmlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + XMLfile.delete(); + logger.debug("FileContent-I:"); + logger.debug(fileContent); + assertThat(fileContent, is(HTMLresult(0))); } - XMLfile.delete(); - logger.debug("FileContent-I:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - @Test - public void testHTMLfromOXMStringVersion() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String fileContent = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - fileContent = htmlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testHTMLfromOXMStringVersion() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String fileContent = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + fileContent = htmlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.debug("FileContent-II:"); + logger.debug(fileContent); + assertThat(fileContent, is(HTMLresult(0))); } - logger.debug("FileContent-II:"); - logger.debug(fileContent); - assertThat(fileContent, is(HTMLresult(0))); - } - @Test - public void testProcessJavaTypeElement() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - Element customer = null; - try { - htmlFromOxm.setXmlVersion(testXML, v); - htmlFromOxm.process(); - customer = htmlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testProcessJavaTypeElement() { + String target = "Element=java-type/Customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + Element customer = null; + try { + htmlFromOxm.setXmlVersion(testXML, v); + htmlFromOxm.process(); + customer = htmlFromOxm.getJavaTypeElementSwagger("Customer"); + } catch (Exception e) { + e.printStackTrace(); + } + logger.debug("Element:"); + logger.debug("Element=" + customer.getNodeName() + "/" + customer.getAttribute("name")); + assertThat("Element=" + customer.getNodeName() + "/" + customer.getAttribute("name"), + is(target)); } - logger.debug("Element:"); - logger.debug("Element="+customer.getNodeName()+"/"+customer.getAttribute("name")); - assertThat("Element="+customer.getNodeName()+"/"+customer.getAttribute("name"), is(target)); } - public String HTMLresult() { - return HTMLresult(0); - } + public String HTMLresult() { + return HTMLresult(0); + } - public String HTMLresult(int sbopt) { - StringBuilder sb = new StringBuilder(32368); - sb.append(HTMLheader()); - sb.append(HTMLdefs(sbopt)); - return sb.toString(); - } + public String HTMLresult(int sbopt) { + StringBuilder sb = new StringBuilder(32368); + sb.append(HTMLheader()); + sb.append(HTMLdefs(sbopt)); + return sb.toString(); + } - public String HTMLheader() { - StringBuilder sb = new StringBuilder(1500); - sb.append("" + OxmFileProcessor.LINE_SEPARATOR); - sb.append("" + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - return sb.toString(); - } + public String HTMLheader() { + StringBuilder sb = new StringBuilder(1500); + sb.append("" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + "" + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + return sb.toString(); + } - public String HTMLdefs() { - return HTMLdefs(0); - } - public String HTMLdefs(int sbopt) { - StringBuilder sb = new StringBuilder(1500); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(isKey=true,description=\"Value defined by orchestration to identify this service.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"This property will be deleted from A&AI in the near future. Only stop gap solution.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - if ( sbopt == 0 ) { - sb.append(" @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR); - } else { - sb.append(" @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-type,subscriber-name,global-customer-id\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR); + public String HTMLdefs() { + return HTMLdefs(0); } - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(isKey=true,description=\"Global customer id used across to uniquely identify customer.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber name, an alternate way to retrieve a customer.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - if ( sbopt == 0 ) { - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - } else { - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + public String HTMLdefs(int sbopt) { + StringBuilder sb = new StringBuilder(1500); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(isKey=true,description=\"Value defined by orchestration to identify this service.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"This property will be deleted from A&AI in the near future. Only stop gap solution.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + if (sbopt == 0) { + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + + OxmFileProcessor.LINE_SEPARATOR); + } else { + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-type,subscriber-name,global-customer-id\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + + OxmFileProcessor.LINE_SEPARATOR); + } + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(isKey=true,description=\"Global customer id used across to uniquely identify customer.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Subscriber name, an alternate way to retrieve a customer.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + if (sbopt == 0) { + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + } else { + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Used for optimistic concurrency. Must be empty on create, valid on update and delete.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Subscriber type, a way to provide VID with only the INFRA customers.\",defaultValue=\"CUST\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + + } + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); + sb.append("" + OxmFileProcessor.LINE_SEPARATOR); + return sb.toString(); } - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" " + OxmFileProcessor.LINE_SEPARATOR); - sb.append("" + OxmFileProcessor.LINE_SEPARATOR); - return sb.toString(); - } } - diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodeGetOperationTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodeGetOperationTest.java index 8ecc8b5..fc75150 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodeGetOperationTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodeGetOperationTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Vector; + import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,82 +35,86 @@ 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 NodeGetOperationTest { - private static final Logger logger = LoggerFactory.getLogger("NodeGetOperationTest.class"); - private String useOpId; - private String xmlRootElementName; - private String tag; - private String path; - private String pathParams; - private String result; + private static final Logger logger = LoggerFactory.getLogger("NodeGetOperationTest.class"); + private String useOpId; + private String xmlRootElementName; + private String tag; + private String path; + private String pathParams; + private String result; - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," /nodes/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Operations\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/generic-vnf\"\n \"default\":\n null\n parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, - {"GenericVnf","generic-vnf","","/Network/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__"," /nodes/p-interfaces?parameter=value[¶meter2=value2]:\n get:\n tags:\n - Operations\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/p-interfaces\"\n \"default\":\n null\n parameters:\n - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__\n - name: interface-name\n in: query\n description:\n required: false\n type: string - name: prov-status\n in: query\n description:\n required: false\n type: string"}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } + @Parameters + public static Collection testConditions() { + String inputs[][] = {{"NetworkGenericVnfsGenericVnf", "generic-vnf", "Network", + "/network/generic-vnfs/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + " /nodes/generic-vnfs/generic-vnf/{vnf-id}:\n get:\n tags:\n - Operations\n summary: returns generic-vnf\n description: returns generic-vnf\n operationId: getNetworkGenericVnfsGenericVnf\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/generic-vnf\"\n \"default\":\n null\n parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"}, + {"GenericVnf", "generic-vnf", "", "/Network/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + ""}, + {"CloudInfrastructurePserversPserverPInterfaces", "p-interfaces", "CloudInfrastructure", + "/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces", + " - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__", + " /nodes/p-interfaces?parameter=value[¶meter2=value2]:\n get:\n tags:\n - Operations\n summary: returns p-interfaces\n description: returns p-interfaces\n operationId: getCloudInfrastructurePserversPserverPInterfaces\n produces:\n - application/json\n - application/xml\n responses:\n \"200\":\n description: successful operation\n schema:\n $ref: \"#/definitions/p-interfaces\"\n \"default\":\n null\n parameters:\n - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__\n - name: interface-name\n in: query\n description:\n required: false\n type: string - name: prov-status\n in: query\n description:\n required: false\n type: string"}, + // {"","ctag-pool","","","",""}, + // {"","pserver","","","",""}, + // {"","oam-network","","","",""}, + // {"","dvs-switch","","","",""}, + // {"","availability-zone","","","",""} + }; + return Arrays.asList(inputs); + } + + public NodeGetOperationTest(String useOpId, String xmlRootElementName, String tag, String path, + String pathParams, String result) { + super(); + this.useOpId = useOpId; + this.xmlRootElementName = xmlRootElementName; + this.tag = tag; + this.path = path; + this.pathParams = pathParams; + this.result = result; + } - public NodeGetOperationTest(String useOpId, String xmlRootElementName, String tag, String path, String pathParams, String result) { - super(); - this.useOpId = useOpId; - this.xmlRootElementName = xmlRootElementName; - this.tag = tag; - this.path = path; - this.pathParams=pathParams; - this.result = result; - } - @BeforeClass - public static void setUpBeforeClass() throws Exception { - String container = "p-interfaces"; - String queryProps[] = { - " - name: interface-name\n in: query\n description:\n required: false\n type: string", - " - name: prov-status\n in: query\n description:\n required: false\n type: string" - }; - Vector containerProps = new Vector(); - for(String prop : queryProps) { - containerProps.add(prop); + @BeforeClass + public static void setUpBeforeClass() throws Exception { + String container = "p-interfaces"; + String queryProps[] = { + " - name: interface-name\n in: query\n description:\n required: false\n type: string", + " - name: prov-status\n in: query\n description:\n required: false\n type: string"}; + Vector containerProps = new Vector(); + for (String prop : queryProps) { + containerProps.add(prop); + } + NodeGetOperation.addContainerProps(container, containerProps); } - NodeGetOperation.addContainerProps(container, containerProps); - } - @Test - public void testAddContainerProps() { - String container = this.xmlRootElementName; - String prop = " - name: "+container+"\n in: query\n description:\n required: false\n type: string"; - Vector queryProps = new Vector(); - queryProps.add(prop); - String props=null; - for(String p : queryProps) { - props += "qProp="+p+"\n"; -// logger.debug("qProp="+p); + @Test + public void testAddContainerProps() { + String container = this.xmlRootElementName; + String prop = " - name: " + container + + "\n in: query\n description:\n required: false\n type: string"; + Vector queryProps = new Vector(); + queryProps.add(prop); + String props = null; + for (String p : queryProps) { + props += "qProp=" + p + "\n"; + // logger.debug("qProp="+p); + } + // logger.debug("Done="+this.xmlRootElementName); + NodeGetOperation.addContainerProps(container, queryProps); + assertThat(props + "Done=" + this.xmlRootElementName, + NodeGetOperation.containers.get(container).get(0), is(prop)); } -// logger.debug("Done="+this.xmlRootElementName); - NodeGetOperation.addContainerProps(container, queryProps); - assertThat(props+"Done="+this.xmlRootElementName,NodeGetOperation.containers.get(container).get(0), is(prop)); - } - @Test - public void testToString() { - NodeGetOperation get = new NodeGetOperation(useOpId, xmlRootElementName, tag, path, pathParams); - String modResult = get.toString(); - assertThat(modResult, is(this.result)); - } + @Test + public void testToString() { + NodeGetOperation get = + new NodeGetOperation(useOpId, xmlRootElementName, tag, path, pathParams); + String modResult = get.toString(); + assertThat(modResult, is(this.result)); + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXMTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXMTest.java index ed403e0..468de16 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXMTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/NodesYAMLfromOXMTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -39,232 +52,229 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.w3c.dom.Element; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaVersions.class, - SchemaLocationsBean.class, - TestUtilConfigTranslatorforEdges.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class +@ContextConfiguration( + classes = {SchemaVersions.class, SchemaLocationsBean.class, + TestUtilConfigTranslatorforEdges.class, EdgeIngestor.class, NodeIngestor.class, + SwaggerGenerationConfiguration.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) + }) +@TestPropertySource(properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000"}) public class NodesYAMLfromOXMTest { -//public class NodesYAMLfromOXMTest extends AAISetup { - private static final Logger logger = LoggerFactory.getLogger("NodesYAMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; + // public class NodesYAMLfromOXMTest extends AAISetup { + private static final Logger logger = LoggerFactory.getLogger("NodesYAMLfromOXMTest.class"); + private static final String OXMFILENAME = "src/test/resources/oxm/business_v11.xml"; + private static final String EDGEFILENAME = + "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; + public static AnnotationConfigApplicationContext ctx = null; + private static String testXML; - @Autowired - NodesYAMLfromOXM nodesYamlFromOxm; - @Autowired + @Autowired + NodesYAMLfromOXM nodesYamlFromOxm; + @Autowired SchemaVersions schemaVersions; - @BeforeClass - public static void setUpBeforeClass() throws Exception { + @BeforeClass + public static void setUpBeforeClass() throws Exception { - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(YAMLfromOXMTest.EdgeDefs()); - bw1.close(); + XSDElementTest x = new XSDElementTest(); + x.setUp(); + testXML = x.testXML; + logger.debug(testXML); + BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + bw.write(testXML); + bw.close(); + BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw1.write(YAMLfromOXMTest.EdgeDefs()); + bw1.close(); + } - } - - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - NodeGetOperation.checklist.clear(); - XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; + NodeGetOperation.checklist.clear(); + XSDElementTest x = new XSDElementTest(); + x.setUp(); + testXML = x.testXML; - logger.debug(testXML); - } + logger.debug(testXML); + } - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String header = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - header = nodesYamlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testGetDocumentHeader() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String header = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + nodesYamlFromOxm.process(); + header = nodesYamlFromOxm.getDocumentHeader(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Header:\n" + header, header, is(YAMLheader())); } - assertThat("Header:\n"+header,header, is(YAMLheader())); - } - @Test - public void testProcess() { + @Test + public void testProcess() { + + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + fileContent = nodesYamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("FileContent-I:\n" + fileContent, fileContent, is(YAMLresult())); + } - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testNodesYAMLfromOXMFileVersionFile() throws IOException { + String outfileName = "testXML.xml"; + File XMLfile = new File(outfileName); + XMLfile.createNewFile(); + BufferedWriter bw = null; + Charset charset = Charset.forName("UTF-8"); + Path path = Paths.get(outfileName); + bw = Files.newBufferedWriter(path, charset); + bw.write(testXML); + bw.close(); + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + fileContent = nodesYamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + XMLfile.delete(); + assertThat("FileContent:\n" + fileContent, fileContent, is(YAMLresult())); } - assertThat("FileContent-I:\n"+fileContent,fileContent, is(YAMLresult())); - } - @Test - public void testNodesYAMLfromOXMFileVersionFile() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testNodesYAMLfromOXMStringVersionFile() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + fileContent = nodesYamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("FileContent-II:\n" + fileContent, fileContent, is(YAMLresult())); } - XMLfile.delete(); - assertThat("FileContent:\n"+fileContent,fileContent, is(YAMLresult())); - } - @Test - public void testNodesYAMLfromOXMStringVersionFile() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - fileContent = nodesYamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testAppendDefinitions() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String definitions = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + nodesYamlFromOxm.process(); + definitions = nodesYamlFromOxm.appendDefinitions(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Definitions:\n" + definitions, definitions, is(YAMLgetDefs())); } - assertThat("FileContent-II:\n"+fileContent,fileContent, is(YAMLresult())); - } - @Test - public void testAppendDefinitions() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String definitions = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - definitions = nodesYamlFromOxm.appendDefinitions(); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testGetXMLRootElementName() { + String target = "RootElement=customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + Element customer = null; + String root = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + nodesYamlFromOxm.process(); + customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); + root = nodesYamlFromOxm.getXMLRootElementName(customer); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("RootElement=" + root, is(target)); } - assertThat("Definitions:\n"+definitions,definitions, is(YAMLgetDefs())); - } - @Test - public void testGetXMLRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - String root = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); - root = nodesYamlFromOxm.getXMLRootElementName(customer); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testGetXmlRootElementName() { + String target = "RootElement=customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String root = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + nodesYamlFromOxm.process(); + root = nodesYamlFromOxm.getXmlRootElementName("Customer"); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("RootElement=" + root, is(target)); } - assertThat("RootElement="+root, is(target)); - } - @Test - public void testGetXmlRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String root = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - root = nodesYamlFromOxm.getXmlRootElementName("Customer"); - } catch(Exception e) { - e.printStackTrace(); + @Test + public void testGetJavaTypeElementSwagger() { + String target = "Element=java-type/Customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + Element customer = null; + try { + nodesYamlFromOxm.setXmlVersion(testXML, v); + nodesYamlFromOxm.process(); + customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Element=" + customer.getNodeName() + "/" + customer.getAttribute("name"), + is(target)); } - assertThat("RootElement="+root, is(target)); - } - @Test - public void testGetJavaTypeElementSwagger() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - try { - nodesYamlFromOxm.setXmlVersion(testXML, v); - nodesYamlFromOxm.process(); - customer = nodesYamlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); + public String YAMLresult() { + StringBuilder sb = new StringBuilder(32368); + sb.append(YAMLheader()); + sb.append(YAMLops()); + sb.append(YAMLgetDefs()); + return sb.toString(); } - 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(YAMLgetDefs()); - return sb.toString(); - } - public String YAMLheader() { - StringBuilder sb = new StringBuilder(1500); + public String YAMLheader() { + StringBuilder sb = new StringBuilder(1500); sb.append("swagger: \"2.0\"\n"); sb.append("info:" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" description: |\n"); sb.append("\n"); - sb.append(" [Differences versus the previous schema version](apidocs/aai/aai_swagger_v11.diff)" + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Copyright © 2017-18 AT&T Intellectual Property. All rights reserved." + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License." + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " [Differences versus the previous schema version](apidocs/aai/aai_swagger_v11.diff)" + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Copyright © 2017-18 AT&T Intellectual Property. All rights reserved." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); sb.append(" You may obtain a copy of the License at\n"); sb.append("\n"); - sb.append(" (https://creativecommons.org/licenses/by/4.0/)" + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."+ OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" This document is best viewed with Firefox or Chrome. Nodes can be found by opening the models link below and finding the node-type. Edge definitions can be found with the node definitions." + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" (https://creativecommons.org/licenses/by/4.0/)" + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " This document is best viewed with Firefox or Chrome. Nodes can be found by opening the models link below and finding the node-type. Edge definitions can be found with the node definitions." + + OxmFileProcessor.LINE_SEPARATOR); sb.append(" version: \"v11\"" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" title: Active and Available Inventory REST API" + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " title: Active and Available Inventory REST API" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" license:" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" name: Apache 2.0" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html" + + OxmFileProcessor.LINE_SEPARATOR); sb.append(" contact:" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" name: n/a" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" url: n/a" + OxmFileProcessor.LINE_SEPARATOR); @@ -274,203 +284,219 @@ public class NodesYAMLfromOXMTest { sb.append("schemes:" + OxmFileProcessor.LINE_SEPARATOR); sb.append(" - https\n"); sb.append("paths:" + OxmFileProcessor.LINE_SEPARATOR); - return sb.toString(); - } + return sb.toString(); + } - public String YAMLops() { - StringBuilder sb = new StringBuilder(16384); - sb.append(" /nodes/customers/customer/{global-customer-id}:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns customer\n"); - sb.append(" description: returns customer\n"); - sb.append(" operationId: getBusinessCustomersCustomer\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" /nodes/customers?parameter=value[¶meter2=value2]:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns customers\n"); - sb.append(" description: returns customers\n"); - sb.append(" operationId: getBusinessCustomers\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customers\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: query\n"); - sb.append(" description: n/a\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/a\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/a\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - sb.append(" /nodes/service-subscriptions/service-subscription/{service-type}:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\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: \"#/definitions/service-subscription\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" /nodes/service-subscriptions?parameter=value[¶meter2=value2]:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Operations\n"); - sb.append(" summary: returns service-subscriptions\n"); - sb.append(" description: returns service-subscriptions\n"); - sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/service-subscriptions\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null\n parameters:\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: query\n"); - sb.append(" description: n/a\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - return sb.toString(); - } + public String YAMLops() { + StringBuilder sb = new StringBuilder(16384); + sb.append(" /nodes/customers/customer/{global-customer-id}:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Operations\n"); + sb.append(" summary: returns customer\n"); + sb.append(" description: returns customer\n"); + sb.append(" operationId: getBusinessCustomersCustomer\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null\n parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" /nodes/customers?parameter=value[¶meter2=value2]:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Operations\n"); + sb.append(" summary: returns customers\n"); + sb.append(" description: returns customers\n"); + sb.append(" operationId: getBusinessCustomers\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/customers\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null\n parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: query\n"); + sb.append(" description: n/a\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/a\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/a\n"); + sb.append(" required: false\n"); + sb.append(" type: string\n"); + sb.append(" /nodes/service-subscriptions/service-subscription/{service-type}:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Operations\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: \"#/definitions/service-subscription\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null\n parameters:\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: path\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __SERVICE-TYPE__\n"); + sb.append(" /nodes/service-subscriptions?parameter=value[¶meter2=value2]:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Operations\n"); + sb.append(" summary: returns service-subscriptions\n"); + sb.append(" description: returns service-subscriptions\n"); + sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/service-subscriptions\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null\n parameters:\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: query\n"); + sb.append(" description: n/a\n"); + sb.append(" required: false\n"); + sb.append(" type: string\n"); + return sb.toString(); + } - public String YAMLgetDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("definitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/business\"\n"); - sb.append(" nodes:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" properties:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" inventory-item-data:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" type: array" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" items:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" $ref: \"#/definitions/inventory-item-data\"" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - return sb.toString(); - } + public String YAMLgetDefs() { + StringBuilder sb = new StringBuilder(8092); + sb.append("definitions:\n"); + sb.append(" business:\n"); + sb.append(" description: |\n"); + sb.append(" Namespace for business related constructs\n"); + sb.append(" properties:\n"); + sb.append(" customers:\n"); + sb.append(" type: array\n"); + sb.append(" items:\n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" customer:\n"); + sb.append(" description: |\n"); + sb.append(" customer identifiers to provide linkage back to BSS information.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); + sb.append(" required:\n"); + sb.append(" - global-customer-id\n"); + sb.append(" - subscriber-name\n"); + sb.append(" - subscriber-type\n"); + sb.append(" properties:\n"); + sb.append(" global-customer-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" subscriber-name:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber name, an alternate way to retrieve a customer.\n"); + sb.append(" subscriber-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); + sb.append(" resource-version:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); + sb.append(" service-subscriptions:\n"); + sb.append(" type: array\n"); + sb.append(" items:\n"); + sb.append(" $ref: \"#/definitions/service-subscription\"\n"); + sb.append(" customers:\n"); + sb.append(" description: |\n"); + sb.append( + " Collection of customer identifiers to provide linkage back to BSS information.\n"); + sb.append(" properties:\n"); + sb.append(" customer:\n"); + sb.append(" type: array\n"); + sb.append(" items: \n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" inventory:\n"); + sb.append(" properties:\n"); + sb.append(" business:\n"); + sb.append(" type: object\n"); + sb.append(" $ref: \"#/definitions/business\"\n"); + sb.append(" nodes:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" properties:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" inventory-item-data:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" type: array" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" items:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" $ref: \"#/definitions/inventory-item-data\"" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" service-subscription:\n"); + sb.append(" description: |\n"); + sb.append(" Object that group service instances.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); + sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); + sb.append( + " - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append( + " -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); + sb.append( + " -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); + sb.append(" required:\n"); + sb.append(" - service-type\n"); + sb.append(" properties:\n"); + sb.append(" service-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" temp-ub-sub-account-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); + sb.append(" resource-version:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); + sb.append(" service-subscriptions:\n"); + sb.append(" description: |\n"); + sb.append(" Collection of objects that group service instances.\n"); + sb.append(" properties:\n"); + sb.append(" service-subscription:\n"); + sb.append(" type: array\n"); + sb.append(" items: \n"); + sb.append(" $ref: \"#/definitions/service-subscription\"\n"); + return sb.toString(); + } } - diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PatchOperationTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PatchOperationTest.java index 098b33b..d939a74 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PatchOperationTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PatchOperationTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; + import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,58 +33,62 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.onap.aai.setup.SchemaVersion; -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; - private static SchemaVersion v = new SchemaVersion("v16"); + private String useOpId; + private String xmlRootElementName; + private String tag; + private String path; + private String pathParams; + private String result; + private static SchemaVersion v = new SchemaVersion("v16"); + + @Parameters + public static Collection testConditions() { + String inputs[][] = {{"NetworkGenericVnfsGenericVnf", "generic-vnf", "Network", + "/network/generic-vnfs/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + " patch:\n tags:\n - Network\n summary: update an existing generic-vnf\n description: |\n Update an existing generic-vnf\n #\n Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n The PUT operation will entirely replace an existing object.\n The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n #\n Other differences between PUT and PATCH are:\n #\n - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n operationId: UpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n produces:\n - application/json\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be updated.[See Examples](apidocs/aai/relations/v16/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"}, + // if ( StringUtils.isEmpty(tag) ) + {"GenericVnf", "generic-vnf", "", "/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + ""}, + // Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) + {"CloudInfrastructurePserversPserverPInterfaces", "p-interfaces", "CloudInfrastructure", + "/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces", + " - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__", + ""}, + // {"","ctag-pool","","","",""}, + // {"","pserver","","","",""}, + // {"","oam-network","","","",""}, + // {"","dvs-switch","","","",""}, + // {"","availability-zone","","","",""} + }; + return Arrays.asList(inputs); + } - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," patch:\n tags:\n - Network\n summary: update an existing generic-vnf\n description: |\n Update an existing generic-vnf\n #\n Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n The PUT operation will entirely replace an existing object.\n The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n #\n Other differences between PUT and PATCH are:\n #\n - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n operationId: UpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n produces:\n - application/json\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be updated.[See Examples](apidocs/aai/relations/v16/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } + public 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; + } - 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 { + @BeforeClass + public static void setUpBeforeClass() throws Exception { - } + } - @Test - public void testToString() { - PatchOperation patch = new PatchOperation(useOpId, xmlRootElementName, tag, path, pathParams, v, "/aai" ); - String modResult = patch.toString(); - assertThat(modResult, is(this.result)); - } + @Test + public void testToString() { + PatchOperation patch = + new PatchOperation(useOpId, xmlRootElementName, tag, path, pathParams, v, "/aai"); + String modResult = patch.toString(); + assertThat(modResult, is(this.result)); + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutOperationTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutOperationTest.java index 7c5c00d..c5b9408 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutOperationTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutOperationTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; + import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,58 +33,64 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.onap.aai.setup.SchemaVersion; -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 SchemaVersion v = new SchemaVersion("v14"); + private String useOpId; + private String xmlRootElementName; + private String tag; + private String path; + private String pathParams; + private String result; + private static SchemaVersion v = new SchemaVersion("v14"); + + @Parameters + public static Collection testConditions() { + String inputs[][] = {{"NetworkGenericVnfsGenericVnf", "generic-vnf", "Network", + "/network/generic-vnfs/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + " put:\n tags:\n - Network\n summary: create or update an existing generic-vnf\n description: |\n Create or update an existing generic-vnf.\n #\n Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n operationId: createOrUpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/" + + v.toString() + + "/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"}, + // if ( StringUtils.isEmpty(tag) ) + {"GenericVnf", "generic-vnf", "", "/generic-vnf/{vnf-id}", + " - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__", + ""}, + // Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) + {"CloudInfrastructurePserversPserverPInterfaces", "p-interfaces", "CloudInfrastructure", + "/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces", + " - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__", + ""}, + // {"","ctag-pool","","","",""}, + // {"","pserver","","","",""}, + // {"","oam-network","","","",""}, + // {"","dvs-switch","","","",""}, + // {"","availability-zone","","","",""} + }; + return Arrays.asList(inputs); + } - @Parameters - public static Collection testConditions() { - String inputs [][] = { - {"NetworkGenericVnfsGenericVnf","generic-vnf","Network","/network/generic-vnfs/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__"," put:\n tags:\n - Network\n summary: create or update an existing generic-vnf\n description: |\n Create or update an existing generic-vnf.\n #\n Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n operationId: createOrUpdateNetworkGenericVnfsGenericVnf\n consumes:\n - application/json\n - application/xml\n produces:\n - application/json\n - application/xml\n responses:\n \"default\":\n null parameters:\n - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__ - name: body\n in: body\n description: generic-vnf object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/"+v.toString()+"/NetworkGenericVnfsGenericVnf.json)\n required: true\n schema:\n $ref: \"#/definitions/generic-vnf\"\n"}, -// if ( StringUtils.isEmpty(tag) ) - {"GenericVnf","generic-vnf","","/generic-vnf/{vnf-id}"," - name: vnf-id\n in: path\n description: Unique id of VNF. This is unique across the graph.\n required: true\n type: string\n example: __VNF-ID__",""}, -// Test: if ( !path.endsWith("/relationship") && !path.endsWith("}") ) - {"CloudInfrastructurePserversPserverPInterfaces","p-interfaces","CloudInfrastructure","/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces"," - name: hostname\n in: path\n description: Value from executing hostname on the compute node.\n required: true\n type: string\n example: __HOSTNAME__",""}, - // {"","ctag-pool","","","",""}, -// {"","pserver","","","",""}, -// {"","oam-network","","","",""}, -// {"","dvs-switch","","","",""}, -// {"","availability-zone","","","",""} - }; - return Arrays.asList(inputs); - } + public PutOperationTest(String useOpId, String xmlRootElementName, String tag, String path, + String pathParams, String result) { + super(); + this.useOpId = useOpId; + this.xmlRootElementName = xmlRootElementName; + this.tag = tag; + this.path = path; + this.pathParams = pathParams; + this.result = result; + } - 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 { + @BeforeClass + public static void setUpBeforeClass() throws Exception { - } + } - @Test - public void testToString() { - PutOperation put = new PutOperation(useOpId, xmlRootElementName, tag, path, pathParams, v, "/aai"); - String modResult = put.toString(); - assertThat(modResult, is(this.result)); - } + @Test + public void testToString() { + PutOperation put = + new PutOperation(useOpId, xmlRootElementName, tag, path, pathParams, v, "/aai"); + String modResult = put.toString(); + assertThat(modResult, is(this.result)); + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutRelationPathSetTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutRelationPathSetTest.java index 526c923..09a8dd4 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutRelationPathSetTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/PutRelationPathSetTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; + import org.junit.AfterClass; import org.junit.Before; import org.junit.Ignore; @@ -33,225 +42,168 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaVersions.class, - EdgeIngestor.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai" -}) +@ContextConfiguration(classes = {SchemaVersions.class, EdgeIngestor.class}) +@TestPropertySource(properties = {"schema.uri.base.path = /aai"}) @Ignore("This test needs to get major rework done as it is written very poorly") public class PutRelationPathSetTest { - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; - - private static String json; - private SchemaVersion v ; - private File relationsFile ; - private String target = "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; - private String opId = "createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZoneRelationshipListRelationship"; - private String path = "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; - PutRelationPathSet prp = null; - @Autowired - SchemaVersions schemaVersions; - - @Autowired - EdgeIngestor edgeIngestor; - - - @Before - public void setUpBeforeClass() throws Exception { - v = schemaVersions.getDefaultVersion(); - - relationsFile = new File(GenerateXsd.getYamlDir() + "/relations/" + v.toString()+"/createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZone.json"); - json = "{" - + " \"rules\": [" - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"complex\"," - + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"this description\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"service-capability\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"availability-zone\"," - + " \"to\": \"cloud-region\"," - + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"!${direction}\"," - + " \"delete-other-v\": \"!${direction}\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"NONE\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"ctag-pool\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"dvs-switch\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"generic-vnf\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vf-module\"," - + " \"to\": \"vnfc\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"ONE2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"pserver\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2ONE\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"${direction}\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " {" - + " \"from\": \"vce\"," - + " \"to\": \"availability-zone\"," - + " \"label\": \"org.onap.relationships.inventory.Uses\"," - + " \"direction\": \"OUT\"," - + " \"multiplicity\": \"MANY2MANY\"," - + " \"contains-other-v\": \"NONE\"," - + " \"delete-other-v\": \"NONE\"," - + " \"SVC-INFRA\": \"NONE\"," - + " \"prevent-delete\": \"!${direction}\"," - + " \"default\": \"true\"," - + " \"description\":\"\"" - + " }," - + " ]}"; - - BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw.write(json); - bw.close(); - - } - - @Before - public void setUp() throws Exception { - - DeleteOperation.deletePaths.put("/cloud-infrastructure/pservers/pserver/{hostname}","pserver"); - DeleteOperation.deletePaths.put("/network/vces/vce/{vnf-id}","vce"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/complexes/complex/{physical-location-id}","complex"); - DeleteOperation.deletePaths.put("/service-design-and-creation/service-capabilities/service-capability/{service-type}/{vnf-type}","service-capability"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}","cloud-region"); - DeleteOperation.deletePaths.put("/network/generic-vnfs/generic-vnf/{vnf-id}","generic-vnf"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/dvs-switches/dvs-switch/{switch-name}","dvs-switch"); - DeleteOperation.deletePaths.put("/cloud-infrastructure/complexes/complex/{physical-location-id}/ctag-pools/ctag-pool/{target-pe}/{availability-zone-name}","ctag-pool"); - - DeleteOperation.deletePaths.put(path.replace("/relationship-list/relationship", ""),"availability-zone"); - PutRelationPathSet.add(opId, path); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - File edges = new File(EDGEFILENAME); - edges.delete(); - } - @Test - public void testAdd() { - PutRelationPathSet.add(opId, path); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); - } - - @Test - public void testPutRelationPathSet() { - - this.prp = new PutRelationPathSet(v); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - prp.generateRelations(edgeIngestor); - assertTrue(this.relationsFile.exists()); - this.relationsFile.delete(); - } - - @Test - public void testPutRelationPathSetStringString() { - this.prp = new PutRelationPathSet(opId, path, v); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - } - - @Test - public void testGenerateRelations() { - PutRelationPathSet prp = new PutRelationPathSet(opId, "availability-zone", v); - prp.generateRelations(edgeIngestor); - assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); - assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); - assertTrue(this.relationsFile.exists()); -// this.relationsFile.delete(); - } + private static final String EDGEFILENAME = + "src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"; + + private static String json; + private SchemaVersion v; + private File relationsFile; + private String target = + "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; + private String opId = + "createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZoneRelationshipListRelationship"; + private String path = + "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/availability-zones/availability-zone/{availability-zone-name}/relationship-list/relationship"; + PutRelationPathSet prp = null; + @Autowired + SchemaVersions schemaVersions; + + @Autowired + EdgeIngestor edgeIngestor; + + @Before + public void setUpBeforeClass() throws Exception { + v = schemaVersions.getDefaultVersion(); + + relationsFile = new File(GenerateXsd.getYamlDir() + "/relations/" + v.toString() + + "/createOrUpdateCloudInfrastructureCloudRegionsCloudRegionAvailabilityZonesAvailabilityZone.json"); + json = "{" + " \"rules\": [" + " {" + " \"from\": \"availability-zone\"," + + " \"to\": \"complex\"," + + " \"label\": \"org.onap.relationships.inventory.LocatedIn\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"this description\"" + + " }," + " {" + " \"from\": \"availability-zone\"," + + " \"to\": \"service-capability\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " {" + + " \"from\": \"availability-zone\"," + " \"to\": \"cloud-region\"," + + " \"label\": \"org.onap.relationships.inventory.BelongsTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"!${direction}\"," + + " \"delete-other-v\": \"!${direction}\"," + " \"SVC-INFRA\": \"NONE\"," + + " \"prevent-delete\": \"NONE\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"ctag-pool\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " {" + + " \"from\": \"dvs-switch\"," + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.AppliesTo\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " {" + + " \"from\": \"generic-vnf\"," + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.Uses\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"${direction}\"," + + " \"prevent-delete\": \"!${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"vf-module\"," + + " \"to\": \"vnfc\"," + + " \"label\": \"org.onap.relationships.inventory.Uses\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"ONE2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"${direction}\"," + + " \"prevent-delete\": \"${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"pserver\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.MemberOf\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2ONE\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"${direction}\"," + + " \"prevent-delete\": \"!${direction}\"," + " \"default\": \"true\"," + + " \"description\":\"\"" + " }," + " {" + " \"from\": \"vce\"," + + " \"to\": \"availability-zone\"," + + " \"label\": \"org.onap.relationships.inventory.Uses\"," + + " \"direction\": \"OUT\"," + " \"multiplicity\": \"MANY2MANY\"," + + " \"contains-other-v\": \"NONE\"," + " \"delete-other-v\": \"NONE\"," + + " \"SVC-INFRA\": \"NONE\"," + " \"prevent-delete\": \"!${direction}\"," + + " \"default\": \"true\"," + " \"description\":\"\"" + " }," + " ]}"; + + BufferedWriter bw = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw.write(json); + bw.close(); + + } + + @Before + public void setUp() throws Exception { + + DeleteOperation.deletePaths.put("/cloud-infrastructure/pservers/pserver/{hostname}", + "pserver"); + DeleteOperation.deletePaths.put("/network/vces/vce/{vnf-id}", "vce"); + DeleteOperation.deletePaths + .put("/cloud-infrastructure/complexes/complex/{physical-location-id}", "complex"); + DeleteOperation.deletePaths.put( + "/service-design-and-creation/service-capabilities/service-capability/{service-type}/{vnf-type}", + "service-capability"); + DeleteOperation.deletePaths.put( + "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}", + "cloud-region"); + DeleteOperation.deletePaths.put("/network/generic-vnfs/generic-vnf/{vnf-id}", + "generic-vnf"); + DeleteOperation.deletePaths.put( + "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}/dvs-switches/dvs-switch/{switch-name}", + "dvs-switch"); + DeleteOperation.deletePaths.put( + "/cloud-infrastructure/complexes/complex/{physical-location-id}/ctag-pools/ctag-pool/{target-pe}/{availability-zone-name}", + "ctag-pool"); + + DeleteOperation.deletePaths.put(path.replace("/relationship-list/relationship", ""), + "availability-zone"); + PutRelationPathSet.add(opId, path); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + File edges = new File(EDGEFILENAME); + edges.delete(); + } + + @Test + public void testAdd() { + PutRelationPathSet.add(opId, path); + assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); + assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); + } + + @Test + public void testPutRelationPathSet() { + + this.prp = new PutRelationPathSet(v); + assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); + prp.generateRelations(edgeIngestor); + assertTrue(this.relationsFile.exists()); + this.relationsFile.delete(); + } + + @Test + public void testPutRelationPathSetStringString() { + this.prp = new PutRelationPathSet(opId, path, v); + assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); + } + + @Test + public void testGenerateRelations() { + PutRelationPathSet prp = new PutRelationPathSet(opId, "availability-zone", v); + prp.generateRelations(edgeIngestor); + assertThat(PutRelationPathSet.putRelationPaths.size(), is(1)); + assertThat(PutRelationPathSet.putRelationPaths.get(opId), is(target)); + assertTrue(this.relationsFile.exists()); + // this.relationsFile.delete(); + } } - - diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDElementTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDElementTest.java index 7c8dd78..7ce87af 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDElementTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDElementTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +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.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.io.StringReader; +import java.util.*; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.BeforeClass; @@ -31,625 +48,721 @@ 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.*; +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; + } -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.assertEquals; -import static org.junit.Assert.assertThat; + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } -public class XSDElementTest { - private static final Logger logger = LoggerFactory.getLogger("XSDElementTest.class"); - private static final int maxSizeForXml = 20000; - protected String testXML; - protected Document doc = null; - protected NodeList javaTypeNodes=null; - - public String getTestXML() { - return testXML; - } - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - setUp(0); - } - - public void setUp( int sbopt ) throws Exception { - StringBuilder sb = new StringBuilder(maxSizeForXml); - addNamespace(sb); - addBusiness(sb); - addCustomers(sb); - if ( sbopt == 0 ) { - addCustomer(sb); - } else { - addCustomerNoSubscriberType(sb); - addCustomerSubscriberType(sb); + @Before + public void setUp() throws Exception { + setUp(0); + } + + public void setUp(int sbopt) throws Exception { + StringBuilder sb = new StringBuilder(maxSizeForXml); + addNamespace(sb); + addBusiness(sb); + addCustomers(sb); + if (sbopt == 0) { + addCustomer(sb); + } else { + addCustomerNoSubscriberType(sb); + addCustomerSubscriberType(sb); + } + addServiceSubscriptions(sb); + addServiceSubscription(sb); + addEndOfXML(sb); + testXML = sb.toString(); + init(); + } + + public void setUpRelationship() throws Exception { + StringBuilder sb = new StringBuilder(maxSizeForXml); + addNamespaceNoInventory(sb); + addRelationship(sb); + addRelationshipList(sb); + addRelatedToProperty(sb); + addRelationshipData(sb); + addEndOfXML(sb); + testXML = sb.toString(); + init(); + } + + private void addNamespace(StringBuilder sb) { + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + } + + private void addNamespaceNoInventory(StringBuilder sb) { + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); } - addServiceSubscriptions(sb); - addServiceSubscription(sb); - addEndOfXML(sb); - testXML = sb.toString(); - init(); - } - - public void setUpRelationship( ) throws Exception { - StringBuilder sb = new StringBuilder(maxSizeForXml); - addNamespaceNoInventory(sb); - addRelationship(sb); - addRelationshipList(sb); - addRelatedToProperty(sb); - addRelationshipData(sb); - addEndOfXML(sb); - testXML = sb.toString(); - init(); - } - - private void addNamespace(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addNamespaceNoInventory(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addBusiness(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); + + private void addBusiness(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); sb.append("\n"); sb.append("\n"); sb.append("\n"); - sb.append("\n"); + sb.append( + "\n"); sb.append("\n"); sb.append("\n"); - } - - private void addCustomers(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomer(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); -// sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomerNoSubscriberType(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addCustomerSubscriberType(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addServiceSubscriptions(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - private void addServiceSubscription(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); -// sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationshipList(StringBuilder sb ) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("/n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationship(StringBuilder sb ) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append(""); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelatedToProperty(StringBuilder sb) { - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - private void addRelationshipData(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - } - - - private void addEndOfXML(StringBuilder sb){ - sb.append("\n"); - sb.append("\n"); - } - - public void init() throws ParserConfigurationException, SAXException, IOException { - 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; + + private void addCustomers(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + } + + private void addCustomer(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + // sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); } - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; + private void addCustomerNoSubscriberType(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + } - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - throw new SAXException("OXM file error: missing in XML"); + private void addCustomerSubscriberType(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); } - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - throw new SAXException("OXM file error: missing in XML"); + private void addServiceSubscriptions(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); } - javaTypesElement = (Element) javaTypesNodes.item(0); - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - throw new SAXException("OXM file error: missing in XML"); + private void addServiceSubscription(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + // sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); } - logger.debug(testXML); - } - @Test - public void testXSDElement() { - // repeat of testGetIndexedProps() which uses the constructor - ArrayList target = new ArrayList(); - target.add("subscriber-name"); - target.add("global-customer-id"); - target.add("subscriber-type"); - target.add("service-type"); - - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - indexedProps.addAll(javaTypeElement.getIndexedProps()); + + private void addRelationshipList(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "/n"); + sb.append("\n"); + sb.append("\n"); } - assertThat(new ArrayList<>(indexedProps),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testName() { - ArrayList target = new ArrayList(); - target.add("ServiceSubscriptions"); - target.add("ServiceSubscription"); - target.add("Inventory"); - target.add("Business"); - target.add("Customers"); - target.add("Customer"); - ArrayList names = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - names.add(javaTypeElement.name()); + + private void addRelationship(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append(""); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); } - logger.debug(String.join("|", names)); - assertThat(names,both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetAddTypes() { - HashMap> map = new HashMap>(); - HashMap> target = new HashMap>(); - target.put("Customer", new ArrayList<>(Arrays.asList("ServiceSubscriptions", "RelationshipList"))); - target.put("Customer", new ArrayList<>(Arrays.asList("ServiceSubscriptions"))); - target.put("Business", new ArrayList<>(Arrays.asList("Customers"))); - target.put("Inventory", new ArrayList<>(Arrays.asList("Business"))); - target.put("Customers", new ArrayList<>(Arrays.asList("Customer"))); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList("RelationshipList"))); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList())); - target.put("ServiceSubscriptions", new ArrayList<>(Arrays.asList("ServiceSubscription"))); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList addTypes = new ArrayList(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - String name=javaTypeElement.name(); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - addTypes.addAll(xmlElement.getAddTypes("v11")); - map.put(name,addTypes); - } + + private void addRelatedToProperty(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); } - for(String key : map.keySet()) { - assertThat("Expected for key:"+key, map.get(key),equalTo(target.get(key))); + + private void addRelationshipData(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append( + "\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); } - } -/* - @Test - public void testGetRequiredElements() { - HashMap> map = new HashMap>(); - ArrayList target = new ArrayList(); - target.add("global-customer-id\n"); - target.add("subscriber-name\n"); - target.add("subscriber-type"); - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList requiredItems = new ArrayList(); - String name=javaTypeElement.name(); - requiredItems.addAll(javaTypeElement.getRequiredElements("v11")); - map.put(name,requiredItems); + + private void addEndOfXML(StringBuilder sb) { + sb.append("\n"); + sb.append("\n"); } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target)); + + public void init() throws ParserConfigurationException, SAXException, IOException { + 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 SAXException("OXM file error: missing in XML"); + } + + bindingElement = (Element) bindingsNodes.item(0); + javaTypesNodes = bindingElement.getElementsByTagName("java-types"); + if (javaTypesNodes.getLength() < 1) { + throw new SAXException("OXM file error: missing in XML"); + } + javaTypesElement = (Element) javaTypesNodes.item(0); + + javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); + if (javaTypeNodes.getLength() < 1) { + throw new SAXException( + "OXM file error: missing in XML"); + } + logger.debug(testXML); } - } -*/ - @Test - public void testGetPathDescriptionProperty() { - ArrayList target = new ArrayList(); - target.add("Namespace for business related constructs"); - target.add("Collection of customer identifiers to provide linkage back to BSS information."); - target.add("customer identifiers to provide linkage back to BSS information."); - target.add("Collection of objects that group service instances."); - target.add("Object that group service instances."); - List descs = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getPathDescriptionProperty() != null) - descs.add(javaTypeElement.getPathDescriptionProperty()); + + @Test + public void testXSDElement() { + // repeat of testGetIndexedProps() which uses the constructor + ArrayList target = new ArrayList(); + target.add("subscriber-name"); + target.add("global-customer-id"); + target.add("subscriber-type"); + target.add("service-type"); + + Vector indexedProps = new Vector(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + indexedProps.addAll(javaTypeElement.getIndexedProps()); + } + assertThat(new ArrayList<>(indexedProps), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } - logger.debug(String.join("|", descs)); - assertThat(new ArrayList<>(descs),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetIndexedProps() { - ArrayList target = new ArrayList(); - target.add("subscriber-name"); - target.add("global-customer-id"); - target.add("subscriber-type"); - target.add("service-type"); - - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - indexedProps.addAll(javaTypeElement.getIndexedProps()); + + @Test + public void testName() { + ArrayList target = new ArrayList(); + target.add("ServiceSubscriptions"); + target.add("ServiceSubscription"); + target.add("Inventory"); + target.add("Business"); + target.add("Customers"); + target.add("Customer"); + ArrayList names = new ArrayList(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + names.add(javaTypeElement.name()); + } + logger.debug(String.join("|", names)); + assertThat(names, + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } - assertThat(new ArrayList<>(indexedProps),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetContainerProperty() { - ArrayList target = new ArrayList(); - target.add("service-subscriptions"); - target.add("customers"); - List containers = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getContainerProperty() != null) - containers.add(javaTypeElement.getContainerProperty()); + + @Test + public void testGetAddTypes() { + HashMap> map = new HashMap>(); + HashMap> target = new HashMap>(); + target.put("Customer", + new ArrayList<>(Arrays.asList("ServiceSubscriptions", "RelationshipList"))); + target.put("Customer", new ArrayList<>(Arrays.asList("ServiceSubscriptions"))); + target.put("Business", new ArrayList<>(Arrays.asList("Customers"))); + target.put("Inventory", new ArrayList<>(Arrays.asList("Business"))); + target.put("Customers", new ArrayList<>(Arrays.asList("Customer"))); + target.put("ServiceSubscription", new ArrayList<>(Arrays.asList("RelationshipList"))); + target.put("ServiceSubscription", new ArrayList<>(Arrays.asList())); + target.put("ServiceSubscriptions", new ArrayList<>(Arrays.asList("ServiceSubscription"))); + + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + ArrayList addTypes = new ArrayList(); + NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); + String name = javaTypeElement.name(); + for (int j = 0; j < xmlElementNodes.getLength(); ++j) { + XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); + addTypes.addAll(xmlElement.getAddTypes("v11")); + map.put(name, addTypes); + } + } + for (String key : map.keySet()) { + assertThat("Expected for key:" + key, map.get(key), equalTo(target.get(key))); + } } - logger.debug(String.join("|", containers)); - assertThat(new ArrayList<>(containers),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetQueryParamYAML() { - ArrayList target = new ArrayList(); - target.add(" - name: global-customer-id\n in: query\n description: n/a\n required: false\n type: string\n"); - target.add(" - name: subscriber-name\n in: query\n description: n/a\n required: false\n type: string\n"); - target.add(" - name: subscriber-type\n in: query\n description: n/a\n required: false\n type: string\n"); - Vector indexedProps = new Vector(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getContainerProperty() != null) { - indexedProps.addAll(javaTypeElement.getIndexedProps()); - String container = javaTypeElement.getContainerProperty(); - Vector containerProps = new Vector(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - if(indexedProps.contains(xmlElement.name())) - containerProps.add(xmlElement.getQueryParamYAML()); + + /* + * @Test + * public void testGetRequiredElements() { + * HashMap> map = new HashMap>(); + * ArrayList target = new ArrayList(); + * target.add("global-customer-id\n"); + * target.add("subscriber-name\n"); + * target.add("subscriber-type"); + * for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { + * XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + * ArrayList requiredItems = new ArrayList(); + * String name=javaTypeElement.name(); + * requiredItems.addAll(javaTypeElement.getRequiredElements("v11")); + * map.put(name,requiredItems); + * } + * for(String key : map.keySet()) { + * assertThat(map.get(key),equalTo(target)); + * } + * } + */ + @Test + public void testGetPathDescriptionProperty() { + ArrayList target = new ArrayList(); + target.add("Namespace for business related constructs"); + target + .add("Collection of customer identifiers to provide linkage back to BSS information."); + target.add("customer identifiers to provide linkage back to BSS information."); + target.add("Collection of objects that group service instances."); + target.add("Object that group service instances."); + List descs = new ArrayList(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (javaTypeElement.getPathDescriptionProperty() != null) + descs.add(javaTypeElement.getPathDescriptionProperty()); } - GetOperation.addContainerProps(container, containerProps); - } + logger.debug(String.join("|", descs)); + assertThat(new ArrayList<>(descs), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } -/* - List queryParams = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getQueryParamYAML() != null) - queryParams.add(javaTypeElement.getQueryParamYAML()); + + @Test + public void testGetIndexedProps() { + ArrayList target = new ArrayList(); + target.add("subscriber-name"); + target.add("global-customer-id"); + target.add("subscriber-type"); + target.add("service-type"); + + Vector indexedProps = new Vector(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + indexedProps.addAll(javaTypeElement.getIndexedProps()); + } + assertThat(new ArrayList<>(indexedProps), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } -*/ - assertThat(GetOperation.containers.get("customers"),equalTo( target)); - } - - @Test - public void testGetPathParamYAML() { - ArrayList target = new ArrayList(); - target.add(" - name: Inventory\n in: path\n description: Inventory\n required: true\n example: __INVENTORY__\n"); - target.add(" - name: Business\n in: path\n description: Business\n required: true\n example: __BUSINESS__\n"); - target.add(" - name: Customers\n in: path\n description: Customers\n required: true\n example: __CUSTOMERS__\n"); - target.add(" - name: Customer\n in: path\n description: Customer\n required: true\n example: __CUSTOMER__\n"); - target.add(" - name: ServiceSubscriptions\n in: path\n description: ServiceSubscriptions\n required: true\n example: __SERVICESUBSCRIPTIONS__\n"); - target.add(" - name: ServiceSubscription\n in: path\n description: ServiceSubscription\n required: true\n example: __SERVICESUBSCRIPTION__\n"); - List pathParams = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getPathParamYAML(javaTypeElement.name()) != null) - pathParams.add(javaTypeElement.getPathParamYAML(javaTypeElement.name())); + + @Test + public void testGetContainerProperty() { + ArrayList target = new ArrayList(); + target.add("service-subscriptions"); + target.add("customers"); + List containers = new ArrayList(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (javaTypeElement.getContainerProperty() != null) + containers.add(javaTypeElement.getContainerProperty()); + } + logger.debug(String.join("|", containers)); + assertThat(new ArrayList<>(containers), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } - logger.debug(String.join("|", pathParams)); - assertThat(new ArrayList<>(pathParams),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - } - - @Test - public void testGetHTMLAnnotation() { - ArrayList target = new ArrayList(); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR + " " + OxmFileProcessor.LINE_SEPARATOR); - List annotes = new ArrayList(); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(StringUtils.isNotEmpty(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(),""))) - annotes.add(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(), " ")); + + @Test + public void testGetQueryParamYAML() { + ArrayList target = new ArrayList(); + target.add( + " - name: global-customer-id\n in: query\n description: n/a\n required: false\n type: string\n"); + target.add( + " - name: subscriber-name\n in: query\n description: n/a\n required: false\n type: string\n"); + target.add( + " - name: subscriber-type\n in: query\n description: n/a\n required: false\n type: string\n"); + Vector indexedProps = new Vector(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (javaTypeElement.getContainerProperty() != null) { + indexedProps.addAll(javaTypeElement.getIndexedProps()); + String container = javaTypeElement.getContainerProperty(); + Vector containerProps = new Vector(); + NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); + for (int j = 0; j < xmlElementNodes.getLength(); ++j) { + XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); + if (indexedProps.contains(xmlElement.name())) + containerProps.add(xmlElement.getQueryParamYAML()); + } + GetOperation.addContainerProps(container, containerProps); + } + } + /* + * List queryParams = new ArrayList(); + * for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + * XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + * if(javaTypeElement.getQueryParamYAML() != null) + * queryParams.add(javaTypeElement.getQueryParamYAML()); + * } + */ + assertThat(GetOperation.containers.get("customers"), equalTo(target)); } - logger.debug("result:"); - logger.debug(String.join("|", annotes)); - logger.debug("Expected:"); - logger.debug(String.join("|", target)); - assertThat(new ArrayList<>(annotes),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - - } - - @Test - public void testGetTypePropertyYAML() { - ArrayList target = new ArrayList(); - target.add(" Inventory:\n type: "); - target.add(" Business:\n type: description: Namespace for business related constructs\n"); - target.add(" Customers:\n type: description: Collection of customer identifiers to provide linkage back to BSS information.\n"); - target.add(" Customer:\n type: description: customer identifiers to provide linkage back to BSS information.\n"); - target.add(" ServiceSubscriptions:\n type: description: Collection of objects that group service instances.\n"); - target.add(" ServiceSubscription:\n type: description: Object that group service instances.\n"); - StringBuilder sb = new StringBuilder(" Customer:\n type: description: |\n customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" *This property can be used as a filter to find the start node for a dsl query\n"); - String yamlDesc = sb.toString(); - List types = new ArrayList(); - String container; - String customerDesc = null; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - if(javaTypeElement.getTypePropertyYAML(false) != null) - types.add(javaTypeElement.getTypePropertyYAML(false)); - container = javaTypeElement.getContainerProperty(); - if ( "customers".equals(container)) { - customerDesc = javaTypeElement.getTypePropertyYAML(true); - } + + @Test + public void testGetPathParamYAML() { + ArrayList target = new ArrayList(); + target.add( + " - name: Inventory\n in: path\n description: Inventory\n required: true\n example: __INVENTORY__\n"); + target.add( + " - name: Business\n in: path\n description: Business\n required: true\n example: __BUSINESS__\n"); + target.add( + " - name: Customers\n in: path\n description: Customers\n required: true\n example: __CUSTOMERS__\n"); + target.add( + " - name: Customer\n in: path\n description: Customer\n required: true\n example: __CUSTOMER__\n"); + target.add( + " - name: ServiceSubscriptions\n in: path\n description: ServiceSubscriptions\n required: true\n example: __SERVICESUBSCRIPTIONS__\n"); + target.add( + " - name: ServiceSubscription\n in: path\n description: ServiceSubscription\n required: true\n example: __SERVICESUBSCRIPTION__\n"); + List pathParams = new ArrayList(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (javaTypeElement.getPathParamYAML(javaTypeElement.name()) != null) + pathParams.add(javaTypeElement.getPathParamYAML(javaTypeElement.name())); + } + logger.debug(String.join("|", pathParams)); + assertThat(new ArrayList<>(pathParams), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); } - assertThat(new ArrayList<>(types),both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); - assertEquals(customerDesc, yamlDesc ); - } - - @Test - public void testIsStandardType() { - HashMap> map = new HashMap>(); - HashMap> target = new HashMap>(); - target.put("Customer", new ArrayList<>(Arrays.asList("global-customer-id","subscriber-name", "subscriber-type","resource-version"))); - target.put("Business", new ArrayList<>()); - target.put("Inventory", new ArrayList<>()); - target.put("Customers", new ArrayList<>()); - target.put("ServiceSubscriptions", new ArrayList<>()); - target.put("ServiceSubscription", new ArrayList<>(Arrays.asList("service-type", "temp-ub-sub-account-id", "resource-version"))); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - ArrayList addTypes = new ArrayList(); - NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); - String name=javaTypeElement.name(); - for ( int j = 0; j < xmlElementNodes.getLength(); ++j ) { - XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); - if(xmlElement.isStandardType()) - addTypes.add(xmlElement.name()); - } - map.put(name,addTypes); + + @Test + public void testGetHTMLAnnotation() { + ArrayList target = new ArrayList(); + target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + + " @org.onap.aai.annotations.Metadata(description=\"Namespace for business related constructs\")" + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR); + target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + + " @org.onap.aai.annotations.Metadata(description=\"Collection of customer identifiers to provide linkage back to BSS information.\")" + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR); + target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + + " @org.onap.aai.annotations.Metadata(description=\"customer identifiers to provide linkage back to BSS information.\",nameProps=\"subscriber-name\",indexedProps=\"subscriber-name,global-customer-id,subscriber-type\",searchable=\"global-customer-id,subscriber-name\",uniqueProps=\"global-customer-id\",container=\"customers\",namespace=\"business\")" + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR); + target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + + " @org.onap.aai.annotations.Metadata(description=\"Collection of objects that group service instances.\")" + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR); + target.add(" " + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + + " @org.onap.aai.annotations.Metadata(description=\"Object that group service instances.\",indexedProps=\"service-type\",dependentOn=\"customer\",container=\"service-subscriptions\",crossEntityReference=\"service-instance,service-type\")" + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR + " " + + OxmFileProcessor.LINE_SEPARATOR); + List annotes = new ArrayList(); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (StringUtils + .isNotEmpty(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(), ""))) + annotes.add(javaTypeElement.getHTMLAnnotation(javaTypeElement.name(), " ")); + } + logger.debug("result:"); + logger.debug(String.join("|", annotes)); + logger.debug("Expected:"); + logger.debug(String.join("|", target)); + assertThat(new ArrayList<>(annotes), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); + } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target.get(key))); + + @Test + public void testGetTypePropertyYAML() { + ArrayList target = new ArrayList(); + target.add(" Inventory:\n type: "); + target.add( + " Business:\n type: description: Namespace for business related constructs\n"); + target.add( + " Customers:\n type: description: Collection of customer identifiers to provide linkage back to BSS information.\n"); + target.add( + " Customer:\n type: description: customer identifiers to provide linkage back to BSS information.\n"); + target.add( + " ServiceSubscriptions:\n type: description: Collection of objects that group service instances.\n"); + target.add( + " ServiceSubscription:\n type: description: Object that group service instances.\n"); + StringBuilder sb = new StringBuilder( + " Customer:\n type: description: |\n customer identifiers to provide linkage back to BSS information.\n"); + sb.append( + " *This property can be used as a filter to find the start node for a dsl query\n"); + String yamlDesc = sb.toString(); + List types = new ArrayList(); + String container; + String customerDesc = null; + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + if (javaTypeElement.getTypePropertyYAML(false) != null) + types.add(javaTypeElement.getTypePropertyYAML(false)); + container = javaTypeElement.getContainerProperty(); + if ("customers".equals(container)) { + customerDesc = javaTypeElement.getTypePropertyYAML(true); + } + } + assertThat(new ArrayList<>(types), + both(everyItem(is(in(target.toArray())))).and(containsInAnyOrder(target.toArray()))); + assertEquals(customerDesc, yamlDesc); } - } + @Test + public void testIsStandardType() { + HashMap> map = new HashMap>(); + HashMap> target = new HashMap>(); + target.put("Customer", new ArrayList<>(Arrays.asList("global-customer-id", + "subscriber-name", "subscriber-type", "resource-version"))); + target.put("Business", new ArrayList<>()); + target.put("Inventory", new ArrayList<>()); + target.put("Customers", new ArrayList<>()); + target.put("ServiceSubscriptions", new ArrayList<>()); + target.put("ServiceSubscription", new ArrayList<>( + Arrays.asList("service-type", "temp-ub-sub-account-id", "resource-version"))); + + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + ArrayList addTypes = new ArrayList(); + NodeList xmlElementNodes = javaTypeElement.getElementsByTagName("xml-element"); + String name = javaTypeElement.name(); + for (int j = 0; j < xmlElementNodes.getLength(); ++j) { + XSDElement xmlElement = new XSDElement((Element) xmlElementNodes.item(j)); + if (xmlElement.isStandardType()) + addTypes.add(xmlElement.name()); + } + map.put(name, addTypes); + } + for (String key : map.keySet()) { + assertThat(map.get(key), equalTo(target.get(key))); + } + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDJavaTypeTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDJavaTypeTest.java index b961524..e750da2 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDJavaTypeTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/XSDJavaTypeTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,85 +17,86 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Element; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; import java.util.HashMap; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Element; public class XSDJavaTypeTest extends XSDElementTest { - @Before - public void setUp() throws Exception { - super.setUp(); - } + @Before + public void setUp() throws Exception { + super.setUp(); + } - @Test - public void testXSDJavaTypeElement() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", "global-customer-id"); - target.put("Business", "customers"); - target.put("Inventory", "business"); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", "service-type"); + @Test + public void testXSDJavaTypeElement() { + HashMap map = new HashMap(); + HashMap target = new HashMap(); + target.put("Customer", "global-customer-id"); + target.put("Business", "customers"); + target.put("Inventory", "business"); + target.put("Customers", "customer"); + target.put("ServiceSubscriptions", "service-subscription"); + target.put("ServiceSubscription", "service-type"); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getItemName()); + for (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))); + } } - for(String key : map.keySet()) { - assertThat("For key: "+key,map.get(key),equalTo(target.get(key))); - } - } - @Test - public void testGetItemName() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", "global-customer-id"); - target.put("Business", "customers"); - target.put("Inventory", "business"); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", "service-type"); + @Test + public void testGetItemName() { + HashMap map = new HashMap(); + HashMap target = new HashMap(); + target.put("Customer", "global-customer-id"); + target.put("Business", "customers"); + target.put("Inventory", "business"); + target.put("Customers", "customer"); + target.put("ServiceSubscriptions", "service-subscription"); + target.put("ServiceSubscription", "service-type"); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getItemName()); - } - for(String key : map.keySet()) { - assertThat("For key: "+key,map.get(key),equalTo(target.get(key))); + for (int i = 0; i < javaTypeNodes.getLength(); ++i) { + XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); + XSDJavaType javaType = new XSDJavaType(javaTypeElement); + map.put(javaType.name(), javaType.getItemName()); + } + for (String key : map.keySet()) { + assertThat("For key: " + key, map.get(key), equalTo(target.get(key))); + } } - } - @Test - public void testGetArrayType() { - HashMap map = new HashMap(); - HashMap target = new HashMap(); - target.put("Customer", null); - target.put("Business", null); - target.put("Inventory", null); - target.put("Customers","customer"); - target.put("ServiceSubscriptions", "service-subscription"); - target.put("ServiceSubscription", null); + @Test + public void testGetArrayType() { + HashMap map = new HashMap(); + HashMap target = new HashMap(); + target.put("Customer", null); + target.put("Business", null); + target.put("Inventory", null); + target.put("Customers", "customer"); + target.put("ServiceSubscriptions", "service-subscription"); + target.put("ServiceSubscription", null); - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - XSDElement javaTypeElement = new XSDElement((Element) javaTypeNodes.item(i)); - XSDJavaType javaType = new XSDJavaType(javaTypeElement); - map.put(javaType.name(),javaType.getArrayType()); - } - for(String key : map.keySet()) { - assertThat(map.get(key),equalTo(target.get(key))); + 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-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/YAMLfromOXMTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/YAMLfromOXMTest.java index 06653c8..1d06c38 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/YAMLfromOXMTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/genxsd/YAMLfromOXMTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,9 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemagen.genxsd; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + import com.google.common.collect.Multimap; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.SortedSet; +import java.util.TreeSet; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -43,802 +61,845 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.w3c.dom.Document; import org.w3c.dom.Element; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.SortedSet; -import java.util.TreeSet; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - SchemaVersions.class, - SchemaLocationsBean.class, - TestUtilConfigTranslatorforBusiness.class, - SchemaVersions.class, - EdgeIngestor.class, - NodeIngestor.class, - SwaggerGenerationConfiguration.class - -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai", - "schema.xsd.maxoccurs = 5000" -}) +@ContextConfiguration( + classes = {SchemaVersions.class, SchemaLocationsBean.class, + TestUtilConfigTranslatorforBusiness.class, SchemaVersions.class, EdgeIngestor.class, + NodeIngestor.class, SwaggerGenerationConfiguration.class + + }) +@TestPropertySource(properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000"}) public class YAMLfromOXMTest { - @Autowired + @Autowired EdgeIngestor edgeIngestor; - @Autowired + @Autowired NodeIngestor nodeIngestor; - private static final Logger logger = LoggerFactory.getLogger("YAMLfromOXMTest.class"); - private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; - private static final String EDGEFILENAME = "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; - public static AnnotationConfigApplicationContext ctx = null; - private static String testXML; - protected static final String SERVICE_NAME = "JUNIT"; + private static final Logger logger = LoggerFactory.getLogger("YAMLfromOXMTest.class"); + private static final String OXMFILENAME = "src/test/resources/oxm/business_oxm_v11.xml"; + private static final String EDGEFILENAME = + "src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"; + public static AnnotationConfigApplicationContext ctx = null; + private static String testXML; + protected static final String SERVICE_NAME = "JUNIT"; boolean first = true; @Autowired - YAMLfromOXM yamlFromOxm; + YAMLfromOXM yamlFromOxm; @Autowired SchemaVersions schemaVersions; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - System.setProperty("aai.service.name", SERVICE_NAME); - } - - - - @Before - public void setUp() throws Exception { + @BeforeClass + public static void setUpBeforeClass() throws Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + System.setProperty("aai.service.name", SERVICE_NAME); + } + + @Before + public void setUp() throws Exception { XSDElementTest x = new XSDElementTest(); - x.setUp(); - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); - bw.write(testXML); - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(EdgeDefs()); - bw1.close(); + x.setUp(); + testXML = x.testXML; + logger.debug(testXML); + BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + bw.write(testXML); + bw.close(); + BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw1.write(EdgeDefs()); + bw1.close(); } - - public void setupRelationship() throws Exception{ + + public void setupRelationship() throws Exception { XSDElementTest x = new XSDElementTest(); - x.setUpRelationship(); + x.setUpRelationship(); + + testXML = x.testXML; + logger.debug(testXML); + BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + + bw.write(testXML); + + bw.close(); + BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); + bw1.write(EdgeDefs()); + bw1.close(); + } + + @Test + public void AtestIngestors() throws EdgeRuleNotFoundException { + Multimap results = + edgeIngestor.getAllRules(schemaVersions.getDefaultVersion()); + SortedSet ss = new TreeSet(results.keySet()); + for (String key : ss) { + results.get(key).stream().filter((i) -> ((!i.isPrivateEdge()))).forEach((i) -> { + EdgeDescription ed = new EdgeDescription(i); + System.out.println(ed.getRuleKey()); + }); + } + Document doc = nodeIngestor.getSchema(schemaVersions.getDefaultVersion()); + assertNotNull(doc); + } + + @Test + public void testGetDocumentHeader() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String header = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + yamlFromOxm.process(); + header = yamlFromOxm.getDocumentHeader(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Header:\n" + header, header, is(YAMLheader())); + } + + @Test + public void testProcess() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + fileContent = yamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("FileContent-TestProcess:\n" + fileContent, fileContent, is(YAMLresult())); + } - testXML = x.testXML; - logger.debug(testXML); - BufferedWriter bw = new BufferedWriter(new FileWriter(OXMFILENAME)); + @Test + public void testYAMLfromOXMFileVersionFile() throws IOException { + String outfileName = "testXML.xml"; + File XMLfile = new File(outfileName); + XMLfile.createNewFile(); + BufferedWriter bw = null; + Charset charset = Charset.forName("UTF-8"); + Path path = Paths.get(outfileName); + bw = Files.newBufferedWriter(path, charset); + bw.write(testXML); + bw.close(); + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + fileContent = yamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + XMLfile.delete(); + assertThat("FileContent-OXMFileVersionFile:\n" + fileContent, fileContent, + is(YAMLresult())); + } - bw.write(testXML); + @Test + public void testYAMLfromOXMStringVersionFile() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + fileContent = yamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("FileContent-OXMStringVersionFile:\n" + fileContent, fileContent, + is(YAMLresult())); + } - bw.close(); - BufferedWriter bw1 = new BufferedWriter(new FileWriter(EDGEFILENAME)); - bw1.write(EdgeDefs()); - bw1.close(); - } + @Test + public void testRelationshipListYAMLfromOXMStringVersionFile() { + try { + setupRelationship(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String fileContent = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + fileContent = yamlFromOxm.process(); + } catch (Exception e) { + e.printStackTrace(); + } + boolean matchFound = fileContent.contains((YAMLRelationshipList())); + assertTrue("RelationshipListFormat:\n", matchFound); + } - @Test - public void AtestIngestors() throws EdgeRuleNotFoundException { - Multimap results = edgeIngestor.getAllRules(schemaVersions.getDefaultVersion()); - SortedSet ss=new TreeSet(results.keySet()); - for(String key : ss) { - results.get(key).stream().filter((i) -> ((! i.isPrivateEdge()))).forEach((i) ->{ EdgeDescription ed = new EdgeDescription(i); System.out.println(ed.getRuleKey()); } ); + @Test + public void testAppendDefinitions() { + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String definitions = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + yamlFromOxm.process(); + definitions = yamlFromOxm.appendDefinitions(); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Definitions:\n" + definitions, definitions, + is(YAMLdefs() + YAMLdefsAddPatch())); } - Document doc = nodeIngestor.getSchema(schemaVersions.getDefaultVersion()); - assertNotNull(doc); - } - - @Test - public void testGetDocumentHeader() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String header = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - header = yamlFromOxm.getDocumentHeader(); - } catch(Exception e) { - e.printStackTrace(); + + @Test + public void testGetXMLRootElementName() { + String target = "RootElement=customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + Element customer = null; + String root = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + yamlFromOxm.process(); + customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); + root = yamlFromOxm.getXMLRootElementName(customer); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("RootElement=" + root, is(target)); } - assertThat("Header:\n"+header,header, is(YAMLheader())); - } - - @Test - public void testProcess() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + + @Test + public void testGetXmlRootElementName() { + String target = "RootElement=customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + String root = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + yamlFromOxm.process(); + root = yamlFromOxm.getXmlRootElementName("Customer"); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("RootElement=" + root, is(target)); } - assertThat("FileContent-TestProcess:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testYAMLfromOXMFileVersionFile() throws IOException { - String outfileName = "testXML.xml"; - File XMLfile = new File(outfileName); - XMLfile.createNewFile(); - BufferedWriter bw = null; - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(testXML); - bw.close(); - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + + @Test + public void testGetJavaTypeElementSwagger() { + String target = "Element=java-type/Customer"; + SchemaVersion v = schemaVersions.getAppRootVersion(); + String apiVersion = v.toString(); + Element customer = null; + try { + yamlFromOxm.setXmlVersion(testXML, v); + yamlFromOxm.process(); + customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); + } catch (Exception e) { + e.printStackTrace(); + } + assertThat("Element=" + customer.getNodeName() + "/" + customer.getAttribute("name"), + is(target)); } - XMLfile.delete(); - assertThat("FileContent-OXMFileVersionFile:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testYAMLfromOXMStringVersionFile() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + + public String YAMLresult() { + StringBuilder sb = new StringBuilder(32368); + sb.append(YAMLheader()); + sb.append(YAMLops()); + sb.append(YAMLdefs()); + sb.append(YAMLdefsAddPatch()); + return sb.toString(); } - assertThat("FileContent-OXMStringVersionFile:\n"+fileContent,fileContent, is(YAMLresult())); - } - - @Test - public void testRelationshipListYAMLfromOXMStringVersionFile() { - try { - setupRelationship(); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + + public String YAMLheader() { + StringBuilder sb = new StringBuilder(1500); + sb.append("swagger: \"2.0\"\n"); + sb.append("info:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" description: |\n"); + sb.append("\n"); + sb.append( + " [Differences versus the previous schema version](apidocs/aai/aai_swagger_v11.diff)" + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Copyright © 2017-18 AT&T Intellectual Property. All rights reserved." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append(" You may obtain a copy of the License at\n"); + sb.append("\n"); + sb.append(" (https://creativecommons.org/licenses/by/4.0/)" + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." + + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); + sb.append( + " This document is best viewed with Firefox or Chrome. Nodes can be found by opening the models link below and finding the node-type. Edge definitions can be found with the node definitions." + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" version: \"v11\"" + OxmFileProcessor.LINE_SEPARATOR); + sb.append( + " title: Active and Available Inventory REST API" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" license:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" name: Apache 2.0\n"); + sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" contact:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" name: n/a" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" url: n/a" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" email: n/a" + OxmFileProcessor.LINE_SEPARATOR); + sb.append("host: n/a" + OxmFileProcessor.LINE_SEPARATOR); + sb.append("basePath: /aai/v11" + OxmFileProcessor.LINE_SEPARATOR); + sb.append("schemes:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" - https\n"); + sb.append("paths:" + OxmFileProcessor.LINE_SEPARATOR); + return sb.toString(); } - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String fileContent = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - fileContent = yamlFromOxm.process(); - } catch(Exception e) { - e.printStackTrace(); + + 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: \"#/definitions/service-subscription\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: path\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __SERVICE-TYPE__\n"); + sb.append(" put:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: create or update an existing service-subscription\n"); + sb.append(" description: |\n"); + sb.append(" Create or update an existing service-subscription.\n"); + sb.append(" #\n"); + sb.append( + " Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); + sb.append( + " operationId: createOrUpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: path\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __SERVICE-TYPE__\n"); + sb.append(" - name: body\n"); + sb.append(" in: body\n"); + sb.append( + " description: service-subscription object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/v11/BusinessCustomersCustomerServiceSubscriptionsServiceSubscription.json)\n"); + sb.append(" required: true\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/service-subscription\"\n"); + sb.append(" patch:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: update an existing service-subscription\n"); + sb.append(" description: |\n"); + sb.append(" Update an existing service-subscription\n"); + sb.append(" #\n"); + sb.append( + " Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); + sb.append(" The PUT operation will entirely replace an existing object.\n"); + sb.append( + " The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); + sb.append(" #\n"); + sb.append(" Other differences between PUT and PATCH are:\n"); + sb.append(" #\n"); + sb.append( + " - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); + sb.append( + " - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); + sb.append( + " - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); + sb.append( + " operationId: UpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: path\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __SERVICE-TYPE__\n"); + sb.append(" - name: body\n"); + sb.append(" in: body\n"); + sb.append(" description: service-subscription object that needs to be updated."); + sb.append( + "[See Examples](apidocs/aai/relations/v11/BusinessCustomersCustomerServiceSubscriptionsServiceSubscription.json)\n"); + sb.append(" required: true\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/zzzz-patch-service-subscription\"\n"); + sb.append(" delete:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: delete an existing service-subscription\n"); + sb.append(" description: delete an existing service-subscription\n"); + sb.append( + " operationId: deleteBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: path\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __SERVICE-TYPE__\n"); + sb.append(" - name: resource-version\n"); + sb.append(" in: query\n"); + sb.append(" description: resource-version for concurrency\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" /business/customers/customer/{global-customer-id}/service-subscriptions:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: returns service-subscriptions\n"); + sb.append(" description: returns service-subscriptions\n"); + sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/service-subscriptions\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: service-type\n"); + sb.append(" in: query\n"); + sb.append(" description: n/a\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: \"#/definitions/customer\"\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" put:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: create or update an existing customer\n"); + sb.append(" description: |\n"); + sb.append(" Create or update an existing customer.\n"); + sb.append(" #\n"); + sb.append( + " Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); + sb.append(" operationId: createOrUpdateBusinessCustomersCustomer\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: body\n"); + sb.append(" in: body\n"); + sb.append( + " description: customer object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/v11/BusinessCustomersCustomer.json)\n"); + sb.append(" required: true\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" patch:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: update an existing customer\n"); + sb.append(" description: |\n"); + sb.append(" Update an existing customer\n"); + sb.append(" #\n"); + sb.append( + " Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); + sb.append(" The PUT operation will entirely replace an existing object.\n"); + sb.append( + " The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); + sb.append(" #\n"); + sb.append(" Other differences between PUT and PATCH are:\n"); + sb.append(" #\n"); + sb.append( + " - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); + sb.append( + " - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); + sb.append( + " - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); + sb.append(" operationId: UpdateBusinessCustomersCustomer\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: body\n"); + sb.append(" in: body\n"); + sb.append(" description: customer object that needs to be updated."); + sb.append("[See Examples](apidocs/aai/relations/v11/BusinessCustomersCustomer.json)\n"); + sb.append(" required: true\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/zzzz-patch-customer\"\n"); + sb.append(" delete:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: delete an existing customer\n"); + sb.append(" description: delete an existing customer\n"); + sb.append(" operationId: deleteBusinessCustomersCustomer\n"); + sb.append(" consumes:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"default\":\n"); + sb.append(" null parameters:\n"); + sb.append(" - name: global-customer-id\n"); + sb.append(" in: path\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); + sb.append(" - name: resource-version\n"); + sb.append(" in: query\n"); + sb.append(" description: resource-version for concurrency\n"); + sb.append(" required: true\n"); + sb.append(" type: string\n"); + sb.append(" /business/customers:\n"); + sb.append(" get:\n"); + sb.append(" tags:\n"); + sb.append(" - Business\n"); + sb.append(" summary: returns customers\n"); + sb.append(" description: returns customers\n"); + sb.append(" operationId: getBusinessCustomers\n"); + sb.append(" produces:\n"); + sb.append(" - application/json\n"); + sb.append(" - application/xml\n"); + sb.append(" responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" schema:\n"); + sb.append(" $ref: \"#/definitions/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/a\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/a\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/a\n"); + sb.append(" required: false\n"); + sb.append(" type: string\n"); + return sb.toString(); } - boolean matchFound = fileContent.contains(( YAMLRelationshipList())); - assertTrue("RelationshipListFormat:\n", matchFound); - } - - @Test - public void testAppendDefinitions() { - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String definitions = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - definitions = yamlFromOxm.appendDefinitions(); - } catch(Exception e) { - e.printStackTrace(); + + public String YAMLdefs() { + StringBuilder sb = new StringBuilder(8092); + sb.append("definitions:\n"); + sb.append(" business:\n"); + sb.append(" description: |\n"); + sb.append(" Namespace for business related constructs\n"); + sb.append(" properties:\n"); + sb.append(" customers:\n"); + sb.append(" type: array\n"); + sb.append(" items:\n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" customer:\n"); + sb.append(" description: |\n"); + sb.append(" customer identifiers to provide linkage back to BSS information.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); + sb.append(" required:\n"); + sb.append(" - global-customer-id\n"); + sb.append(" - subscriber-name\n"); + sb.append(" - subscriber-type\n"); + sb.append(" properties:\n"); + sb.append(" global-customer-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" subscriber-name:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber name, an alternate way to retrieve a customer.\n"); + sb.append(" subscriber-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); + sb.append(" resource-version:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); + sb.append(" service-subscriptions:\n"); + sb.append(" type: array\n"); + sb.append(" items:\n"); + sb.append(" $ref: \"#/definitions/service-subscription\"\n"); + sb.append(" customers:\n"); + sb.append(" description: |\n"); + sb.append( + " Collection of customer identifiers to provide linkage back to BSS information.\n"); + sb.append(" properties:\n"); + sb.append(" customer:\n"); + sb.append(" type: array\n"); + sb.append(" items: \n"); + sb.append(" $ref: \"#/definitions/customer\"\n"); + sb.append(" inventory:\n"); + sb.append(" properties:\n"); + sb.append(" business:\n"); + sb.append(" type: object\n"); + sb.append(" $ref: \"#/definitions/business\"\n"); + sb.append(" nodes:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" properties:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" inventory-item-data:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" type: array" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" items:" + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" $ref: \"#/definitions/inventory-item-data\"" + + OxmFileProcessor.LINE_SEPARATOR); + sb.append(" service-subscription:\n"); + sb.append(" description: |\n"); + sb.append(" Object that group service instances.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); + sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); + sb.append( + " - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append( + " -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); + sb.append( + " -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); + sb.append(" required:\n"); + sb.append(" - service-type\n"); + sb.append(" properties:\n"); + sb.append(" service-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" temp-ub-sub-account-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); + sb.append(" resource-version:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); + sb.append(" service-subscriptions:\n"); + sb.append(" description: |\n"); + sb.append(" Collection of objects that group service instances.\n"); + sb.append(" properties:\n"); + sb.append(" service-subscription:\n"); + sb.append(" type: array\n"); + sb.append(" items: \n"); + sb.append(" $ref: \"#/definitions/service-subscription\"\n"); + return sb.toString(); } - assertThat("Definitions:\n"+definitions,definitions, is(YAMLdefs()+YAMLdefsAddPatch())); - } - - @Test - public void testGetXMLRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - String root = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); - root = yamlFromOxm.getXMLRootElementName(customer); - } catch(Exception e) { - e.printStackTrace(); + + public String YAMLdefsAddPatch() { + StringBuilder sb = new StringBuilder(8092); + sb.append(" zzzz-patch-customer:\n"); + sb.append(" description: |\n"); + sb.append(" customer identifiers to provide linkage back to BSS information.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); + sb.append(" properties:\n"); + sb.append(" global-customer-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Global customer id used across to uniquely identify customer.\n"); + sb.append(" subscriber-name:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber name, an alternate way to retrieve a customer.\n"); + sb.append(" subscriber-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); + sb.append(" zzzz-patch-service-subscription:\n"); + sb.append(" description: |\n"); + sb.append(" Object that group service instances.\n"); + sb.append(" ###### Related Nodes\n"); + sb.append( + " - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); + sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); + sb.append( + " - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); + sb.append("\n"); + sb.append( + " -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); + sb.append( + " -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); + sb.append(" properties:\n"); + sb.append(" service-type:\n"); + sb.append(" type: string\n"); + sb.append( + " description: Value defined by orchestration to identify this service.\n"); + sb.append(" temp-ub-sub-account-id:\n"); + sb.append(" type: string\n"); + sb.append( + " description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); + return sb.toString(); } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetXmlRootElementName() { - String target = "RootElement=customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - String root = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - root = yamlFromOxm.getXmlRootElementName("Customer"); - } catch(Exception e) { - e.printStackTrace(); + + public String YAMLRelationshipList() { + StringBuilder sb = new StringBuilder(8092); + sb.append(" relationship-list:\n"); + sb.append(" properties:\n"); + sb.append(" relationship:\n"); + sb.append(" type: object\n"); + sb.append(" $ref: \"#/definitions/relationship\"\n"); + return sb.toString(); } - assertThat("RootElement="+root, is(target)); - } - - @Test - public void testGetJavaTypeElementSwagger() { - String target = "Element=java-type/Customer"; - SchemaVersion v = schemaVersions.getAppRootVersion(); - String apiVersion = v.toString(); - Element customer = null; - try { - yamlFromOxm.setXmlVersion(testXML, v); - yamlFromOxm.process(); - customer = yamlFromOxm.getJavaTypeElementSwagger("Customer"); - } catch(Exception e) { - e.printStackTrace(); + + public static String EdgeDefs() { + StringBuilder sb = new StringBuilder(8092); + sb.append("{\n" + " \"rules\": [\n"); + sb.append(" {\n"); + sb.append(" \"from\": \"service-subscription\",\n"); + sb.append(" \"to\": \"customer\",\n" + + " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + + " \"direction\": \"OUT\",\n" + " \"multiplicity\": \"MANY2ONE\",\n" + + " \"contains-other-v\": \"!${direction}\",\n" + + " \"delete-other-v\": \"!${direction}\",\n" + + " \"prevent-delete\": \"NONE\",\n" + " \"default\": \"true\",\n" + + " \"description\":\"\"\n"); + sb.append(" },\n"); + sb.append(" {\n" + " \"from\": \"service-instance\",\n" + + " \"to\": \"service-subscription\",\n" + + " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + + " \"direction\": \"OUT\",\n" + " \"multiplicity\": \"MANY2ONE\",\n" + + " \"contains-other-v\": \"!${direction}\",\n" + + " \"delete-other-v\": \"!${direction}\",\n" + + " \"prevent-delete\": \"NONE\",\n" + " \"default\": \"true\",\n" + + " \"description\":\"\"\n" + " },\n"); + sb.append(" {\n" + " \"from\": \"service-subscription\",\n" + + " \"to\": \"tenant\",\n" + + " \"label\": \"org.onap.relationships.inventory.Uses\",\n" + + " \"direction\": \"OUT\",\n" + " \"multiplicity\": \"MANY2MANY\",\n" + + " \"contains-other-v\": \"NONE\",\n" + " \"delete-other-v\": \"NONE\",\n" + + " \"prevent-delete\": \"NONE\",\n" + " \"default\": \"true\",\n" + + " \"description\":\"\"\n" + " }"); + sb.append(" ]\n" + "}\n"); + return sb.toString(); } - 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(YAMLdefsAddPatch()); - return sb.toString(); - } - public String YAMLheader() { - StringBuilder sb = new StringBuilder(1500); - sb.append("swagger: \"2.0\"\n"); - sb.append("info:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" description: |\n"); - sb.append("\n"); - sb.append(" [Differences versus the previous schema version](apidocs/aai/aai_swagger_v11.diff)" + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Copyright © 2017-18 AT&T Intellectual Property. All rights reserved." + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License." + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" You may obtain a copy of the License at\n"); - sb.append("\n"); - sb.append(" (https://creativecommons.org/licenses/by/4.0/)"+ OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." + OxmFileProcessor.DOUBLE_LINE_SEPARATOR); - sb.append(" This document is best viewed with Firefox or Chrome. Nodes can be found by opening the models link below and finding the node-type. Edge definitions can be found with the node definitions." + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" version: \"v11\"" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" title: Active and Available Inventory REST API" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" license:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" name: Apache 2.0\n"); - sb.append(" url: http://www.apache.org/licenses/LICENSE-2.0.html" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" contact:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" name: n/a" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" url: n/a" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" email: n/a" + OxmFileProcessor.LINE_SEPARATOR); - sb.append("host: n/a" + OxmFileProcessor.LINE_SEPARATOR); - sb.append("basePath: /aai/v11" + OxmFileProcessor.LINE_SEPARATOR); - sb.append("schemes:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" - https\n"); - sb.append("paths:" + OxmFileProcessor.LINE_SEPARATOR); - 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: \"#/definitions/service-subscription\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" put:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: create or update an existing service-subscription\n"); - sb.append(" description: |\n"); - sb.append(" Create or update an existing service-subscription.\n"); - sb.append(" #\n"); - sb.append(" Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); - sb.append(" operationId: createOrUpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: service-subscription object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/v11/BusinessCustomersCustomerServiceSubscriptionsServiceSubscription.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" patch:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: update an existing service-subscription\n"); - sb.append(" description: |\n"); - sb.append(" Update an existing service-subscription\n"); - sb.append(" #\n"); - sb.append(" Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); - sb.append(" The PUT operation will entirely replace an existing object.\n"); - sb.append(" The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); - sb.append(" #\n"); - sb.append(" Other differences between PUT and PATCH are:\n"); - sb.append(" #\n"); - sb.append(" - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); - sb.append(" - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); - sb.append(" - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); - sb.append(" operationId: UpdateBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: service-subscription object that needs to be updated."); - sb.append("[See Examples](apidocs/aai/relations/v11/BusinessCustomersCustomerServiceSubscriptionsServiceSubscription.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/zzzz-patch-service-subscription\"\n"); - sb.append(" delete:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: delete an existing service-subscription\n"); - sb.append(" description: delete an existing service-subscription\n"); - sb.append(" operationId: deleteBusinessCustomersCustomerServiceSubscriptionsServiceSubscription\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: path\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __SERVICE-TYPE__\n"); - sb.append(" - name: resource-version\n"); - sb.append(" in: query\n"); - sb.append(" description: resource-version for concurrency\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" /business/customers/customer/{global-customer-id}/service-subscriptions:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns service-subscriptions\n"); - sb.append(" description: returns service-subscriptions\n"); - sb.append(" operationId: getBusinessCustomersCustomerServiceSubscriptions\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/service-subscriptions\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: service-type\n"); - sb.append(" in: query\n"); - sb.append(" description: n/a\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: \"#/definitions/customer\"\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" put:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: create or update an existing customer\n"); - sb.append(" description: |\n"); - sb.append(" Create or update an existing customer.\n"); - sb.append(" #\n"); - sb.append(" Note! This PUT method has a corresponding PATCH method that can be used to update just a few of the fields of an existing object, rather than a full object replacement. An example can be found in the [PATCH section] below\n"); - sb.append(" operationId: createOrUpdateBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: customer object that needs to be created or updated. [Valid relationship examples shown here](apidocs/aai/relations/v11/BusinessCustomersCustomer.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" patch:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: update an existing customer\n"); - sb.append(" description: |\n"); - sb.append(" Update an existing customer\n"); - sb.append(" #\n"); - sb.append(" Note: Endpoints that are not devoted to object relationships support both PUT and PATCH operations.\n"); - sb.append(" The PUT operation will entirely replace an existing object.\n"); - sb.append(" The PATCH operation sends a \"description of changes\" for an existing object. The entire set of changes must be applied. An error result means no change occurs.\n"); - sb.append(" #\n"); - sb.append(" Other differences between PUT and PATCH are:\n"); - sb.append(" #\n"); - sb.append(" - For PATCH, you can send any of the values shown in sample REQUEST body. There are no required values.\n"); - sb.append(" - For PATCH, resource-id which is a required REQUEST body element for PUT, must not be sent.\n"); - sb.append(" - PATCH cannot be used to update relationship elements; there are dedicated PUT operations for this.\n"); - sb.append(" operationId: UpdateBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: body\n"); - sb.append(" in: body\n"); - sb.append(" description: customer object that needs to be updated."); - sb.append("[See Examples](apidocs/aai/relations/v11/BusinessCustomersCustomer.json)\n"); - sb.append(" required: true\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/zzzz-patch-customer\"\n"); - sb.append(" delete:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: delete an existing customer\n"); - sb.append(" description: delete an existing customer\n"); - sb.append(" operationId: deleteBusinessCustomersCustomer\n"); - sb.append(" consumes:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"default\":\n"); - sb.append(" null parameters:\n"); - sb.append(" - name: global-customer-id\n"); - sb.append(" in: path\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" example: __GLOBAL-CUSTOMER-ID__\n"); - sb.append(" - name: resource-version\n"); - sb.append(" in: query\n"); - sb.append(" description: resource-version for concurrency\n"); - sb.append(" required: true\n"); - sb.append(" type: string\n"); - sb.append(" /business/customers:\n"); - sb.append(" get:\n"); - sb.append(" tags:\n"); - sb.append(" - Business\n"); - sb.append(" summary: returns customers\n"); - sb.append(" description: returns customers\n"); - sb.append(" operationId: getBusinessCustomers\n"); - sb.append(" produces:\n"); - sb.append(" - application/json\n"); - sb.append(" - application/xml\n"); - sb.append(" responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" schema:\n"); - sb.append(" $ref: \"#/definitions/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/a\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/a\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/a\n"); - sb.append(" required: false\n"); - sb.append(" type: string\n"); - return sb.toString(); - } - public String YAMLdefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("definitions:\n"); - sb.append(" business:\n"); - sb.append(" description: |\n"); - sb.append(" Namespace for business related constructs\n"); - sb.append(" properties:\n"); - sb.append(" customers:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - global-customer-id\n"); - sb.append(" - subscriber-name\n"); - sb.append(" - subscriber-type\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" type: array\n"); - sb.append(" items:\n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - sb.append(" customers:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" properties:\n"); - sb.append(" customer:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/customer\"\n"); - sb.append(" inventory:\n"); - sb.append(" properties:\n"); - sb.append(" business:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/business\"\n"); - sb.append(" nodes:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" properties:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" inventory-item-data:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" type: array" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" items:" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" $ref: \"#/definitions/inventory-item-data\"" + OxmFileProcessor.LINE_SEPARATOR); - sb.append(" service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" required:\n"); - sb.append(" - service-type\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - sb.append(" resource-version:\n"); - sb.append(" type: string\n"); - sb.append(" description: Used for optimistic concurrency. Must be empty on create, valid on update and delete.\n"); - sb.append(" service-subscriptions:\n"); - sb.append(" description: |\n"); - sb.append(" Collection of objects that group service instances.\n"); - sb.append(" properties:\n"); - sb.append(" service-subscription:\n"); - sb.append(" type: array\n"); - sb.append(" items: \n"); - sb.append(" $ref: \"#/definitions/service-subscription\"\n"); - return sb.toString(); - } - public String YAMLdefsAddPatch() { - StringBuilder sb = new StringBuilder(8092); - sb.append(" zzzz-patch-customer:\n"); - sb.append(" description: |\n"); - sb.append(" customer identifiers to provide linkage back to BSS information.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - FROM service-subscription (CHILD of customer, service-subscription BelongsTo customer, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this CUSTOMER node is deleted, this FROM node is DELETED also\n"); - sb.append(" properties:\n"); - sb.append(" global-customer-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: Global customer id used across to uniquely identify customer.\n"); - sb.append(" subscriber-name:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber name, an alternate way to retrieve a customer.\n"); - sb.append(" subscriber-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Subscriber type, a way to provide VID with only the INFRA customers.\n"); - sb.append(" zzzz-patch-service-subscription:\n"); - sb.append(" description: |\n"); - sb.append(" Object that group service instances.\n"); - sb.append(" ###### Related Nodes\n"); - sb.append(" - TO customer (PARENT of service-subscription, service-subscription BelongsTo customer, MANY2ONE)(4)\n"); - sb.append(" - TO tenant( service-subscription Uses tenant, MANY2MANY)\n"); - sb.append(" - FROM service-instance (CHILD of service-subscription, service-instance BelongsTo service-subscription, MANY2ONE)(1)\n"); - sb.append("\n"); - sb.append(" -(1) IF this SERVICE-SUBSCRIPTION node is deleted, this FROM node is DELETED also\n"); - sb.append(" -(4) IF this TO node is deleted, this SERVICE-SUBSCRIPTION is DELETED also\n"); - sb.append(" properties:\n"); - sb.append(" service-type:\n"); - sb.append(" type: string\n"); - sb.append(" description: Value defined by orchestration to identify this service.\n"); - sb.append(" temp-ub-sub-account-id:\n"); - sb.append(" type: string\n"); - sb.append(" description: This property will be deleted from A&AI in the near future. Only stop gap solution.\n"); - return sb.toString(); - } - - public String YAMLRelationshipList() { - StringBuilder sb = new StringBuilder(8092); - sb.append(" relationship-list:\n"); - sb.append(" properties:\n"); - sb.append(" relationship:\n"); - sb.append(" type: object\n"); - sb.append(" $ref: \"#/definitions/relationship\"\n"); - return sb.toString(); - } - - public static String EdgeDefs() { - StringBuilder sb = new StringBuilder(8092); - sb.append("{\n" + - " \"rules\": [\n"); - sb.append(" {\n"); - sb.append(" \"from\": \"service-subscription\",\n"); - sb.append(" \"to\": \"customer\",\n" + - " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2ONE\",\n" + - " \"contains-other-v\": \"!${direction}\",\n" + - " \"delete-other-v\": \"!${direction}\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n"); - sb.append(" },\n"); - sb.append(" {\n" + - " \"from\": \"service-instance\",\n" + - " \"to\": \"service-subscription\",\n" + - " \"label\": \"org.onap.relationships.inventory.BelongsTo\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2ONE\",\n" + - " \"contains-other-v\": \"!${direction}\",\n" + - " \"delete-other-v\": \"!${direction}\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n" + - " },\n"); - sb.append(" {\n" + - " \"from\": \"service-subscription\",\n" + - " \"to\": \"tenant\",\n" + - " \"label\": \"org.onap.relationships.inventory.Uses\",\n" + - " \"direction\": \"OUT\",\n" + - " \"multiplicity\": \"MANY2MANY\",\n" + - " \"contains-other-v\": \"NONE\",\n" + - " \"delete-other-v\": \"NONE\",\n" + - " \"prevent-delete\": \"NONE\",\n" + - " \"default\": \"true\",\n" + - " \"description\":\"\"\n" + - " }"); - sb.append(" ]\n" + - "}\n"); - return sb.toString(); - } -} \ No newline at end of file +} diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/swagger/DefinitionTest.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/swagger/DefinitionTest.java index 3a53019..98169d8 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/swagger/DefinitionTest.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/swagger/DefinitionTest.java @@ -46,12 +46,11 @@ public class DefinitionTest { */ @Parameters public static Collection testConditions() { - String inputs[][] = { - {"name1", "desc1", - "Definition{definitionName='name1', definitionDescription='desc1', propertyList=[]}"}, - {"name2", "desc2", + String inputs[][] = {{"name1", "desc1", + "Definition{definitionName='name1', definitionDescription='desc1', propertyList=[]}"}, + {"name2", "desc2", "Definition{definitionName='name2', definitionDescription='desc2', propertyList=[]}"}, - {"fake", "random", + {"fake", "random", "Definition{definitionName='fake', definitionDescription='random', propertyList=[]}"}}; return (Arrays.asList(inputs)); } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforBusiness.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforBusiness.java index e7de26b..fdc2002 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforBusiness.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforBusiness.java @@ -8,7 +8,7 @@ * 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, @@ -20,54 +20,55 @@ package org.onap.aai.schemagen.testutils; -import org.onap.aai.setup.ConfigTranslator; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; - import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; +import org.onap.aai.setup.ConfigTranslator; +import org.onap.aai.setup.SchemaLocationsBean; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; + public class TestUtilConfigTranslatorforBusiness extends ConfigTranslator { - public TestUtilConfigTranslatorforBusiness(SchemaLocationsBean bean, SchemaVersions schemaVersions) { - super(bean, schemaVersions); - } + public TestUtilConfigTranslatorforBusiness(SchemaLocationsBean bean, + SchemaVersions schemaVersions) { + super(bean, schemaVersions); + } - @Override - public Map> getNodeFiles() { + @Override + public Map> getNodeFiles() { - List files11 = new ArrayList<>(); - files11.add("src/test/resources/oxm/business_oxm_v11.xml"); + List files11 = new ArrayList<>(); + files11.add("src/test/resources/oxm/business_oxm_v11.xml"); - List files13 = new ArrayList<>(); - files13.add("src/test/resources/oxm/business_oxm_v13.xml"); - files13.add("src/test/resources/oxm/common_oxm_v13.xml"); - files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml"); - files13.add("src/test/resources/oxm/network_oxm_v13.xml"); + List files13 = new ArrayList<>(); + files13.add("src/test/resources/oxm/business_oxm_v13.xml"); + files13.add("src/test/resources/oxm/common_oxm_v13.xml"); + files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml"); + files13.add("src/test/resources/oxm/network_oxm_v13.xml"); - Map> input = new TreeMap<>(); - input.put(new SchemaVersion("v11"), files11); - input.put(schemaVersions.getDefaultVersion(), files13); - return input; - } + Map> input = new TreeMap<>(); + input.put(new SchemaVersion("v11"), files11); + input.put(schemaVersions.getDefaultVersion(), files13); + return input; + } - @Override - public Map> getEdgeFiles() { - List files = new ArrayList<>(); - files.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); - Map> input = new TreeMap<>(); - input.put(schemaVersions.getDefaultVersion(), files); + @Override + public Map> getEdgeFiles() { + List files = new ArrayList<>(); + files.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); + Map> input = new TreeMap<>(); + input.put(schemaVersions.getDefaultVersion(), files); - List files2 = new ArrayList<>(); - files2.add("src/test/resources/dbedgerules/test.json"); + List files2 = new ArrayList<>(); + files2.add("src/test/resources/dbedgerules/test.json"); - List files3 = new ArrayList<>(); - files3.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); - input.put(new SchemaVersion("v11"), files3); + List files3 = new ArrayList<>(); + files3.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); + input.put(new SchemaVersion("v11"), files3); - return input; - } + return input; + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforDataLink.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforDataLink.java index 3cee014..7fdcc34 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforDataLink.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforDataLink.java @@ -8,7 +8,7 @@ * 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, @@ -20,40 +20,49 @@ package org.onap.aai.schemagen.testutils; -import org.onap.aai.setup.ConfigTranslator; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; - import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; +import org.onap.aai.setup.ConfigTranslator; +import org.onap.aai.setup.SchemaLocationsBean; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; + public class TestUtilConfigTranslatorforDataLink extends ConfigTranslator { - public TestUtilConfigTranslatorforDataLink(SchemaLocationsBean bean, SchemaVersions schemaVersions) { - super(bean, schemaVersions); - } - - @Override - public Map> getNodeFiles() { - - Map> input = new TreeMap<>(); - input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_one.xml")); - input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_two.xml")); - input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_three.xml")); - input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_four.xml")); - return input; - } - - @Override - public Map> getEdgeFiles() { - Map> input = new TreeMap<>(); - input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_one.json")); - input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_two.json")); - input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_three.json")); - input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_four.json")); - return input; - } + public TestUtilConfigTranslatorforDataLink(SchemaLocationsBean bean, + SchemaVersions schemaVersions) { + super(bean, schemaVersions); + } + + @Override + public Map> getNodeFiles() { + + Map> input = new TreeMap<>(); + input.put(new SchemaVersion("v1"), + Arrays.asList("src/test/resources/oxm/dbalias_oxm_one.xml")); + input.put(new SchemaVersion("v2"), + Arrays.asList("src/test/resources/oxm/dbalias_oxm_two.xml")); + input.put(new SchemaVersion("v3"), + Arrays.asList("src/test/resources/oxm/dbalias_oxm_three.xml")); + input.put(new SchemaVersion("v4"), + Arrays.asList("src/test/resources/oxm/dbalias_oxm_four.xml")); + return input; + } + + @Override + public Map> getEdgeFiles() { + Map> input = new TreeMap<>(); + input.put(new SchemaVersion("v1"), + Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_one.json")); + input.put(new SchemaVersion("v2"), + Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_two.json")); + input.put(new SchemaVersion("v3"), + Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_three.json")); + input.put(new SchemaVersion("v4"), + Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_four.json")); + return input; + } } diff --git a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforEdges.java b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforEdges.java index e39986f..ca45b9d 100644 --- a/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforEdges.java +++ b/aai-schema-gen/src/test/java/org/onap/aai/schemagen/testutils/TestUtilConfigTranslatorforEdges.java @@ -8,7 +8,7 @@ * 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, @@ -20,54 +20,55 @@ package org.onap.aai.schemagen.testutils; -import org.onap.aai.setup.ConfigTranslator; -import org.onap.aai.setup.SchemaLocationsBean; -import org.onap.aai.setup.SchemaVersion; -import org.onap.aai.setup.SchemaVersions; - import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; +import org.onap.aai.setup.ConfigTranslator; +import org.onap.aai.setup.SchemaLocationsBean; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; + public class TestUtilConfigTranslatorforEdges extends ConfigTranslator { - public TestUtilConfigTranslatorforEdges(SchemaLocationsBean bean, SchemaVersions schemaVersions) { - super(bean, schemaVersions); - } + public TestUtilConfigTranslatorforEdges(SchemaLocationsBean bean, + SchemaVersions schemaVersions) { + super(bean, schemaVersions); + } - @Override - public Map> getNodeFiles() { - List files11 = new ArrayList<>(); - files11.add("src/test/resources/oxm/business_oxm_v11.xml"); + @Override + public Map> getNodeFiles() { + List files11 = new ArrayList<>(); + files11.add("src/test/resources/oxm/business_oxm_v11.xml"); - List files13 = new ArrayList<>(); - files13.add("src/test/resources/oxm/business_oxm_v13.xml"); - files13.add("src/test/resources/oxm/common_oxm_v13.xml"); - files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml"); - files13.add("src/test/resources/oxm/network_oxm_v13.xml"); + List files13 = new ArrayList<>(); + files13.add("src/test/resources/oxm/business_oxm_v13.xml"); + files13.add("src/test/resources/oxm/common_oxm_v13.xml"); + files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml"); + files13.add("src/test/resources/oxm/network_oxm_v13.xml"); - Map> input = new TreeMap<>(); - input.put(new SchemaVersion("v11"), files11); - input.put(new SchemaVersion("v13"), files13); - return input; - } + Map> input = new TreeMap<>(); + input.put(new SchemaVersion("v11"), files11); + input.put(new SchemaVersion("v13"), files13); + return input; + } - @Override - public Map> getEdgeFiles() { - List files = new ArrayList<>(); - files.add("src/test/resources/dbedgerules/test.json"); - files.add("src/test/resources/dbedgerules/test2.json"); - Map> input = new TreeMap<>(); - input.put(schemaVersions.getDefaultVersion(), files); + @Override + public Map> getEdgeFiles() { + List files = new ArrayList<>(); + files.add("src/test/resources/dbedgerules/test.json"); + files.add("src/test/resources/dbedgerules/test2.json"); + Map> input = new TreeMap<>(); + input.put(schemaVersions.getDefaultVersion(), files); - List files2 = new ArrayList<>(); - files2.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); - input.put(new SchemaVersion("v10"), files2); - List files3 = new ArrayList<>(); - files3.add("src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"); - input.put(new SchemaVersion("v11"), files3); + List files2 = new ArrayList<>(); + files2.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json"); + input.put(new SchemaVersion("v10"), files2); + List files3 = new ArrayList<>(); + files3.add("src/test/resources/dbedgerules/EdgeDescriptionRules_test.json"); + input.put(new SchemaVersion("v11"), files3); - return input; - } + return input; + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/Profiles.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/Profiles.java index 863d6c8..a34db5f 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/Profiles.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/Profiles.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice; public final class Profiles { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/SchemaServiceApp.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/SchemaServiceApp.java index 66718dd..291e0a6 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/SchemaServiceApp.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/SchemaServiceApp.java @@ -8,7 +8,7 @@ * 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, @@ -17,12 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.Map; +import java.util.UUID; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.onap.aai.aailog.logs.AaiDebugLog; import org.onap.aai.exceptions.AAIException; import org.onap.aai.schemaservice.config.PropertyPasswordConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; @@ -33,12 +41,6 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.env.Environment; -import org.onap.aai.aailog.logs.AaiDebugLog; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import java.util.Map; -import java.util.UUID; import org.springframework.web.context.request.RequestContextListener; @SpringBootApplication @@ -46,15 +48,10 @@ import org.springframework.web.context.request.RequestContextListener; // It only searches beans in the following packages // Any method annotated with @Bean annotation or any class // with @Component, @Configuration, @Service will be picked up -@EnableAutoConfiguration(exclude = { - DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - HibernateJpaAutoConfiguration.class -}) -@ComponentScan(basePackages = { - "org.onap.aai.schemaservice", - "org.onap.aai.aaf" -}) +@EnableAutoConfiguration( + exclude = {DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan(basePackages = {"org.onap.aai.schemaservice", "org.onap.aai.aaf"}) public class SchemaServiceApp { private static final Logger logger = LoggerFactory.getLogger(SchemaServiceApp.class.getName()); @@ -79,11 +76,8 @@ public class SchemaServiceApp { Environment env = app.run(args).getEnvironment(); - logger.debug( - "Application '{}' is running on {}!", - env.getProperty("spring.application.name"), - env.getProperty("server.port") - ); + logger.debug("Application '{}' is running on {}!", + env.getProperty("spring.application.name"), env.getProperty("server.port")); logger.debug("SchemaService MicroService Started"); @@ -125,8 +119,8 @@ public class SchemaServiceApp { // This is only needed for tomcat keeping this as temporary System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); - - if (env.acceptsProfiles(Profiles.TWO_WAY_SSL) && env.acceptsProfiles(Profiles.ONE_WAY_SSL)) { + if (env.acceptsProfiles(Profiles.TWO_WAY_SSL) + && env.acceptsProfiles(Profiles.ONE_WAY_SSL)) { logger.warn("You have seriously misconfigured your application"); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AAIConfigTranslator.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AAIConfigTranslator.java index 38645db..3d1e854 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AAIConfigTranslator.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AAIConfigTranslator.java @@ -8,7 +8,7 @@ * 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, @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.config; -import org.onap.aai.schemaservice.nodeschema.SchemaVersion; -import org.onap.aai.schemaservice.nodeschema.SchemaVersions; +package org.onap.aai.schemaservice.config; import java.io.File; import java.util.Arrays; @@ -31,6 +29,9 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +import org.onap.aai.schemaservice.nodeschema.SchemaVersions; + /** * AAIConfigTranslator is responsible for looking at the * schema files and edge files based on the available versions @@ -38,81 +39,73 @@ import java.util.stream.Stream; */ public class AAIConfigTranslator extends ConfigTranslator { - private static final String FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); + private static final String FILESEP = + (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); public AAIConfigTranslator(SchemaLocationsBean bean, SchemaVersions schemaVersions) { - super(bean, schemaVersions); - } - - /* (non-Javadoc) - * @see org.onap.aai.setup.ConfigTranslator#getNodeFiles() - */ - @Override - public Map> getNodeFiles() { - - Map> files = new TreeMap<>(); - for (SchemaVersion v : schemaVersions.getVersions()) { - List container = getVersionNodeFiles(v); - files.put(v, container); + super(bean, schemaVersions); } - return files; - } - + /* + * (non-Javadoc) + * + * @see org.onap.aai.setup.ConfigTranslator#getNodeFiles() + */ + @Override + public Map> getNodeFiles() { + + Map> files = new TreeMap<>(); + for (SchemaVersion v : schemaVersions.getVersions()) { + List container = getVersionNodeFiles(v); + files.put(v, container); + } + + return files; + } - private List getVersionNodeFiles(SchemaVersion v) { + private List getVersionNodeFiles(SchemaVersion v) { - return getVersionFiles( - bean.getNodeDirectory(), - v, - () -> bean.getNodesInclusionPattern().stream(), - () -> bean.getNodesExclusionPattern().stream() - ); - } + return getVersionFiles(bean.getNodeDirectory(), v, + () -> bean.getNodesInclusionPattern().stream(), + () -> bean.getNodesExclusionPattern().stream()); + } + /* + * (non-Javadoc) + * + * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles() + */ + @Override + public Map> getEdgeFiles() { + + Map> files = new TreeMap<>(); + for (SchemaVersion v : schemaVersions.getVersions()) { + List container = getVersionEdgeFiles(v); + files.put(v, container); + } + + return files; + } - /* (non-Javadoc) - * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles() - */ - @Override - public Map> getEdgeFiles() { + private List getVersionEdgeFiles(SchemaVersion v) { - Map> files = new TreeMap<>(); - for (SchemaVersion v : schemaVersions.getVersions()) { - List container = getVersionEdgeFiles(v); - files.put(v, container); + return getVersionFiles(bean.getEdgeDirectory(), v, + () -> bean.getEdgesInclusionPattern().stream(), + () -> bean.getEdgesExclusionPattern().stream()); } - return files; - } - - private List getVersionEdgeFiles(SchemaVersion v) { - - return getVersionFiles( - bean.getEdgeDirectory(), - v, - () -> bean.getEdgesInclusionPattern().stream(), - () -> bean.getEdgesExclusionPattern().stream() - ); - } - - private List getVersionFiles( - String startDirectory, - SchemaVersion schemaVersion, - Supplier> inclusionPattern, - Supplier> exclusionPattern - ){ - - List container; - final String directoryName = startDirectory + FILESEP + schemaVersion.toString() + FILESEP; - - container = Arrays.stream(new File(directoryName).listFiles()) - .map(File::getName) - .filter(name -> inclusionPattern.get().anyMatch(name::matches)) - .map(name -> directoryName + name) - .filter(name -> exclusionPattern.get().noneMatch(name::matches)) - .collect(Collectors.toList()); - - return container; - } + private List getVersionFiles(String startDirectory, SchemaVersion schemaVersion, + Supplier> inclusionPattern, Supplier> exclusionPattern) { + + List container; + final String directoryName = startDirectory + FILESEP + schemaVersion.toString() + FILESEP; + + container = Arrays.stream(new File(directoryName).listFiles()).map(File::getName) + .filter(name -> inclusionPattern.get().anyMatch(name::matches)) + .map(name -> directoryName + name) + .filter(name -> exclusionPattern.get().noneMatch(name::matches)) + .collect(Collectors.toList()); + + return container; + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AuthorizationConfiguration.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AuthorizationConfiguration.java index 8069520..971fb2b 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AuthorizationConfiguration.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/AuthorizationConfiguration.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; import org.onap.aai.aaf.auth.AAIAuthCore; @@ -33,7 +34,7 @@ public class AuthorizationConfiguration { private String basePath; @Bean - public AAIAuthCore aaiAuthCore(){ + public AAIAuthCore aaiAuthCore() { return new AAIAuthCore(basePath); } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ConfigTranslator.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ConfigTranslator.java index e13367d..b86f9fa 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ConfigTranslator.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ConfigTranslator.java @@ -8,7 +8,7 @@ * 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, @@ -17,15 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; +import java.util.List; +import java.util.Map; + import org.onap.aai.schemaservice.nodeschema.SchemaVersion; import org.onap.aai.schemaservice.nodeschema.SchemaVersions; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.Map; - /** * Converts the contents of the schema config file * (which lists which schema files to be loaded) to @@ -33,34 +34,34 @@ import java.util.Map; * */ public abstract class ConfigTranslator { - protected SchemaLocationsBean bean; - protected SchemaVersions schemaVersions; + protected SchemaLocationsBean bean; + protected SchemaVersions schemaVersions; - @Autowired - public ConfigTranslator(SchemaLocationsBean schemaLocationbean, SchemaVersions schemaVersions) { - this.bean = schemaLocationbean; - this.schemaVersions = schemaVersions; - } + @Autowired + public ConfigTranslator(SchemaLocationsBean schemaLocationbean, SchemaVersions schemaVersions) { + this.bean = schemaLocationbean; + this.schemaVersions = schemaVersions; + } - /** - * Translates the contents of the schema config file - * into the input for the NodeIngestor - * - * @return Map of Version to the list of (string) filenames to be - * ingested for that version - */ - public abstract Map> getNodeFiles(); + /** + * Translates the contents of the schema config file + * into the input for the NodeIngestor + * + * @return Map of Version to the list of (string) filenames to be + * ingested for that version + */ + public abstract Map> getNodeFiles(); - /** - * Translates the contents of the schema config file - * into the input for the EdgeIngestor - * - * @return Map of Version to the List of (String) filenames to be - * ingested for that version - */ - public abstract Map> getEdgeFiles(); + /** + * Translates the contents of the schema config file + * into the input for the EdgeIngestor + * + * @return Map of Version to the List of (String) filenames to be + * ingested for that version + */ + public abstract Map> getEdgeFiles(); - public SchemaVersions getSchemaVersions(){ - return schemaVersions; - } + public SchemaVersions getSchemaVersions() { + return schemaVersions; + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ErrorHandler.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ErrorHandler.java index a565298..83a1805 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ErrorHandler.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/ErrorHandler.java @@ -23,11 +23,13 @@ package org.onap.aai.schemaservice.config; import java.io.IOException; import java.util.ArrayList; import java.util.List; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; + import org.onap.aai.exceptions.AAIException; import org.onap.aai.logging.ErrorLogHelper; import org.onap.aai.logging.ErrorObject; @@ -61,8 +63,8 @@ public class ErrorHandler extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - FilterChain filterChain) throws ServletException, IOException { + HttpServletResponse httpServletResponse, FilterChain filterChain) + throws ServletException, IOException { String uri = httpServletRequest.getRequestURI(); @@ -104,8 +106,8 @@ public class ErrorHandler extends OncePerRequestFilter { ArrayList templateVars = new ArrayList<>(); AAIException aaiException = (AAIException) e; - String message = ErrorLogHelper - .getRESTAPIErrorResponse(mediaTypeList, aaiException, templateVars); + String message = ErrorLogHelper.getRESTAPIErrorResponse(mediaTypeList, aaiException, + templateVars); ErrorObject object = null; try { object = ErrorLogHelper.getErrorObject(aaiException.getCode()); @@ -128,8 +130,8 @@ public class ErrorHandler extends OncePerRequestFilter { ArrayList templateVars = new ArrayList<>(); AAIException aaiException = new AAIException("AAI_4000", e); LOGGER.error("Encountered an internal exception {}", LogFormatTools.getStackTop(e)); - String message = ErrorLogHelper - .getRESTAPIErrorResponse(mediaTypeList, aaiException, templateVars); + String message = ErrorLogHelper.getRESTAPIErrorResponse(mediaTypeList, aaiException, + templateVars); ErrorObject object = null; try { object = ErrorLogHelper.getErrorObject(aaiException.getCode()); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/JettyPasswordDecoder.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/JettyPasswordDecoder.java index 1b48753..f1576b0 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/JettyPasswordDecoder.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/JettyPasswordDecoder.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; import org.eclipse.jetty.util.security.Password; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PasswordDecoder.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PasswordDecoder.java index f0ae940..9ebd684 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PasswordDecoder.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PasswordDecoder.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; public interface PasswordDecoder { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PropertyPasswordConfiguration.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PropertyPasswordConfiguration.java index 2f42309..2292577 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PropertyPasswordConfiguration.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/PropertyPasswordConfiguration.java @@ -29,6 +29,7 @@ import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; + import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -68,9 +69,8 @@ public class PropertyPasswordConfiguration logger.warn("Keystore password is null in AAF Certman password file"); } } catch (IOException e) { - logger.warn( - "Not using AAF Certman password file " + passwordFile.getName() + " e=" + - e.getMessage()); + logger.warn("Not using AAF Certman password file " + passwordFile.getName() + " e=" + + e.getMessage()); } File passphrasesFile = new File(certPath + ".passphrases"); @@ -86,9 +86,8 @@ public class PropertyPasswordConfiguration logger.warn("Truststore password is null in AAF Certman passphrases file"); } } catch (IOException e) { - logger.warn( - "Not using AAF Certman passphrases file " + passphrasesFile.getName() + " e=" + - e.getMessage()); + logger.warn("Not using AAF Certman passphrases file " + passphrasesFile.getName() + + " e=" + e.getMessage()); } } for (PropertySource propertySource : environment.getPropertySources()) { @@ -97,8 +96,8 @@ public class PropertyPasswordConfiguration if (!propertyOverrides.isEmpty()) { PropertySource decodedProperties = new MapPropertySource("decoded " + propertySource.getName(), propertyOverrides); - environment.getPropertySources() - .addBefore(propertySource.getName(), decodedProperties); + environment.getPropertySources().addBefore(propertySource.getName(), + decodedProperties); } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaConfiguration.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaConfiguration.java index 28f6bc1..69d214c 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaConfiguration.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaConfiguration.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; import org.onap.aai.schemaservice.nodeschema.NodeIngestor; @@ -38,7 +39,8 @@ public class SchemaConfiguration { } @Bean(name = "configTranslator") - public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean, SchemaVersions schemaVersions) { + public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean, + SchemaVersions schemaVersions) { return new AAIConfigTranslator(schemaLocationsBean, schemaVersions); } @@ -53,12 +55,11 @@ public class SchemaConfiguration { } @Bean - public NodeValidator nodeValidator( - ConfigTranslator configTranslator, + public NodeValidator nodeValidator(ConfigTranslator configTranslator, SchemaErrorStrategy schemaErrorStrategy, - DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule - ) { - return new NodeValidator(configTranslator, schemaErrorStrategy, duplicateNodeDefinitionValidationModule); + DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule) { + return new NodeValidator(configTranslator, schemaErrorStrategy, + duplicateNodeDefinitionValidationModule); } @Bean diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaLocationsBean.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaLocationsBean.java index 042889b..3582c5e 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaLocationsBean.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/config/SchemaLocationsBean.java @@ -8,7 +8,7 @@ * 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, @@ -17,122 +17,123 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.config; +import java.util.List; + import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import java.util.List; - @Configuration -@PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound=true) -@PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound=true) +@PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound = true) +@PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound = true) public class SchemaLocationsBean { - /* - * Per Spring documentation, the last PropertySource that works will - * be applied. Here, schema.ingest.file will be an environment variable - * set on install that tells Spring where to look for the schema - * ingest properties file (and the actual filename), but the former - * PropertySource gives the default of looking on the classpath for - * schema-ingest.properties in case that second one doesn't work. - * - * The schema-ingest.properties file (or its equivalent if you choose - * to name it otherwise) must contain the entries the below @Value - * annotations are looking for. - */ - - @Value("${schema.configuration.location}") - private String schemaConfigLoc; - - @Value("${schema.nodes.location}") - private String nodeDirectory; - - @Value("${schema.edges.location}") - private String edgeDirectory; - - @Value("${schema.nodes.inclusion.list:}#{T(java.util.Arrays).asList(\".*oxm(.*).xml\")}") - private List nodesInclusionPattern; - - @Value("${schema.nodes.exclusion.list:}#{T(java.util.Collections).emptyList()}") - private List nodesExclusionPattern; - - @Value("${schema.edges.inclusion.list:}#{T(java.util.Arrays).asList(\"DbEdgeRules_.*.json\")}") - private List edgesInclusionPattern; - - @Value("${schema.edges.exclusion.list:}#{T(java.util.Collections).emptyList()}") - private List edgesExclusionPattern; - - /** - * @return the file name/location with the list of schema files to be ingested - */ - public String getSchemaConfigLocation() { - return schemaConfigLoc; - } - - /** - * Sets the name/location of the file with the list of schema files to ingest - * - * @param schemaConfigLoc - the file name/location - */ - public void setSchemaConfigLocation(String schemaConfigLoc) { - this.schemaConfigLoc = schemaConfigLoc; - } - - /** - * @return the location of the OXM files - */ - public String getNodeDirectory() { - return nodeDirectory; - } - - /** - * Sets the location of the OXM files - * - * @param nodeDirectory - the location of the OXM files - */ - public void setNodeDirectory(String nodeDirectory) { - this.nodeDirectory = nodeDirectory; - } - - /** - * @return the location of the edge rule json files - */ - public String getEdgeDirectory() { - return edgeDirectory; - } - - /** - * Sets the location of the edge rule json files - * - * @param edgeDirectory - the location of the edge rule files - */ - public void setEdgeDirectory(String edgeDirectory) { - this.edgeDirectory = edgeDirectory; - } - - public List getNodesExclusionPattern(){ - return this.nodesExclusionPattern; - } - - public List getNodesInclusionPattern(){ - return this.nodesInclusionPattern; - } - - public List getEdgesExclusionPattern(){ - return this.edgesExclusionPattern; - } - - public List getEdgesInclusionPattern(){ - return this.edgesInclusionPattern; - } - - //this allows the code to actually read the value from the config file - //without this those strings get set to literally "${edgeDir}" etc - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } + /* + * Per Spring documentation, the last PropertySource that works will + * be applied. Here, schema.ingest.file will be an environment variable + * set on install that tells Spring where to look for the schema + * ingest properties file (and the actual filename), but the former + * PropertySource gives the default of looking on the classpath for + * schema-ingest.properties in case that second one doesn't work. + * + * The schema-ingest.properties file (or its equivalent if you choose + * to name it otherwise) must contain the entries the below @Value + * annotations are looking for. + */ + + @Value("${schema.configuration.location}") + private String schemaConfigLoc; + + @Value("${schema.nodes.location}") + private String nodeDirectory; + + @Value("${schema.edges.location}") + private String edgeDirectory; + + @Value("${schema.nodes.inclusion.list:}#{T(java.util.Arrays).asList(\".*oxm(.*).xml\")}") + private List nodesInclusionPattern; + + @Value("${schema.nodes.exclusion.list:}#{T(java.util.Collections).emptyList()}") + private List nodesExclusionPattern; + + @Value("${schema.edges.inclusion.list:}#{T(java.util.Arrays).asList(\"DbEdgeRules_.*.json\")}") + private List edgesInclusionPattern; + + @Value("${schema.edges.exclusion.list:}#{T(java.util.Collections).emptyList()}") + private List edgesExclusionPattern; + + /** + * @return the file name/location with the list of schema files to be ingested + */ + public String getSchemaConfigLocation() { + return schemaConfigLoc; + } + + /** + * Sets the name/location of the file with the list of schema files to ingest + * + * @param schemaConfigLoc - the file name/location + */ + public void setSchemaConfigLocation(String schemaConfigLoc) { + this.schemaConfigLoc = schemaConfigLoc; + } + + /** + * @return the location of the OXM files + */ + public String getNodeDirectory() { + return nodeDirectory; + } + + /** + * Sets the location of the OXM files + * + * @param nodeDirectory - the location of the OXM files + */ + public void setNodeDirectory(String nodeDirectory) { + this.nodeDirectory = nodeDirectory; + } + + /** + * @return the location of the edge rule json files + */ + public String getEdgeDirectory() { + return edgeDirectory; + } + + /** + * Sets the location of the edge rule json files + * + * @param edgeDirectory - the location of the edge rule files + */ + public void setEdgeDirectory(String edgeDirectory) { + this.edgeDirectory = edgeDirectory; + } + + public List getNodesExclusionPattern() { + return this.nodesExclusionPattern; + } + + public List getNodesInclusionPattern() { + return this.nodesInclusionPattern; + } + + public List getEdgesExclusionPattern() { + return this.edgesExclusionPattern; + } + + public List getEdgesInclusionPattern() { + return this.edgesInclusionPattern; + } + + // this allows the code to actually read the value from the config file + // without this those strings get set to literally "${edgeDir}" etc + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeResource.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeResource.java index cb045ea..bae48c3 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeResource.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeResource.java @@ -8,7 +8,7 @@ * 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, @@ -17,18 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.edges; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.restcore.HttpMethod; -import org.onap.aai.restcore.RESTAPI; -import org.onap.aai.schemaservice.nodeschema.SchemaVersion; -import org.onap.aai.schemaservice.nodeschema.SchemaVersions; -import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.StringUtils; + +import java.util.Optional; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -38,7 +33,15 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; -import java.util.Optional; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.restcore.RESTAPI; +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +import org.onap.aai.schemaservice.nodeschema.SchemaVersions; +import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; @Path("/v1") public class EdgeResource extends RESTAPI { @@ -48,46 +51,46 @@ public class EdgeResource extends RESTAPI { private final Gson gson; @Autowired - public EdgeResource(EdgeService edgeService, SchemaVersions schemaVersions){ - this.edgeService = edgeService; + public EdgeResource(EdgeService edgeService, SchemaVersions schemaVersions) { + this.edgeService = edgeService; this.schemaVersions = schemaVersions; gson = new GsonBuilder().create(); } @GET @Path("/edgerules") - @Produces({ "application/json"}) + @Produces({"application/json"}) public Response retrieveSchema(@QueryParam("version") String version, - @Context HttpHeaders headers, - @Context UriInfo info) - { + @Context HttpHeaders headers, @Context UriInfo info) { Response response = null; try { - if(StringUtils.isEmpty(version)){ + if (StringUtils.isEmpty(version)) { throw new AAIException("AAI_3050"); } SchemaVersion schemaVersion = new SchemaVersion(version); - if(!schemaVersions.getVersions().contains(schemaVersion)){ + if (!schemaVersions.getVersions().contains(schemaVersion)) { throw new AAIException("AAI_3018", version); } Optional edgeRulesOptional = edgeService.findRules(version); - if(!edgeRulesOptional.isPresent()){ + if (!edgeRulesOptional.isPresent()) { throw new AAIException("AAI_3001"); } response = Response.ok(gson.toJson(edgeRulesOptional.get())).build(); - } catch(AAIException ex){ + } catch (AAIException ex) { response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex); - } catch(AAISchemaValidationException ex){ - response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, new AAIException("AAI_3051", version)); - } catch(Exception ex){ - response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, new AAIException("AAI_4000")); + } catch (AAISchemaValidationException ex) { + response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, + new AAIException("AAI_3051", version)); + } catch (Exception ex) { + response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, + new AAIException("AAI_4000")); } return response; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRule.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRule.java index ab0f311..e7eb15b 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRule.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRule.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.edges; import com.google.gson.annotations.SerializedName; @@ -36,19 +37,11 @@ public class EdgeRule { @Override public String toString() { - return "EdgeRule{" + - "from='" + from + '\'' + - ", to='" + to + '\'' + - ", label='" + label + '\'' + - ", direction='" + direction + '\'' + - ", multiplicity='" + multiplicity + '\'' + - ", description='" + description + '\'' + - ", containsOtherV='" + containsOtherV + '\'' + - ", deleteOtherV='" + deleteOtherV + '\'' + - ", preventDelete='" + preventDelete + '\'' + - ", privateEdge=" + privateEdge + - ", isDefaultEdge=" + defaultEdge + - '}'; + return "EdgeRule{" + "from='" + from + '\'' + ", to='" + to + '\'' + ", label='" + label + + '\'' + ", direction='" + direction + '\'' + ", multiplicity='" + multiplicity + '\'' + + ", description='" + description + '\'' + ", containsOtherV='" + containsOtherV + '\'' + + ", deleteOtherV='" + deleteOtherV + '\'' + ", preventDelete='" + preventDelete + '\'' + + ", privateEdge=" + privateEdge + ", isDefaultEdge=" + defaultEdge + '}'; } @SerializedName("delete-other-v") diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRules.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRules.java index ec68d30..bad43d3 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRules.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeRules.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.edges; import com.google.gson.annotations.SerializedName; @@ -29,7 +30,7 @@ public class EdgeRules { @SerializedName("rules") private List rules; - public EdgeRules(List rules){ + public EdgeRules(List rules) { this.rules = rules; } @@ -64,9 +65,7 @@ public class EdgeRules { @Override public String toString() { - return "EdgeRules{" + - "rules=" + rules + - '}'; + return "EdgeRules{" + "rules=" + rules + '}'; } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeService.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeService.java index a4eba45..0b2cc75 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeService.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/edges/EdgeService.java @@ -8,7 +8,7 @@ * 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, @@ -17,21 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.edges; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; -import org.onap.aai.schemaservice.nodeschema.SchemaVersion; -import org.onap.aai.schemaservice.nodeschema.SchemaVersions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -42,6 +35,16 @@ import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.annotation.PostConstruct; + +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +import org.onap.aai.schemaservice.nodeschema.SchemaVersions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + @Service public class EdgeService { @@ -56,39 +59,42 @@ public class EdgeService { @Autowired public EdgeService(SchemaVersions schemaVersions, - @Value("${schema.edges.location}") String edgesLocation){ + @Value("${schema.edges.location}") String edgesLocation) { this.schemaVersions = schemaVersions; - this.edgesLocation = edgesLocation; - this.rulesMap = new HashMap<>(); + this.edgesLocation = edgesLocation; + this.rulesMap = new HashMap<>(); } @PostConstruct public void initialize() throws IOException { - Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create(); + Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) + .create(); for (SchemaVersion schemaVersion : schemaVersions.getVersions()) { String edgeRuleVersionPath = edgesLocation + FILESEP + schemaVersion.toString(); - LOGGER.debug("For the version {} looking for edge rules in folder {}", schemaVersion, edgeRuleVersionPath); + LOGGER.debug("For the version {} looking for edge rules in folder {}", schemaVersion, + edgeRuleVersionPath); - try (Stream pathStream = Files.walk(Paths.get(edgeRuleVersionPath))){ + try (Stream pathStream = Files.walk(Paths.get(edgeRuleVersionPath))) { - List jsonFiles = pathStream - .filter((path) -> path.toString().endsWith(".json")) - .collect(Collectors.toList()); + List jsonFiles = + pathStream.filter((path) -> path.toString().endsWith(".json")) + .collect(Collectors.toList()); - if(jsonFiles.isEmpty()){ - LOGGER.error("Unable to find any edge rules json files in folder {}", edgeRuleVersionPath); + if (jsonFiles.isEmpty()) { + LOGGER.error("Unable to find any edge rules json files in folder {}", + edgeRuleVersionPath); } else { LOGGER.trace("Found the following edge rules {}", jsonFiles); } List rules = new ArrayList<>(); - for(Path path : jsonFiles){ + for (Path path : jsonFiles) { File edgeRuleFile = path.toFile(); - try (JsonReader jsonReader = new JsonReader(new FileReader(edgeRuleFile))){ + try (JsonReader jsonReader = new JsonReader(new FileReader(edgeRuleFile))) { EdgeRules edgeRules = gson.fromJson(jsonReader, EdgeRules.class); rules.addAll(edgeRules.getRules()); } @@ -100,7 +106,7 @@ public class EdgeService { } - public Optional findRules(String version){ + public Optional findRules(String version) { return Optional.ofNullable(rulesMap.get(version)); } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/healthcheck/EchoResource.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/healthcheck/EchoResource.java index 2a98876..47552b1 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/healthcheck/EchoResource.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/healthcheck/EchoResource.java @@ -8,7 +8,7 @@ * 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, @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.healthcheck; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.logging.ErrorLogHelper; -import org.onap.aai.restcore.RESTAPI; +import java.util.ArrayList; +import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; @@ -29,8 +29,10 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.*; import javax.ws.rs.core.Response.Status; -import java.util.ArrayList; -import java.util.HashMap; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.restcore.RESTAPI; /** * The Class EchoResponse. @@ -40,7 +42,8 @@ public class EchoResource extends RESTAPI { /** * Simple health-check API that echos back the X-FromAppId and X-TransactionId to clients. - * If there is a query string, a transaction gets logged into hbase, proving the application is connected to the data store. + * If there is a query string, a transaction gets logged into hbase, proving the application is + * connected to the data store. * If there is no query string, no transaction logging is done to hbase. * * @param headers the headers @@ -48,9 +51,10 @@ public class EchoResource extends RESTAPI { * @return the response */ @GET - @Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/echo") - public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req, @Context UriInfo uriInfo) { + public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req, + @Context UriInfo uriInfo) { Response response = null; AAIException ex = null; @@ -58,20 +62,21 @@ public class EchoResource extends RESTAPI { String transId = null; try { - fromAppId = getFromAppId(headers ); + fromAppId = getFromAppId(headers); transId = getTransId(headers); } catch (AAIException e) { ArrayList templateVars = new ArrayList(); templateVars.add("Headers missing"); return Response - .status(e.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars)) + .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper + .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars)) .build(); } try { - HashMap> exceptionList = new HashMap>(); + HashMap> exceptionList = + new HashMap>(); ArrayList templateVars = new ArrayList(); templateVars.add(fromAppId); @@ -79,22 +84,21 @@ public class EchoResource extends RESTAPI { exceptionList.put(new AAIException("AAI_0002", "OK"), templateVars); - response = Response.status(Status.OK) - .entity(ErrorLogHelper.getRESTAPIInfoResponse( - headers.getAcceptableMediaTypes(), exceptionList)) + response = Response + .status(Status.OK).entity(ErrorLogHelper + .getRESTAPIInfoResponse(headers.getAcceptableMediaTypes(), exceptionList)) .build(); } catch (Exception e) { ex = new AAIException("AAI_4000", e); ArrayList templateVars = new ArrayList(); templateVars.add(Action.GET.name()); - templateVars.add(fromAppId +" "+transId); + templateVars.add(fromAppId + " " + transId); response = Response - .status(Status.INTERNAL_SERVER_ERROR) - .entity(ErrorLogHelper.getRESTAPIErrorResponse( - headers.getAcceptableMediaTypes(), ex, - templateVars)).build(); + .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper + .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars)) + .build(); } finally { if (ex != null) { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIContainerFilter.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIContainerFilter.java index e5588b6..cb04bc4 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIContainerFilter.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIContainerFilter.java @@ -8,7 +8,7 @@ * 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, @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.interceptors; -import org.onap.aai.util.FormatDate; +package org.onap.aai.schemaservice.interceptors; import java.util.UUID; +import org.onap.aai.util.FormatDate; + public abstract class AAIContainerFilter { protected String genDate() { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIHeaderProperties.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIHeaderProperties.java index 8f08d3f..467475b 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIHeaderProperties.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/AAIHeaderProperties.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors; public final class AAIHeaderProperties { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/package-info.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/package-info.java index 6cf55f0..4929cc0 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/package-info.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/package-info.java @@ -8,7 +8,7 @@ * 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, @@ -26,11 +26,12 @@ * *
          *     
        - *         @Priority(AAIRequestFilterPriority.YOUR_PRIORITY)
        + *         @Priority(AAIRequestFilterPriority.YOUR_PRIORITY)
          *         public class YourInterceptor extends AAIContainerFilter implements ContainerRequestFilter {
          *
          *         }
          *     
          * 
        */ + package org.onap.aai.schemaservice.interceptors; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/AAIResponseFilterPriority.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/AAIResponseFilterPriority.java index fceadeb..b4144bb 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/AAIResponseFilterPriority.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/AAIResponseFilterPriority.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.post; /** diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/InvalidResponseStatus.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/InvalidResponseStatus.java index d987171..5f80b2b 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/InvalidResponseStatus.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/InvalidResponseStatus.java @@ -8,7 +8,7 @@ * 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, @@ -17,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.post; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.logging.ErrorLogHelper; -import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import javax.annotation.Priority; import javax.print.attribute.standard.Media; @@ -30,16 +31,17 @@ import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; @Priority(AAIResponseFilterPriority.INVALID_RESPONSE_STATUS) public class InvalidResponseStatus extends AAIContainerFilter implements ContainerResponseFilter { @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) - throws IOException { + public void filter(ContainerRequestContext requestContext, + ContainerResponseContext responseContext) throws IOException { String contentType = responseContext.getHeaderString("Content-Type"); ArrayList templateVars = new ArrayList<>(); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseHeaderManipulation.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseHeaderManipulation.java index 76d14b6..170ac40 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseHeaderManipulation.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseHeaderManipulation.java @@ -21,11 +21,13 @@ package org.onap.aai.schemaservice.interceptors.post; import java.io.IOException; + import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MediaType; + import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; @@ -38,15 +40,14 @@ public class ResponseHeaderManipulation extends AAIContainerFilter @Override public void filter(ContainerRequestContext requestContext, - ContainerResponseContext responseContext) - throws IOException { + ContainerResponseContext responseContext) throws IOException { updateResponseHeaders(requestContext, responseContext); } private void updateResponseHeaders(ContainerRequestContext requestContext, - ContainerResponseContext responseContext) { + ContainerResponseContext responseContext) { responseContext.getHeaders().add(AAIHeaderProperties.AAI_TX_ID, requestContext.getProperty(AAIHeaderProperties.AAI_TX_ID)); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseTransactionLogging.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseTransactionLogging.java index 11f3737..f89440a 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseTransactionLogging.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/post/ResponseTransactionLogging.java @@ -8,7 +8,7 @@ * 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, @@ -17,18 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.post; import com.google.gson.JsonObject; + import java.io.IOException; import java.util.Objects; import java.util.Optional; + import javax.annotation.Priority; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.HttpMethod; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; + import org.onap.aai.logging.ErrorLogHelper; import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; @@ -40,39 +44,42 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Priority(AAIResponseFilterPriority.RESPONSE_TRANS_LOGGING) -public class ResponseTransactionLogging extends AAIContainerFilter implements ContainerResponseFilter { +public class ResponseTransactionLogging extends AAIContainerFilter + implements ContainerResponseFilter { - private static final Logger TRANSACTION_LOGGER = LoggerFactory.getLogger(ResponseTransactionLogging.class); + private static final Logger TRANSACTION_LOGGER = + LoggerFactory.getLogger(ResponseTransactionLogging.class); @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) - throws IOException { + public void filter(ContainerRequestContext requestContext, + ContainerResponseContext responseContext) throws IOException { this.transLogging(requestContext, responseContext); } - private void transLogging(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { + private void transLogging(ContainerRequestContext requestContext, + ContainerResponseContext responseContext) { String logValue = AAIConfig.get("aai.transaction.logging", "true"); - String isGetTransactionResponseLoggingEnabled = AAIConfig.get("aai.transaction.logging.get", "false"); + String isGetTransactionResponseLoggingEnabled = + AAIConfig.get("aai.transaction.logging.get", "false"); String httpMethod = requestContext.getMethod(); - if(Boolean.parseBoolean(logValue)){ + if (Boolean.parseBoolean(logValue)) { String transId = requestContext.getHeaderString(AAIHeaderProperties.TRANSACTION_ID); String fromAppId = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID); String fullUri = requestContext.getUriInfo().getRequestUri().toString(); - String requestTs = (String) requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST_TS); - + String requestTs = + (String) requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST_TS); String status = Integer.toString(responseContext.getStatus()); String request = (String) requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST); String response = this.getResponseString(responseContext); - JsonObject logEntry = new JsonObject(); logEntry.addProperty("transactionId", transId); logEntry.addProperty("status", status); @@ -82,7 +89,8 @@ public class ResponseTransactionLogging extends AAIContainerFilter implements Co logEntry.addProperty("resourceId", fullUri); logEntry.addProperty("resourceType", httpMethod); logEntry.addProperty("rqstBuf", Objects.toString(request, "")); - if(Boolean.parseBoolean(isGetTransactionResponseLoggingEnabled) || (!HttpMethod.GET.equals(httpMethod))) { + if (Boolean.parseBoolean(isGetTransactionResponseLoggingEnabled) + || (!HttpMethod.GET.equals(httpMethod))) { logEntry.addProperty("respBuf", Objects.toString(response, "")); } @@ -97,7 +105,8 @@ public class ResponseTransactionLogging extends AAIContainerFilter implements Co private String getHttpServletResponseContentType() { final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes != null) { - HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); + HttpServletResponse response = + ((ServletRequestAttributes) requestAttributes).getResponse(); return response == null ? null : response.getContentType(); } return null; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/AAIRequestFilterPriority.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/AAIRequestFilterPriority.java index 0ecc0cf..423ff61 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/AAIRequestFilterPriority.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/AAIRequestFilterPriority.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; public final class AAIRequestFilterPriority { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HeaderValidation.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HeaderValidation.java index 66be48e..3b22ff0 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HeaderValidation.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HeaderValidation.java @@ -8,7 +8,7 @@ * 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, @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.logging.ErrorLogHelper; -import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; -import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.ref.slf4j.ONAPLogConstants; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; @@ -32,10 +31,13 @@ import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; +import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; @PreMatching @Priority(AAIRequestFilterPriority.HEADER_VALIDATION) @@ -62,18 +64,21 @@ public class HeaderValidation extends AAIContainerFilter implements ContainerReq } private Optional validateHeaderValuePresence(String value, String errorCode, - List acceptHeaderValues) { + List acceptHeaderValues) { Response response = null; AAIException aaie; if (value == null || value.isEmpty()) { aaie = new AAIException(errorCode); - return Optional.of(Response.status(aaie.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>())) - .build()); + return Optional + .of(Response + .status(aaie.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper + .getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>())) + .build()); } return Optional.ofNullable(response); } + public String getRequestId(ContainerRequestContext requestContext) { String requestId = requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID); if (requestId == null || requestId.isEmpty()) { @@ -81,7 +86,8 @@ public class HeaderValidation extends AAIContainerFilter implements ContainerReq if (requestId == null || requestId.isEmpty()) { requestId = requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID); if (requestId == null || requestId.isEmpty()) { - requestId = requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID); + requestId = + requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID); if (requestId == null || requestId.isEmpty()) { return requestId; } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HttpHeaderInterceptor.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HttpHeaderInterceptor.java index 26765e5..2830456 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HttpHeaderInterceptor.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/HttpHeaderInterceptor.java @@ -8,7 +8,7 @@ * 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, @@ -17,17 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; -import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; -import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; +import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.HttpMethod; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; -import java.io.IOException; + +import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; +import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; /** * The Class HttpHeaderInterceptor @@ -39,10 +41,12 @@ public class HttpHeaderInterceptor extends AAIContainerFilter implements Contain @Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { - String overrideMethod = containerRequestContext.getHeaderString(AAIHeaderProperties.HTTP_METHOD_OVERRIDE); + String overrideMethod = + containerRequestContext.getHeaderString(AAIHeaderProperties.HTTP_METHOD_OVERRIDE); String httpMethod = containerRequestContext.getMethod(); - if (HttpMethod.POST.equalsIgnoreCase(httpMethod) && patchMethod.equalsIgnoreCase(overrideMethod)) { + if (HttpMethod.POST.equalsIgnoreCase(httpMethod) + && patchMethod.equalsIgnoreCase(overrideMethod)) { containerRequestContext.setMethod(patchMethod); } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/OneWaySslAuthorization.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/OneWaySslAuthorization.java index 989e56a..32bf3d8 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/OneWaySslAuthorization.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/OneWaySslAuthorization.java @@ -8,7 +8,7 @@ * 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, @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.logging.ErrorLogHelper; -import org.onap.aai.schemaservice.Profiles; -import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; -import org.onap.aai.schemaservice.service.AuthorizationService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; @@ -33,10 +31,14 @@ import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.schemaservice.Profiles; +import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; +import org.onap.aai.schemaservice.service.AuthorizationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; @Profile(Profiles.ONE_WAY_SSL) @PreMatching @@ -49,7 +51,8 @@ public class OneWaySslAuthorization extends AAIContainerFilter implements Contai @Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { - if (containerRequestContext.getUriInfo().getRequestUri().getPath().matches("^.*/util/echo$")) { + if (containerRequestContext.getUriInfo().getRequestUri().getPath() + .matches("^.*/util/echo$")) { return; } @@ -75,7 +78,8 @@ public class OneWaySslAuthorization extends AAIContainerFilter implements Contai private Optional errorResponse(String errorCode, List acceptHeaderValues) { AAIException aaie = new AAIException(errorCode); return Optional.of(Response.status(aaie.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>())) + .entity( + ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>())) .build()); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestHeaderManipulation.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestHeaderManipulation.java index 211350a..996ae68 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestHeaderManipulation.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestHeaderManipulation.java @@ -8,7 +8,7 @@ * 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, @@ -17,23 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; -import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; -import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; +import java.util.Collections; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.MultivaluedMap; -import java.util.Collections; -import java.util.regex.Matcher; -import java.util.regex.Pattern; + +import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; +import org.onap.aai.schemaservice.interceptors.AAIHeaderProperties; @PreMatching @Priority(AAIRequestFilterPriority.HEADER_MANIPULATION) -public class RequestHeaderManipulation extends AAIContainerFilter implements ContainerRequestFilter { +public class RequestHeaderManipulation extends AAIContainerFilter + implements ContainerRequestFilter { public static final Pattern EXTRACT_VERSION_PATTERN = Pattern.compile("^(v[1-9][0-9]*).*$"); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestTransactionLogging.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestTransactionLogging.java index fbf9fbe..cfbd364 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestTransactionLogging.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/interceptors/pre/RequestTransactionLogging.java @@ -8,7 +8,7 @@ * 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, @@ -17,20 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.interceptors.pre; import com.google.gson.JsonObject; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; + import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.MediaType; + import org.glassfish.jersey.message.internal.ReaderWriter; import org.glassfish.jersey.server.ContainerException; import org.onap.aai.schemaservice.interceptors.AAIContainerFilter; @@ -42,7 +46,8 @@ import org.springframework.web.context.request.ServletRequestAttributes; @PreMatching @Priority(AAIRequestFilterPriority.REQUEST_TRANS_LOGGING) -public class RequestTransactionLogging extends AAIContainerFilter implements ContainerRequestFilter { +public class RequestTransactionLogging extends AAIContainerFilter + implements ContainerRequestFilter { private static final String DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON; private static final String DEFAULT_RESPONSE_TYPE = MediaType.APPLICATION_XML; @@ -56,12 +61,15 @@ public class RequestTransactionLogging extends AAIContainerFilter implements Con String currentTimeStamp = genDate(); String fullId = this.getAAITxIdToHeader(); this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_TX_ID, fullId); - this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST, this.getRequest(requestContext, fullId)); - this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST_TS, currentTimeStamp); + this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST, + this.getRequest(requestContext, fullId)); + this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST_TS, + currentTimeStamp); this.addDefaultContentType(requestContext); } - private void addToRequestContext(ContainerRequestContext requestContext, String name, String aaiTxIdToHeader) { + private void addToRequestContext(ContainerRequestContext requestContext, String name, + String aaiTxIdToHeader) { requestContext.setProperty(name, aaiTxIdToHeader); } @@ -87,7 +95,8 @@ public class RequestTransactionLogging extends AAIContainerFilter implements Con private String getHttpServletRequestContentType() { final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes != null) { - HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + HttpServletRequest request = + ((ServletRequestAttributes) requestAttributes).getRequest(); return request.getContentType(); } return null; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/logging/LocalHostAccessLog.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/logging/LocalHostAccessLog.java index 9ff3cb2..dc42bde 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/logging/LocalHostAccessLog.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/logging/LocalHostAccessLog.java @@ -8,7 +8,7 @@ * 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, @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.logging; import ch.qos.logback.access.jetty.RequestLogImpl; + +import java.util.Arrays; + import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; @@ -30,16 +34,13 @@ import org.springframework.boot.web.servlet.server.AbstractServletWebServerFacto import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Arrays; - @Configuration public class LocalHostAccessLog { @Bean public AbstractServletWebServerFactory jettyConfigBean( @Value("${jetty.threadPool.maxThreads:200}") final String maxThreads, - @Value("${jetty.threadPool.minThreads:8}") final String minThreads - ) { + @Value("${jetty.threadPool.minThreads:8}") final String minThreads) { JettyServletWebServerFactory jef = new JettyServletWebServerFactory(); jef.addServerCustomizers((JettyServerCustomizer) server -> { diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeIngestor.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeIngestor.java index 2459c54..713b078 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeIngestor.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeIngestor.java @@ -8,7 +8,7 @@ * 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, @@ -23,7 +23,9 @@ package org.onap.aai.schemaservice.nodeschema; import com.google.common.base.CaseFormat; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; + import jakarta.xml.bind.JAXBException; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -42,10 +44,12 @@ import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; + import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; + import org.eclipse.persistence.jaxb.JAXBContextProperties; import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; @@ -74,13 +78,12 @@ public class NodeIngestor { private Map schemaPerVersion = new TreeMap<>(); private ConfigTranslator translator; - @Autowired /** * Instantiates the NodeIngestor bean. * * @param translator - ConfigTranslator autowired in by Spring framework which - * contains the configuration information needed to ingest the desired files. + * contains the configuration information needed to ingest the desired files. */ public NodeIngestor(ConfigTranslator translator) { this.translator = translator; @@ -106,7 +109,7 @@ public class NodeIngestor { * @param files - List of full filenames (ie including the path) to be ingested * @return DynamicJAXBContext including schema information from all given files * @throws FileNotFoundException if an OXM file can't be found - * @throws JAXBException if there's an error creating the DynamicJAXBContext + * @throws JAXBException if there's an error creating the DynamicJAXBContext */ private DynamicJAXBContext ingest(List files) throws FileNotFoundException, JAXBException { @@ -118,11 +121,10 @@ public class NodeIngestor { Map properties = new HashMap<>(); properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, streams); - return DynamicJAXBContextFactory - .createContextFromOXM(this.getClass().getClassLoader(), properties); + return DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), + properties); } - private Set getAllNodeTypes(List files) throws ParserConfigurationException, SAXException, IOException { Set types = new HashSet<>(); @@ -142,7 +144,6 @@ public class NodeIngestor { final Document doc = docBuilder.parse(inputStream); final NodeList list = doc.getElementsByTagName("java-type"); - for (int i = 0; i < list.getLength(); i++) { String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue(); javaTypes.add(list.item(i)); @@ -194,7 +195,7 @@ public class NodeIngestor { } private void createNode(Document combinedDoc, Node javaTypesContainer, - Map> map) { + Map> map) { for (Entry> entry : map.entrySet()) { @@ -212,9 +213,8 @@ public class NodeIngestor { Element element = (Element) copyOfFirstElement; NodeList javaAttributesList = element.getElementsByTagName("java-attributes"); - for (int javaAttributeIndex = 0; - javaAttributeIndex < javaAttributesList.getLength(); - javaAttributeIndex++) { + for (int javaAttributeIndex = 0; javaAttributeIndex < javaAttributesList + .getLength(); javaAttributeIndex++) { javaAttributeElement = javaAttributesList.item(javaAttributeIndex); } } @@ -225,14 +225,12 @@ public class NodeIngestor { Element element = (Element) copyOfCurrentElement; NodeList javaAttributesList = element.getElementsByTagName("java-attributes"); - for (int javaAttributeIndex = 0; - javaAttributeIndex < javaAttributesList.getLength(); - javaAttributeIndex++) { + for (int javaAttributeIndex = 0; javaAttributeIndex < javaAttributesList + .getLength(); javaAttributeIndex++) { Node jaElement = javaAttributesList.item(javaAttributeIndex); NodeList xmlElementList = jaElement.getChildNodes(); - for (int xmlElementIndex = 0; - xmlElementIndex < xmlElementList.getLength(); - xmlElementIndex++) { + for (int xmlElementIndex = 0; xmlElementIndex < xmlElementList + .getLength(); xmlElementIndex++) { if (javaAttributeElement != null) { Node curElem = xmlElementList.item(xmlElementIndex); if (curElem != null) { @@ -267,7 +265,7 @@ public class NodeIngestor { * Determines if the given version contains the given node type * * @param nodeType - node type to check, must be in lower hyphen form (ie "type-name") - * @param v - schema version to check against + * @param v - schema version to check against * @return */ public boolean hasNodeType(String nodeType, SchemaVersion v) { @@ -283,20 +281,16 @@ public class NodeIngestor { } private InputStream getShell(SchemaVersion v) { - String source = "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + String source = "\n" + + "\n" + + " \n" + + " \n" + " \n" + " \n" + + " \n" + ""; return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)); } - public SchemaVersion getVersionFromClassName(String classname) { Matcher m = classNamePattern.matcher(classname); String version = null; @@ -308,4 +302,3 @@ public class NodeIngestor { } } } - diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResource.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResource.java index 4eccd71..9c1f894 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResource.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResource.java @@ -8,7 +8,7 @@ * 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, @@ -17,14 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.restcore.HttpMethod; -import org.onap.aai.restcore.RESTAPI; -import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.StringUtils; +import java.util.Optional; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -34,7 +30,13 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; -import java.util.Optional; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.restcore.RESTAPI; +import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; @Path("/v1") public class NodeSchemaResource extends RESTAPI { @@ -46,27 +48,25 @@ public class NodeSchemaResource extends RESTAPI { @Autowired public NodeSchemaResource(NodeSchemaService nodeSchemaService, SchemaVersions schemaVersions) { this.nodeSchemaService = nodeSchemaService; - this.schemaVersions = schemaVersions; + this.schemaVersions = schemaVersions; } @GET @Path("/nodes") - @Produces({ "application/xml"}) + @Produces({"application/xml"}) public Response retrieveSchema(@QueryParam("version") String version, - @Context HttpHeaders headers, - @Context UriInfo info) - { + @Context HttpHeaders headers, @Context UriInfo info) { Response response; Optional optionalSchema = nodeSchemaService.fetch(version); try { - if(StringUtils.isEmpty(version)){ + if (StringUtils.isEmpty(version)) { throw new AAIException("AAI_3050"); } SchemaVersion schemaVersion = new SchemaVersion(version); - if(!schemaVersions.getVersions().contains(schemaVersion)){ + if (!schemaVersions.getVersions().contains(schemaVersion)) { throw new AAIException("AAI_3018", version); } @@ -76,12 +76,14 @@ public class NodeSchemaResource extends RESTAPI { response = Response.ok(optionalSchema.get()).build(); - } catch(AAIException ex){ + } catch (AAIException ex) { response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex); - } catch(AAISchemaValidationException ex){ - response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, new AAIException("AAI_3051", version)); - } catch(Exception ex){ - response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, new AAIException("AAI_4000")); + } catch (AAISchemaValidationException ex) { + response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, + new AAIException("AAI_3051", version)); + } catch (Exception ex) { + response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, + new AAIException("AAI_4000")); } return response; diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaService.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaService.java index 8c6399b..26214aa 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaService.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaService.java @@ -8,7 +8,7 @@ * 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, @@ -17,17 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.nodeschema; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.onap.aai.logging.LogFormatTools; -import org.springframework.stereotype.Service; +package org.onap.aai.schemaservice.nodeschema; -import javax.annotation.PostConstruct; -import javax.xml.transform.*; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; @@ -35,6 +27,16 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; +import javax.annotation.PostConstruct; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.onap.aai.logging.LogFormatTools; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + @Service public class NodeSchemaService { @@ -62,8 +64,8 @@ public class NodeSchemaService { try { transformer = tf.newTransformer(); } catch (TransformerConfigurationException e) { - LOGGER.warn("Encountered an transformer configuration exception" + - "during node schema service startup ", LogFormatTools.getStackTop(e)); + LOGGER.warn("Encountered an transformer configuration exception" + + "during node schema service startup ", LogFormatTools.getStackTop(e)); } transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); @@ -74,12 +76,13 @@ public class NodeSchemaService { try { DOMSource domSource = new DOMSource(nodeIngestor.getSchema(schemaVersion)); - StreamResult streamResult = new StreamResult(new OutputStreamWriter(buffer, "UTF-8")); + StreamResult streamResult = + new StreamResult(new OutputStreamWriter(buffer, "UTF-8")); transformer.transform(domSource, streamResult); versionMap.put(schemaVersion.toString(), buffer.toString("UTF-8")); } catch (TransformerException | UnsupportedEncodingException e) { - LOGGER.warn("Encountered an transformer or unsupported encoding exception " + - "during node schema service startup ", LogFormatTools.getStackTop(e)); + LOGGER.warn("Encountered an transformer or unsupported encoding exception " + + "during node schema service startup ", LogFormatTools.getStackTop(e)); } })); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersion.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersion.java index fc5b48c..380d15f 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersion.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersion.java @@ -8,7 +8,7 @@ * 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, @@ -17,59 +17,61 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.nodeschema; -import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; +package org.onap.aai.schemaservice.nodeschema; import java.util.regex.Pattern; +import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; + public class SchemaVersion implements Comparable { public static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); private final String value; - public SchemaVersion(String value){ + public SchemaVersion(String value) { - if(!VERSION_PATTERN.matcher(value).matches()){ - throw new AAISchemaValidationException("Invalid Schema Version " + value + ", value doesn't match the expected regex: " + VERSION_PATTERN); + if (!VERSION_PATTERN.matcher(value).matches()) { + throw new AAISchemaValidationException("Invalid Schema Version " + value + + ", value doesn't match the expected regex: " + VERSION_PATTERN); } this.value = value; } @Override - public int hashCode(){ + public int hashCode() { return value.hashCode(); } @Override - public boolean equals(Object other){ - if(this == other){ + public boolean equals(Object other) { + if (this == other) { return true; } - if(other == null){ + if (other == null) { return false; } - if(!(other instanceof SchemaVersion)){ + if (!(other instanceof SchemaVersion)) { return false; } - SchemaVersion obj = (SchemaVersion)other; + SchemaVersion obj = (SchemaVersion) other; return this.value.equals(obj.value); } @Override - public String toString(){ + public String toString() { return value; } @Override public int compareTo(SchemaVersion o) { - if(o == null){ + if (o == null) { return -1; } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersions.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersions.java index 208d5d0..a8dc5dd 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersions.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/SchemaVersions.java @@ -8,7 +8,7 @@ * 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, @@ -17,17 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema; +import java.util.List; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; + import org.onap.aai.schemaservice.nodeschema.validation.AAISchemaValidationException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import java.util.List; -import java.util.stream.Collectors; - @Component @PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound = true) @PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound = true) @@ -67,59 +69,53 @@ public class SchemaVersions { public void initialize() { versions = apiVersions.stream().map(SchemaVersion::new).collect(Collectors.toList()); - edgeLabelVersion = new SchemaVersion(edgeLabelStartVersion); - defaultVersion = new SchemaVersion(defaultApiVersion); - depthVersion = new SchemaVersion(depthStartVersion); - appRootVersion = new SchemaVersion(appRootStartVersion); - relatedLinkVersion = new SchemaVersion(relatedLinkStartVersion); + edgeLabelVersion = new SchemaVersion(edgeLabelStartVersion); + defaultVersion = new SchemaVersion(defaultApiVersion); + depthVersion = new SchemaVersion(depthStartVersion); + appRootVersion = new SchemaVersion(appRootStartVersion); + relatedLinkVersion = new SchemaVersion(relatedLinkStartVersion); namespaceChangeVersion = new SchemaVersion(namespaceChangeStartVersion); if (!versions.contains(edgeLabelVersion)) { throw new AAISchemaValidationException( - "Invalid, edge label version is not in the api versions list" + "Invalid, edge label version is not in the api versions list" + ", please check schema.version.list and ensure that the" - + " schema.version.edge.label.start is in that list" - ); + + " schema.version.edge.label.start is in that list"); } if (!versions.contains(defaultVersion)) { throw new AAISchemaValidationException( - "Invalid, default version is not in the api versions list" - + ", please check schema.version.list and ensure that the" - + " schema.version.api.default is in that list" - ); + "Invalid, default version is not in the api versions list" + + ", please check schema.version.list and ensure that the" + + " schema.version.api.default is in that list"); } if (!versions.contains(depthVersion)) { throw new AAISchemaValidationException( - "Invalid, depth version is not in the api versions list" - + ", please check schema.version.list and ensure that the" - + " schema.version.depth.start is in that list" - ); + "Invalid, depth version is not in the api versions list" + + ", please check schema.version.list and ensure that the" + + " schema.version.depth.start is in that list"); } - if(!versions.contains(appRootVersion)){ + if (!versions.contains(appRootVersion)) { throw new AAISchemaValidationException( - "Invalid, app root version is not in the api versions list" - + ", please check schema.version.list and ensure that the" - + " schema.version.app.root.start is in that list" - ); + "Invalid, app root version is not in the api versions list" + + ", please check schema.version.list and ensure that the" + + " schema.version.app.root.start is in that list"); } - if(!versions.contains(relatedLinkVersion)){ + if (!versions.contains(relatedLinkVersion)) { throw new AAISchemaValidationException( - "Invalid, related link version is not in the api versions list" - + ", please check schema.version.list and ensure that the" - + " schema.version.related.link.start is in that list" - ); + "Invalid, related link version is not in the api versions list" + + ", please check schema.version.list and ensure that the" + + " schema.version.related.link.start is in that list"); } - if(!versions.contains(namespaceChangeVersion)){ + if (!versions.contains(namespaceChangeVersion)) { throw new AAISchemaValidationException( - "Invalid, namespace change start version is not in the api versions list" - + ", please check schema.version.list and ensure that the" - + " schema.version.related.link.start is in that list" - ); + "Invalid, namespace change start version is not in the api versions list" + + ", please check schema.version.list and ensure that the" + + " schema.version.related.link.start is in that list"); } } @@ -139,11 +135,11 @@ public class SchemaVersions { return depthVersion; } - public SchemaVersion getAppRootVersion(){ + public SchemaVersion getAppRootVersion() { return appRootVersion; } - public SchemaVersion getRelatedLinkVersion(){ + public SchemaVersion getRelatedLinkVersion() { return relatedLinkVersion; } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/AAISchemaValidationException.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/AAISchemaValidationException.java index fecc079..4d35e83 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/AAISchemaValidationException.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/AAISchemaValidationException.java @@ -8,7 +8,7 @@ * 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, @@ -17,13 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; /** * Indicates that a fatal error in the A&AI schema has been found. */ public class AAISchemaValidationException extends IllegalStateException { - public AAISchemaValidationException(String msg) { - super(msg); - } + public AAISchemaValidationException(String msg) { + super(msg); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/CheckEverythingStrategy.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/CheckEverythingStrategy.java index 047760f..40768b6 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/CheckEverythingStrategy.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/CheckEverythingStrategy.java @@ -8,7 +8,7 @@ * 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, @@ -17,13 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.nodeschema.validation; -import org.apache.commons.lang.StringUtils; +package org.onap.aai.schemaservice.nodeschema.validation; import java.util.ArrayList; import java.util.List; +import org.apache.commons.lang.StringUtils; + /** * When an error is found, mark that it is NOT ok to * continue with installation/whatever other caller function, @@ -31,36 +32,42 @@ import java.util.List; * keep validating so all issues are found in one run. */ public class CheckEverythingStrategy implements SchemaErrorStrategy { - private boolean isOK = true; - private List errorMsgs = new ArrayList<>(); + private boolean isOK = true; + private List errorMsgs = new ArrayList<>(); - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#isOK() - */ - @Override - public boolean isOK() { - return isOK; - } + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#isOK() + */ + @Override + public boolean isOK() { + return isOK; + } - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#getErrorMsg() - */ - @Override - public String getErrorMsg() { - if (errorMsgs.isEmpty()) { - return "No errors found."; - } else { - return StringUtils.join(errorMsgs, "\n"); + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#getErrorMsg() + */ + @Override + public String getErrorMsg() { + if (errorMsgs.isEmpty()) { + return "No errors found."; + } else { + return StringUtils.join(errorMsgs, "\n"); + } } - } - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#notifyOnError(java.lang.String) - */ - @Override - public void notifyOnError(String errorMsg) { - isOK = false; - errorMsgs.add(errorMsg); - } + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#notifyOnError(java.lang.String) + */ + @Override + public void notifyOnError(String errorMsg) { + isOK = false; + errorMsgs.add(errorMsg); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultDuplicateNodeDefinitionValidationModule.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultDuplicateNodeDefinitionValidationModule.java index fa1c36b..b33fd8d 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultDuplicateNodeDefinitionValidationModule.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultDuplicateNodeDefinitionValidationModule.java @@ -8,7 +8,7 @@ * 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, @@ -17,25 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; -import org.onap.aai.schemaservice.nodeschema.SchemaVersion; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -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.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.List; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + /** * Default duplicate rules for A&AI - * node types may never have a duplicate definition @@ -44,63 +47,69 @@ import java.util.List; * Finds all duplicates and what files they're in. * */ -public class DefaultDuplicateNodeDefinitionValidationModule implements DuplicateNodeDefinitionValidationModule { +public class DefaultDuplicateNodeDefinitionValidationModule + implements DuplicateNodeDefinitionValidationModule { - /* (non-Javadoc) - * @see org.onap.aai.nodes.validation.DuplicateNodeDefinitionValidationModule#findDuplicates(java.util.List) - */ - @Override - public String findDuplicates(List files, SchemaVersion v) { - try { - final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.nodes.validation.DuplicateNodeDefinitionValidationModule#findDuplicates(java. + * util.List) + */ + @Override + public String findDuplicates(List files, SchemaVersion v) { + try { + final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); docFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); docFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); docFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Multimap types = ArrayListMultimap.create(); - boolean foundDups = false; - for (String file : files) { - InputStream inputStream = new FileInputStream(file); - final Document doc = docBuilder.parse(inputStream); - final NodeList list = doc.getElementsByTagName("java-type"); + Multimap types = ArrayListMultimap.create(); + boolean foundDups = false; + for (String file : files) { + InputStream inputStream = new FileInputStream(file); + final Document doc = docBuilder.parse(inputStream); + final NodeList list = doc.getElementsByTagName("java-type"); - for (int i = 0; i < list.getLength(); i++) { - String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue(); - if (types.containsKey(type)) { - foundDups = true; - } - types.put(type, file); - } - } + for (int i = 0; i < list.getLength(); i++) { + String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue(); + if (types.containsKey(type)) { + foundDups = true; + } + types.put(type, file); + } + } - if (foundDups) { - return buildErrorMsg(types, v); - } else { - return ""; - } - } catch (ParserConfigurationException | SAXException | IOException e) { - // TODO something useful with this information - return e.getMessage(); + if (foundDups) { + return buildErrorMsg(types, v); + } else { + return ""; + } + } catch (ParserConfigurationException | SAXException | IOException e) { + // TODO something useful with this information + return e.getMessage(); + } } - } - private String buildErrorMsg(Multimap types, SchemaVersion v) { - StringBuilder errorMsg = new StringBuilder().append("Duplicates found in version ").append(v.toString()).append(". "); - for (String nodeType : types.keySet()) { - Collection files = types.get(nodeType); - if (files.size() == 1) { - continue; //only record the duplicated ones - } - errorMsg.append(nodeType).append(" has definitions in "); - for (String file : files) { - errorMsg.append(file).append(" "); - } + private String buildErrorMsg(Multimap types, SchemaVersion v) { + StringBuilder errorMsg = new StringBuilder().append("Duplicates found in version ") + .append(v.toString()).append(". "); + for (String nodeType : types.keySet()) { + Collection files = types.get(nodeType); + if (files.size() == 1) { + continue; // only record the duplicated ones + } + errorMsg.append(nodeType).append(" has definitions in "); + for (String file : files) { + errorMsg.append(file).append(" "); + } + } + return errorMsg.toString(); } - return errorMsg.toString(); - } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultVersionValidationModule.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultVersionValidationModule.java index 8f674fc..ea7cdd7 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultVersionValidationModule.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DefaultVersionValidationModule.java @@ -8,7 +8,7 @@ * 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, @@ -17,16 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; +import java.util.List; +import java.util.Map; + import org.onap.aai.schemaservice.config.ConfigTranslator; import org.onap.aai.schemaservice.nodeschema.SchemaVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; - /** * By default, A&AI must have schema files for all current * supported Versions in the Version enum @@ -34,39 +35,43 @@ import java.util.Map; */ @Component public class DefaultVersionValidationModule implements VersionValidationModule { - private ConfigTranslator config; + private ConfigTranslator config; - @Autowired - public DefaultVersionValidationModule(ConfigTranslator config) { - this.config = config; - } + @Autowired + public DefaultVersionValidationModule(ConfigTranslator config) { + this.config = config; + } - /* (non-Javadoc) - * @see org.onap.aai.validation.VersionValidationModule#validate(org.onap.aai.setup.ConfigTranslator) - */ - @Override - public String validate() { - Map> nodeConfig = config.getNodeFiles(); - Map> edgeConfig = config.getEdgeFiles(); + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.validation.VersionValidationModule#validate(org.onap.aai.setup.ConfigTranslator) + */ + @Override + public String validate() { + Map> nodeConfig = config.getNodeFiles(); + Map> edgeConfig = config.getEdgeFiles(); - StringBuilder missingVers = new StringBuilder().append("Missing schema for the following versions: "); - boolean isMissing = false; - for (SchemaVersion v : config.getSchemaVersions().getVersions()) { - if (nodeConfig.get(v) == null) { - isMissing = true; - missingVers.append(v.toString()).append(" has no OXM configured. "); - } - if (edgeConfig.get(v) == null) { - isMissing = true; - missingVers.append(v.toString()).append(" has no edge rules configured. "); - } - } + StringBuilder missingVers = + new StringBuilder().append("Missing schema for the following versions: "); + boolean isMissing = false; + for (SchemaVersion v : config.getSchemaVersions().getVersions()) { + if (nodeConfig.get(v) == null) { + isMissing = true; + missingVers.append(v.toString()).append(" has no OXM configured. "); + } + if (edgeConfig.get(v) == null) { + isMissing = true; + missingVers.append(v.toString()).append(" has no edge rules configured. "); + } + } - if (isMissing) { - return missingVers.toString(); - } else { - return ""; + if (isMissing) { + return missingVers.toString(); + } else { + return ""; + } } - } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DuplicateNodeDefinitionValidationModule.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DuplicateNodeDefinitionValidationModule.java index 1cab48d..7b07ce8 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DuplicateNodeDefinitionValidationModule.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/DuplicateNodeDefinitionValidationModule.java @@ -8,7 +8,7 @@ * 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, @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.nodeschema.validation; -import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +package org.onap.aai.schemaservice.nodeschema.validation; import java.util.List; +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; + /** * Defines rules for duplicate node definitions in a set of files * (where the intent is the set of files is all the OXM for one version). @@ -34,13 +35,13 @@ import java.util.List; * etc. */ public interface DuplicateNodeDefinitionValidationModule { - /** - * Finds any duplicates according to the defined rules - * - * @param files - the OXM files to use with full directory - * @return empty String if none found, else a String - * with appropriate information about what node types - * were found - */ - String findDuplicates(List files, SchemaVersion v); + /** + * Finds any duplicates according to the defined rules + * + * @param files - the OXM files to use with full directory + * @return empty String if none found, else a String + * with appropriate information about what node types + * were found + */ + String findDuplicates(List files, SchemaVersion v); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/FailFastStrategy.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/FailFastStrategy.java index 7c05007..5bbfb87 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/FailFastStrategy.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/FailFastStrategy.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; /** @@ -25,33 +26,39 @@ package org.onap.aai.schemaservice.nodeschema.validation; * process to abort. */ public class FailFastStrategy implements SchemaErrorStrategy { - private boolean isOK = true; - private String errorMsg = "No errors found."; + private boolean isOK = true; + private String errorMsg = "No errors found."; - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#isOK() - */ - @Override - public boolean isOK() { - return isOK; - } + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#isOK() + */ + @Override + public boolean isOK() { + return isOK; + } - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#getErrorMsg() - */ - @Override - public String getErrorMsg() { - return errorMsg; - } + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#getErrorMsg() + */ + @Override + public String getErrorMsg() { + return errorMsg; + } - /* (non-Javadoc) - * @see org.onap.aai.edges.validation.SchemaErrorStrategy#notifyOnError(java.lang.String) - */ - @Override - public void notifyOnError(String errorMsg) { - isOK = false; - this.errorMsg = errorMsg; - throw new AAISchemaValidationException(errorMsg); - } + /* + * (non-Javadoc) + * + * @see org.onap.aai.edges.validation.SchemaErrorStrategy#notifyOnError(java.lang.String) + */ + @Override + public void notifyOnError(String errorMsg) { + isOK = false; + this.errorMsg = errorMsg; + throw new AAISchemaValidationException(errorMsg); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/NodeValidator.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/NodeValidator.java index bc46e16..faeadc5 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/NodeValidator.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/NodeValidator.java @@ -8,7 +8,7 @@ * 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, @@ -17,41 +17,43 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; +import java.util.List; +import java.util.Map.Entry; + import org.onap.aai.schemaservice.config.ConfigTranslator; import org.onap.aai.schemaservice.nodeschema.SchemaVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map.Entry; - @Component public class NodeValidator { - private ConfigTranslator translator; - private SchemaErrorStrategy strat; - private DuplicateNodeDefinitionValidationModule dupChecker; - - @Autowired - public NodeValidator(ConfigTranslator translator, SchemaErrorStrategy strategy, DuplicateNodeDefinitionValidationModule dupChecker) { - this.translator = translator; - this.strat = strategy; - this.dupChecker = dupChecker; - } - - public boolean validate() { - - for(Entry> entry : translator.getNodeFiles().entrySet()) { - String result = dupChecker.findDuplicates(entry.getValue(), entry.getKey()); - if (!"".equals(result)) { - strat.notifyOnError(result); - } + private ConfigTranslator translator; + private SchemaErrorStrategy strat; + private DuplicateNodeDefinitionValidationModule dupChecker; + + @Autowired + public NodeValidator(ConfigTranslator translator, SchemaErrorStrategy strategy, + DuplicateNodeDefinitionValidationModule dupChecker) { + this.translator = translator; + this.strat = strategy; + this.dupChecker = dupChecker; + } + + public boolean validate() { + + for (Entry> entry : translator.getNodeFiles().entrySet()) { + String result = dupChecker.findDuplicates(entry.getValue(), entry.getKey()); + if (!"".equals(result)) { + strat.notifyOnError(result); + } + } + return strat.isOK(); } - return strat.isOK(); - } - public String getErrorMsg() { - return strat.getErrorMsg(); - } + public String getErrorMsg() { + return strat.getErrorMsg(); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/SchemaErrorStrategy.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/SchemaErrorStrategy.java index a9cafa5..7d76533 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/SchemaErrorStrategy.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/SchemaErrorStrategy.java @@ -8,7 +8,7 @@ * 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, @@ -17,42 +17,43 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; /** * Controls response to finding problems in the schema files. */ public interface SchemaErrorStrategy { - /** - * Gives if it is OK to proceed with whatever process - * invoked the validation (probably the installation of - * the A&AI instance). - * - * @return boolean - */ - public boolean isOK(); + /** + * Gives if it is OK to proceed with whatever process + * invoked the validation (probably the installation of + * the A&AI instance). + * + * @return boolean + */ + public boolean isOK(); - /** - * Gets the error message(s) gathered in the course - * of validation. - * - * @return String error message or messages concatenated together - */ - public String getErrorMsg(); + /** + * Gets the error message(s) gathered in the course + * of validation. + * + * @return String error message or messages concatenated together + */ + public String getErrorMsg(); - /** - * Invokes the ErrorStrategy to do whatever response to - * an issue in the schema having been found. - * - * Options: - * -Throw an exception if the whole process should be - * immediately aborted - * -Set OK status to false, store the message and allow the - * validation process to continue and find any other issues - * -Completely ignore that something is wrong - * etc. - * - * @param String errorMsg - the error message from the validator module - */ - public void notifyOnError(String errorMsg); + /** + * Invokes the ErrorStrategy to do whatever response to + * an issue in the schema having been found. + * + * Options: + * -Throw an exception if the whole process should be + * immediately aborted + * -Set OK status to false, store the message and allow the + * validation process to continue and find any other issues + * -Completely ignore that something is wrong + * etc. + * + * @param String errorMsg - the error message from the validator module + */ + public void notifyOnError(String errorMsg); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidationModule.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidationModule.java index 15ae19a..c7304d6 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidationModule.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidationModule.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.nodeschema.validation; +package org.onap.aai.schemaservice.nodeschema.validation; /** * Defines the behavior for what versions are required/optional. @@ -27,11 +27,11 @@ package org.onap.aai.schemaservice.nodeschema.validation; */ public interface VersionValidationModule { - /** - * Validates that all required versions have schema - * configured for them. - * - * @return empty string if none missing or else an appropriate error - */ - public String validate(); + /** + * Validates that all required versions have schema + * configured for them. + * + * @return empty string if none missing or else an appropriate error + */ + public String validate(); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidator.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidator.java index 0158bc3..135bdcc 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidator.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/nodeschema/validation/VersionValidator.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.nodeschema.validation; import org.springframework.beans.factory.annotation.Autowired; @@ -28,25 +29,25 @@ import org.springframework.stereotype.Component; */ @Component public class VersionValidator { - private SchemaErrorStrategy strat; - private VersionValidationModule verMod; - - @Autowired - public VersionValidator(SchemaErrorStrategy strategy, VersionValidationModule verMod) { - this.strat = strategy; - this.verMod = verMod; - } + private SchemaErrorStrategy strat; + private VersionValidationModule verMod; - public boolean validate() { - String result = verMod.validate(); - if (!"".equals(result)) { - strat.notifyOnError(result); + @Autowired + public VersionValidator(SchemaErrorStrategy strategy, VersionValidationModule verMod) { + this.strat = strategy; + this.verMod = verMod; } - return strat.isOK(); - } + public boolean validate() { + String result = verMod.validate(); + if (!"".equals(result)) { + strat.notifyOnError(result); + } - public String getErrorMsg() { - return strat.getErrorMsg(); - } + return strat.isOK(); + } + + public String getErrorMsg() { + return strat.getErrorMsg(); + } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryResource.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryResource.java index 0137d1d..69c9998 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryResource.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryResource.java @@ -8,7 +8,7 @@ * 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, @@ -17,27 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.query; -import org.springframework.beans.factory.annotation.Autowired; +package org.onap.aai.schemaservice.query; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; +import org.springframework.beans.factory.annotation.Autowired; + @Path("/v1") public class QueryResource { private QueryService queryService; @Autowired - public QueryResource(QueryService queryService){ + public QueryResource(QueryService queryService) { this.queryService = queryService; } @GET @Path("/stored-queries") - public Response retrieveStoredQueries(){ + public Response retrieveStoredQueries() { return Response.ok().entity(queryService.getStoredQueries()).build(); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryService.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryService.java index 1e67bd9..a3c8b5a 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryService.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/query/QueryService.java @@ -8,7 +8,7 @@ * 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, @@ -17,14 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.query; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; +package org.onap.aai.schemaservice.query; -import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -32,6 +27,13 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; +import javax.annotation.PostConstruct; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + @Service public class QueryService { @@ -41,7 +43,7 @@ public class QueryService { private String storedQueriesContent; - public QueryService(@Value("${schema.query.location}") String queryLocation){ + public QueryService(@Value("${schema.query.location}") String queryLocation) { this.queryLocation = queryLocation; } @@ -53,7 +55,7 @@ public class QueryService { StringBuilder contentBuilder = new StringBuilder(); - try(Stream stream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)){ + try (Stream stream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) { stream.forEach(s -> contentBuilder.append(s)); } @@ -62,7 +64,7 @@ public class QueryService { LOGGER.trace("Contents of the stored query file {}", storedQueriesContent); } - public String getStoredQueries(){ + public String getStoredQueries() { return storedQueriesContent; } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/service/AuthorizationService.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/service/AuthorizationService.java index 766e56c..808cde8 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/service/AuthorizationService.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/service/AuthorizationService.java @@ -8,7 +8,7 @@ * 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, @@ -17,17 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.schemaservice.service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.eclipse.jetty.util.security.Password; -import org.onap.aai.schemaservice.Profiles; -import org.onap.aai.util.AAIConstants; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Service; +package org.onap.aai.schemaservice.service; -import javax.annotation.PostConstruct; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; @@ -37,6 +29,16 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; +import javax.annotation.PostConstruct; + +import org.eclipse.jetty.util.security.Password; +import org.onap.aai.schemaservice.Profiles; +import org.onap.aai.util.AAIConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; + @Profile(Profiles.ONE_WAY_SSL) @Service public class AuthorizationService { @@ -48,37 +50,39 @@ public class AuthorizationService { private static final Base64.Encoder ENCODER = Base64.getEncoder(); @PostConstruct - public void init(){ + public void init() { String basicAuthFile = getBasicAuthFilePath(); - try(Stream stream = Files.lines(Paths.get(basicAuthFile))){ + try (Stream stream = Files.lines(Paths.get(basicAuthFile))) { stream.filter(line -> !line.startsWith("#")).forEach(str -> { - byte [] bytes = null; + byte[] bytes = null; String usernamePassword = null; String accessType = null; try { - String [] userAccessType = str.split(","); + String[] userAccessType = str.split(","); - if(userAccessType == null || userAccessType.length != 2){ - throw new RuntimeException("Please check the realm.properties file as it is not conforming to the basic auth"); + if (userAccessType == null || userAccessType.length != 2) { + throw new RuntimeException( + "Please check the realm.properties file as it is not conforming to the basic auth"); } usernamePassword = userAccessType[0]; - accessType = userAccessType[1]; + accessType = userAccessType[1]; String[] usernamePasswordArray = usernamePassword.split(":"); - if(usernamePasswordArray == null || usernamePasswordArray.length != 3){ - throw new RuntimeException("This username / pwd is not a valid entry in realm.properties"); + if (usernamePasswordArray == null || usernamePasswordArray.length != 3) { + throw new RuntimeException( + "This username / pwd is not a valid entry in realm.properties"); } String username = usernamePasswordArray[0]; String password = null; - if(str.contains("OBF:")){ + if (str.contains("OBF:")) { password = usernamePasswordArray[1] + ":" + usernamePasswordArray[2]; password = Password.deobfuscate(password); } @@ -87,8 +91,7 @@ public class AuthorizationService { authorizedUsers.put(new String(bytes), accessType); - } catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { logger.error("Unable to support the encoding of the file" + basicAuthFile); } @@ -99,11 +102,12 @@ public class AuthorizationService { } } - public boolean checkIfUserAuthorized(String authorization){ - return authorizedUsers.containsKey(authorization) && "admin".equals(authorizedUsers.get(authorization)); + public boolean checkIfUserAuthorized(String authorization) { + return authorizedUsers.containsKey(authorization) + && "admin".equals(authorizedUsers.get(authorization)); } - public String getBasicAuthFilePath(){ + public String getBasicAuthFilePath() { return AAIConstants.AAI_HOME_ETC_AUTH + AAIConstants.AAI_FILESEP + "realm.properties"; } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/Version.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/Version.java index 47da48d..2bdf179 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/Version.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/Version.java @@ -8,7 +8,7 @@ * 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, @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.versions; import com.google.gson.annotations.SerializedName; @@ -99,35 +100,33 @@ public class Version { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Version that = (Version) o; - return Objects.equals(versions, that.versions) && - Objects.equals(edgeVersion, that.edgeVersion) && - Objects.equals(defaultVersion, that.defaultVersion) && - Objects.equals(depthVersion, that.depthVersion) && - Objects.equals(appRootVersion, that.appRootVersion) && - Objects.equals(relatedLinkVersion, that.relatedLinkVersion) && - Objects.equals(namespaceChangeVersion, that.namespaceChangeVersion); + return Objects.equals(versions, that.versions) + && Objects.equals(edgeVersion, that.edgeVersion) + && Objects.equals(defaultVersion, that.defaultVersion) + && Objects.equals(depthVersion, that.depthVersion) + && Objects.equals(appRootVersion, that.appRootVersion) + && Objects.equals(relatedLinkVersion, that.relatedLinkVersion) + && Objects.equals(namespaceChangeVersion, that.namespaceChangeVersion); } @Override public int hashCode() { - return Objects.hash(versions, edgeVersion, defaultVersion, depthVersion, appRootVersion, relatedLinkVersion, namespaceChangeVersion); + return Objects.hash(versions, edgeVersion, defaultVersion, depthVersion, appRootVersion, + relatedLinkVersion, namespaceChangeVersion); } - @Override public String toString() { - return "Version{" + - "versions=" + versions + - ", edgeVersion='" + edgeVersion + '\'' + - ", defaultVersion='" + defaultVersion + '\'' + - ", depthVersion='" + depthVersion + '\'' + - ", appRootVersion='" + appRootVersion + '\'' + - ", relatedLinkVersion='" + relatedLinkVersion + '\'' + - ", namespaceChangeVersion='" + namespaceChangeVersion + '\'' + - '}'; + return "Version{" + "versions=" + versions + ", edgeVersion='" + edgeVersion + '\'' + + ", defaultVersion='" + defaultVersion + '\'' + ", depthVersion='" + depthVersion + + '\'' + ", appRootVersion='" + appRootVersion + '\'' + ", relatedLinkVersion='" + + relatedLinkVersion + '\'' + ", namespaceChangeVersion='" + namespaceChangeVersion + + '\'' + '}'; } } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionResource.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionResource.java index 70e32bc..4093769 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionResource.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionResource.java @@ -8,7 +8,7 @@ * 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, @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.versions; import com.google.gson.Gson; -import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -28,20 +28,22 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.springframework.beans.factory.annotation.Autowired; + @Path("/v1") public class VersionResource { private VersionService versionService; @Autowired - public VersionResource(VersionService versionService){ + public VersionResource(VersionService versionService) { this.versionService = versionService; } @GET @Path("/versions") - @Produces({ MediaType.APPLICATION_JSON }) - public Response getVersions(){ + @Produces({MediaType.APPLICATION_JSON}) + public Response getVersions() { Gson gson = new Gson(); return Response.ok(gson.toJson(versionService.getVersionInfo())).build(); } diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionService.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionService.java index 2d80145..810e4eb 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionService.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/versions/VersionService.java @@ -8,7 +8,7 @@ * 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, @@ -17,13 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.versions; +import java.util.List; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.util.List; - @Service public class VersionService { @@ -48,8 +49,7 @@ public class VersionService { @Value("${schema.version.api.default}") private String defaultApi; - - public Version getVersionInfo(){ + public Version getVersionInfo() { Version schemaVersion = new Version(); schemaVersion.setVersions(schemaVersionList); diff --git a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/web/JerseyConfiguration.java b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/web/JerseyConfiguration.java index 182203d..8b3a936 100644 --- a/aai-schema-service/src/main/java/org/onap/aai/schemaservice/web/JerseyConfiguration.java +++ b/aai-schema-service/src/main/java/org/onap/aai/schemaservice/web/JerseyConfiguration.java @@ -8,7 +8,7 @@ * 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, @@ -17,15 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice.web; import java.util.List; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; + import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseFilter; + import org.glassfish.jersey.server.ResourceConfig; import org.onap.aai.schemaservice.edges.EdgeResource; import org.onap.aai.schemaservice.healthcheck.EchoResource; @@ -39,7 +42,6 @@ import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; - @Component public class JerseyConfiguration extends ResourceConfig { @@ -58,7 +60,7 @@ public class JerseyConfiguration extends ResourceConfig { register(QueryResource.class); register(EdgeResource.class); - //Request Filters + // Request Filters registerFilters(ContainerRequestFilter.class); registerFilters(ContainerResponseFilter.class); registerFilters(AuditLogContainerFilter.class); @@ -73,31 +75,30 @@ public class JerseyConfiguration extends ResourceConfig { Set> filters = loggingReflections.getSubTypesOf(type); filters.addAll(reflections.getSubTypesOf(type)); - // Check to ensure that each of the filter has the @Priority annotation and if not throw exception + // Check to ensure that each of the filter has the @Priority annotation and if not throw + // exception for (Class filterClass : filters) { if (filterClass.getAnnotation(Priority.class) == null) { - throw new RuntimeException("Container filter " + filterClass.getName() + " does not have @Priority annotation"); + throw new RuntimeException("Container filter " + filterClass.getName() + + " does not have @Priority annotation"); } } // Turn the set back into a list - List> filtersList = filters - .stream() - .filter(f -> { - if (f.isAnnotationPresent(Profile.class) - && !env.acceptsProfiles(f.getAnnotation(Profile.class).value())) { - return false; - } - return true; - }) - .collect(Collectors.toList()); + List> filtersList = filters.stream().filter(f -> { + if (f.isAnnotationPresent(Profile.class) + && !env.acceptsProfiles(f.getAnnotation(Profile.class).value())) { + return false; + } + return true; + }).collect(Collectors.toList()); // Sort them by their priority levels value - filtersList.sort((c1, c2) -> Integer.valueOf(c1.getAnnotation(Priority.class).value()).compareTo(c2.getAnnotation(Priority.class).value())); + filtersList.sort((c1, c2) -> Integer.valueOf(c1.getAnnotation(Priority.class).value()) + .compareTo(c2.getAnnotation(Priority.class).value())); // Then register this to the jersey application filtersList.forEach(this::register); } - } diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTest.java index 9c214bd..c874038 100644 --- a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTest.java +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,8 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.io.UnsupportedEncodingException; +import java.util.Base64; +import java.util.Collections; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -36,14 +44,9 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; -import java.io.UnsupportedEncodingException; -import java.util.Base64; -import java.util.Collections; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SchemaServiceApp.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = SchemaServiceApp.class) @TestPropertySource(locations = "classpath:application-test.properties") @ContextConfiguration(initializers = PropertyPasswordConfiguration.class) @Import(SchemaServiceTestConfiguration.class) @@ -91,7 +94,7 @@ public class SchemaServiceTest { } @Test - public void testGetSchemaAndEdgeRules(){ + public void testGetSchemaAndEdgeRules() { headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML)); @@ -104,30 +107,23 @@ public class SchemaServiceTest { ResponseEntity responseEntity; - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/nodes?version=v20", - HttpMethod.GET, - httpEntity, - String.class - ); + responseEntity = restTemplate.exchange(baseUrl + "/aai/schema-service/v1/nodes?version=v20", + HttpMethod.GET, httpEntity, String.class); assertThat(responseEntity.getStatusCodeValue(), is(200)); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); httpEntity = new HttpEntity(headers); - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/edgerules?version=v20", - HttpMethod.GET, - httpEntity, - String.class - ); + responseEntity = + restTemplate.exchange(baseUrl + "/aai/schema-service/v1/edgerules?version=v20", + HttpMethod.GET, httpEntity, String.class); assertThat(responseEntity.getStatusCodeValue(), is(200)); } @Test - public void testInvalidSchemaAndEdges(){ + public void testInvalidSchemaAndEdges() { headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML)); @@ -140,56 +136,41 @@ public class SchemaServiceTest { ResponseEntity responseEntity; - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/nodes?version=blah", - HttpMethod.GET, - httpEntity, - String.class - ); - System.out.println(" "+responseEntity.getBody()); + responseEntity = + restTemplate.exchange(baseUrl + "/aai/schema-service/v1/nodes?version=blah", + HttpMethod.GET, httpEntity, String.class); + System.out.println(" " + responseEntity.getBody()); assertThat(responseEntity.getStatusCodeValue(), is(400)); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); httpEntity = new HttpEntity(headers); - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/edgerules?version=blah", - HttpMethod.GET, - httpEntity, - String.class - ); + responseEntity = + restTemplate.exchange(baseUrl + "/aai/schema-service/v1/edgerules?version=blah", + HttpMethod.GET, httpEntity, String.class); assertThat(responseEntity.getStatusCodeValue(), is(400)); } @Test - public void testVersions(){ + public void testVersions() { ResponseEntity responseEntity; - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/versions", - HttpMethod.GET, - httpEntity, - String.class - ); + responseEntity = restTemplate.exchange(baseUrl + "/aai/schema-service/v1/versions", + HttpMethod.GET, httpEntity, String.class); assertThat(responseEntity.getStatusCodeValue(), is(200)); - } @Test - public void testGetStoredQueriesSuccess(){ + public void testGetStoredQueriesSuccess() { ResponseEntity responseEntity; - responseEntity = restTemplate.exchange( - baseUrl + "/aai/schema-service/v1/stored-queries", - HttpMethod.GET, - httpEntity, - String.class - ); + responseEntity = restTemplate.exchange(baseUrl + "/aai/schema-service/v1/stored-queries", + HttpMethod.GET, httpEntity, String.class); assertThat(responseEntity.getStatusCodeValue(), is(200)); } diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTestConfiguration.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTestConfiguration.java index ba8ae26..938d509 100644 --- a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTestConfiguration.java +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/SchemaServiceTestConfiguration.java @@ -8,7 +8,7 @@ * 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, @@ -17,13 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schemaservice; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; + +import javax.net.ssl.SSLContext; + import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.client.RestTemplateBuilder; @@ -36,17 +45,11 @@ import org.springframework.util.ResourceUtils; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; -import javax.net.ssl.SSLContext; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.KeyStore; - @TestConfiguration public class SchemaServiceTestConfiguration { - private static final Logger logger = LoggerFactory.getLogger(SchemaServiceTestConfiguration.class); + private static final Logger logger = + LoggerFactory.getLogger(SchemaServiceTestConfiguration.class); @Autowired private Environment env; @@ -58,39 +61,35 @@ public class SchemaServiceTestConfiguration { @Bean RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception { - - RestTemplate restTemplate = null; - if(env.acceptsProfiles("one-way-ssl", "two-way-ssl")) { - char[] trustStorePassword = env.getProperty("server.ssl.trust-store-password").toCharArray(); - char[] keyStorePassword = env.getProperty("server.ssl.key-store-password").toCharArray(); + if (env.acceptsProfiles("one-way-ssl", "two-way-ssl")) { + char[] trustStorePassword = + env.getProperty("server.ssl.trust-store-password").toCharArray(); + char[] keyStorePassword = + env.getProperty("server.ssl.key-store-password").toCharArray(); String keyStore = env.getProperty("server.ssl.key-store"); String trustStore = env.getProperty("server.ssl.trust-store"); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); if (env.acceptsProfiles("two-way-ssl")) { - sslContextBuilder = sslContextBuilder.loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword); + sslContextBuilder = sslContextBuilder + .loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword); } SSLContext sslContext = sslContextBuilder - .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword) - .build(); + .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword).build(); - HttpClient client = HttpClients.custom() - .setSSLContext(sslContext) - .setSSLHostnameVerifier((s, sslSession) -> true) - .build(); + HttpClient client = HttpClients.custom().setSSLContext(sslContext) + .setSSLHostnameVerifier((s, sslSession) -> true).build(); restTemplate = builder - .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)) - .build(); - }else { + .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)).build(); + } else { restTemplate = builder.build(); } - restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { @@ -103,7 +102,7 @@ public class SchemaServiceTestConfiguration { return true; } - if(clientHttpResponse.getRawStatusCode() % 100 == 5){ + if (clientHttpResponse.getRawStatusCode() % 100 == 5) { logger.debug("Call returned a error " + clientHttpResponse.getStatusText()); return true; } diff --git a/aai-schema/src/test/java/org/onap/aai/schema/ValidateEdgeRulesTest.java b/aai-schema/src/test/java/org/onap/aai/schema/ValidateEdgeRulesTest.java index 55558bc..694f4b9 100644 --- a/aai-schema/src/test/java/org/onap/aai/schema/ValidateEdgeRulesTest.java +++ b/aai-schema/src/test/java/org/onap/aai/schema/ValidateEdgeRulesTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,16 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schema; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.DirectoryFileFilter; -import org.apache.commons.io.filefilter.RegexFileFilter; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Test; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileReader; @@ -36,7 +30,14 @@ import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; -import static org.junit.Assert.fail; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.DirectoryFileFilter; +import org.apache.commons.io.filefilter.RegexFileFilter; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.junit.Test; public class ValidateEdgeRulesTest { @@ -50,24 +51,26 @@ public class ValidateEdgeRulesTest { private static final String DBEDGERULES_IN = "IN"; @Test - public void testOnlyOneDefaultPerEdgeRuleBetweenTwoNodetypes() throws IOException, ParseException { + public void testOnlyOneDefaultPerEdgeRuleBetweenTwoNodetypes() + throws IOException, ParseException { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - List subDirs = Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); + List subDirs = + Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); List multipleDefaultsPerList = new ArrayList<>(); for (File subDir : subDirs) { String edgeRule = subDir.getAbsolutePath() + "/dbedgerules"; File[] edgeRules = new File(edgeRule).listFiles(File::isDirectory); - List dbEdgeRulesList = Arrays.stream(edgeRules).map(File::getAbsolutePath).collect(Collectors.toList()); - + List dbEdgeRulesList = + Arrays.stream(edgeRules).map(File::getAbsolutePath).collect(Collectors.toList()); List dbEdgeRulesFileList = new ArrayList<>(); - dbEdgeRulesList.forEach(s -> - FileUtils.listFiles(new File(s), new RegexFileFilter(".*\\.json"), DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) - .forEach(dbEdgeRulesFileList::add)); + dbEdgeRulesList.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.json"), + DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) + .forEach(dbEdgeRulesFileList::add)); JSONParser jsonParser = new JSONParser(); @@ -75,7 +78,8 @@ public class ValidateEdgeRulesTest { FileReader reader = new FileReader(file); // Map the dbEdgeRules json file into a HashMap for reference Map dbEdgeRules = new HashMap<>(); - // Read JSON file. Expecting JSON file to read an object with a JSONArray names "rules" + // Read JSON file. Expecting JSON file to read an object with a JSONArray names + // "rules" JSONObject jsonObj = (JSONObject) jsonParser.parse(reader); JSONArray rules = (JSONArray) jsonObj.get(DBEDGERULES_RULES); for (int i = 0; i < rules.size(); i++) { @@ -85,7 +89,8 @@ public class ValidateEdgeRulesTest { String direction = rule.get(DBEDGERULES_DIRECTION).toString(); String label = rule.get(DBEDGERULES_LABEL).toString(); String containsOtherV = rule.get(DBEDGERULES_CONTAINS_OTHER_V).toString(); - String isDefault = (rule.get("default") != null) ? rule.get("default").toString() : "false"; + String isDefault = + (rule.get("default") != null) ? rule.get("default").toString() : "false"; // special case - cvlan-tag should be replaced with cvlan-tag-entry if (fromNode.equals("cvlan-tag")) @@ -102,49 +107,54 @@ public class ValidateEdgeRulesTest { dbEdgeRulesMapPut(dbEdgeRules, fromNode, toNode, direction, label, isDefault); } - for(Map.Entry entry : dbEdgeRules.entrySet()){ + for (Map.Entry entry : dbEdgeRules.entrySet()) { String key = entry.getKey(); - if(entry.getValue() > 1){ - multipleDefaultsPerList.add("\n" + file.getAbsoluteFile() + " " + key + " count: " + entry.getValue()); + if (entry.getValue() > 1) { + multipleDefaultsPerList.add("\n" + file.getAbsoluteFile() + " " + key + + " count: " + entry.getValue()); } } } } - if(!multipleDefaultsPerList.isEmpty()){ + if (!multipleDefaultsPerList.isEmpty()) { fail(multipleDefaultsPerList.stream().collect(Collectors.joining())); } } /** * Creating a hashmap to map what child nodes are associated to which parent nodes - * according to the dbEdgeRules json files. A HashMap was chosen for the value of the map for O(1) lookup time. + * according to the dbEdgeRules json files. A HashMap was chosen for the value of the map for + * O(1) lookup time. + * * @param from this variable will act as the key or value depending on the direction * @param to this variable will act as the key or value depending on the direction * @param direction dictates the direction of which vertex is dependent on which - * @return The map returned will act as a dictionary to keep track of the parent nodes. Value of the map is a hashmap to help handle collision of multiple children to one parent + * @return The map returned will act as a dictionary to keep track of the parent nodes. Value of + * the map is a hashmap to help handle collision of multiple children to one parent */ - private Map dbEdgeRulesMapPut(Map dbEdgeRules, String from, String to, String direction, String label, String isDefault) { + private Map dbEdgeRulesMapPut(Map dbEdgeRules, String from, + String to, String direction, String label, String isDefault) { if (isStringEmpty(from) || isStringEmpty(to) || isStringEmpty(direction)) return dbEdgeRules; - String temp; - if(from.compareTo(to) > 0){ + if (from.compareTo(to) > 0) { temp = from; from = to; to = temp; } - String edgeInfo = String.format("%s%s%s[%s]%s", from, ((direction.equals("OUT")) ? "->": "<-"), to, label, isDefault); + String edgeInfo = String.format("%s%s%s[%s]%s", from, + ((direction.equals("OUT")) ? "->" : "<-"), to, label, isDefault); if ("false".equals(isDefault)) { return dbEdgeRules; } - if(dbEdgeRules.containsKey(edgeInfo)){ + if (dbEdgeRules.containsKey(edgeInfo)) { dbEdgeRules.put(edgeInfo, dbEdgeRules.get(edgeInfo) + 1); } else { dbEdgeRules.put(edgeInfo, 1); diff --git a/aai-schema/src/test/java/org/onap/aai/schema/ValidateOXMTest.java b/aai-schema/src/test/java/org/onap/aai/schema/ValidateOXMTest.java index 222ed05..0106dda 100644 --- a/aai-schema/src/test/java/org/onap/aai/schema/ValidateOXMTest.java +++ b/aai-schema/src/test/java/org/onap/aai/schema/ValidateOXMTest.java @@ -8,7 +8,7 @@ * 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, @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.schema; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.DirectoryFileFilter; -import org.apache.commons.io.filefilter.FileFileFilter; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.apache.commons.io.filefilter.RegexFileFilter; -import org.junit.Test; -import org.junit.Ignore; -import org.w3c.dom.*; -import org.xml.sax.SAXException; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -40,15 +37,20 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.stream.Collectors; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.DirectoryFileFilter; +import org.apache.commons.io.filefilter.FileFileFilter; +import org.apache.commons.io.filefilter.FileFilterUtils; +import org.apache.commons.io.filefilter.RegexFileFilter; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.*; +import org.xml.sax.SAXException; public class ValidateOXMTest { @@ -66,7 +68,8 @@ public class ValidateOXMTest { private String ONAP = "onap"; @Test - public void testFindXmlPropContainingSpace() throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { + public void testFindXmlPropContainingSpace() + throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { boolean foundIssue = false; List fileList = getLatestFiles(); @@ -76,13 +79,16 @@ public class ValidateOXMTest { msg.append("\n"); Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type/xml-properties/xml-property[@name!='description' and contains(@value,' ')]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + String expression = + "/xml-bindings/java-types/java-type/xml-properties/xml-property[@name!='description' and contains(@value,' ')]"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { foundIssue = true; msg.append("\t"); - msg.append(nodeList.item(i).getParentNode().getParentNode().getAttributes().getNamedItem("name").getNodeValue()); + msg.append(nodeList.item(i).getParentNode().getParentNode().getAttributes() + .getNamedItem("name").getNodeValue()); msg.append("\n"); msg.append("\t"); msg.append("\n"); @@ -99,13 +105,15 @@ public class ValidateOXMTest { /** * Verifies that all of the node types in the oxm's have their uri templates. + * * @throws XPathExpressionException * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ @Test - public void allNodeTypesHaveAAIUriTemplate() throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { + public void allNodeTypesHaveAAIUriTemplate() + throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { boolean foundIssue = false; List fileList = getFiles(); @@ -115,18 +123,17 @@ public class ValidateOXMTest { msg.append("\n"); Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type[" + - "(" + - "count(xml-properties/xml-property[@name='container']) > 0 " + - "or count(xml-properties/xml-property[@name='dependentOn']) > 0" + - ") " + - "and count(xml-properties/xml-property[@name='uriTemplate']) = 0 " + - "]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + String expression = "/xml-bindings/java-types/java-type[" + "(" + + "count(xml-properties/xml-property[@name='container']) > 0 " + + "or count(xml-properties/xml-property[@name='dependentOn']) > 0" + ") " + + "and count(xml-properties/xml-property[@name='uriTemplate']) = 0 " + "]"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - if (name.equals("InstanceFilter") || name.equals("InventoryResponseItems") || name.equals("InventoryResponseItem")) { + if (name.equals("InstanceFilter") || name.equals("InventoryResponseItems") + || name.equals("InventoryResponseItem")) { continue; } foundIssue = true; @@ -153,41 +160,49 @@ public class ValidateOXMTest { for (File file : fileList) { Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type[count(xml-properties/xml-property[@name='indexedProps']) > 0]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + String expression = + "/xml-bindings/java-types/java-type[count(xml-properties/xml-property[@name='indexedProps']) > 0]"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); Map> nodeTypeBadIndexProps = new HashMap<>(); - for(int i = 0; i < nodeList.getLength(); i++){ + for (int i = 0; i < nodeList.getLength(); i++) { String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - NodeList javaAttributesList = ((Element)nodeList.item(i)).getElementsByTagName("java-attributes"); + NodeList javaAttributesList = + ((Element) nodeList.item(i)).getElementsByTagName("java-attributes"); Set properties = new HashSet<>(); - for(int j = 0; j < javaAttributesList.getLength(); j++){ - NodeList elementList = ((Element)javaAttributesList.item(j)).getElementsByTagName("xml-element"); - for(int k = 0; k < elementList.getLength(); k++){ - properties.add(elementList.item(k).getAttributes().getNamedItem("name").getNodeValue()); + for (int j = 0; j < javaAttributesList.getLength(); j++) { + NodeList elementList = + ((Element) javaAttributesList.item(j)).getElementsByTagName("xml-element"); + for (int k = 0; k < elementList.getLength(); k++) { + properties.add(elementList.item(k).getAttributes().getNamedItem("name") + .getNodeValue()); } } - NodeList xmlPropertiesList = ((Element)nodeList.item(i)).getElementsByTagName("xml-properties"); + NodeList xmlPropertiesList = + ((Element) nodeList.item(i)).getElementsByTagName("xml-properties"); List badIndexedProps = new ArrayList<>(); boolean foundIssueInNodeType = false; - for(int j = 0; j < xmlPropertiesList.getLength(); j++){ - NodeList xmlProperties = ((Element)xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); - for(int k = 0; k < xmlProperties.getLength(); k++){ - String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name").getNodeValue(); - if("indexedProps".equals(xmlProp)){ - String xmlPropValue = xmlProperties.item(k).getAttributes().getNamedItem("value").getNodeValue(); + for (int j = 0; j < xmlPropertiesList.getLength(); j++) { + NodeList xmlProperties = + ((Element) xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); + for (int k = 0; k < xmlProperties.getLength(); k++) { + String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name") + .getNodeValue(); + if ("indexedProps".equals(xmlProp)) { + String xmlPropValue = xmlProperties.item(k).getAttributes() + .getNamedItem("value").getNodeValue(); - List indexProps = Arrays - .stream(xmlPropValue.split(",")) - .collect(Collectors.toList()); + List indexProps = + Arrays.stream(xmlPropValue.split(",")).collect(Collectors.toList()); - for(String indexProp : indexProps){ - if(!properties.contains(indexProp)){ + for (String indexProp : indexProps) { + if (!properties.contains(indexProp)) { foundIssueInNodeType = true; badIndexedProps.add(indexProp); } @@ -197,19 +212,21 @@ public class ValidateOXMTest { } } - if(foundIssueInNodeType){ - foundIssue =true; + if (foundIssueInNodeType) { + foundIssue = true; nodeTypeBadIndexProps.put(name, badIndexedProps); } } - if(!nodeTypeBadIndexProps.isEmpty()){ + if (!nodeTypeBadIndexProps.isEmpty()) { msg.append("\n"); msg.append("File: " + file.getAbsolutePath().replaceAll(".*aai-schema", "")); msg.append("\n"); - for (Map.Entry> nodeTypeBadIndex : nodeTypeBadIndexProps.entrySet()) { + for (Map.Entry> nodeTypeBadIndex : nodeTypeBadIndexProps + .entrySet()) { msg.append("NodeType: " + nodeTypeBadIndex.getKey()); - msg.append(" contains following indexed props that are not properties in object: "); + msg.append( + " contains following indexed props that are not properties in object: "); msg.append(String.join(",", nodeTypeBadIndex.getValue())); msg.append("\n"); } @@ -233,38 +250,46 @@ public class ValidateOXMTest { for (File file : fileList) { Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type[count(xml-properties/xml-property[@name='uniqueProps']) > 0]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + String expression = + "/xml-bindings/java-types/java-type[count(xml-properties/xml-property[@name='uniqueProps']) > 0]"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); Map> nodeTypeBadUniqueProps = new HashMap<>(); for (int i = 0; i < nodeList.getLength(); i++) { String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - NodeList javaAttributesList = ((Element) nodeList.item(i)).getElementsByTagName("java-attributes"); + NodeList javaAttributesList = + ((Element) nodeList.item(i)).getElementsByTagName("java-attributes"); Set properties = new HashSet<>(); for (int j = 0; j < javaAttributesList.getLength(); j++) { - NodeList elementList = ((Element) javaAttributesList.item(j)).getElementsByTagName("xml-element"); + NodeList elementList = + ((Element) javaAttributesList.item(j)).getElementsByTagName("xml-element"); for (int k = 0; k < elementList.getLength(); k++) { - properties.add(elementList.item(k).getAttributes().getNamedItem("name").getNodeValue()); + properties.add(elementList.item(k).getAttributes().getNamedItem("name") + .getNodeValue()); } } - NodeList xmlPropertiesList = ((Element) nodeList.item(i)).getElementsByTagName("xml-properties"); + NodeList xmlPropertiesList = + ((Element) nodeList.item(i)).getElementsByTagName("xml-properties"); List badUniqueProps = new ArrayList<>(); boolean foundIssueInNodeType = false; for (int j = 0; j < xmlPropertiesList.getLength(); j++) { - NodeList xmlProperties = ((Element) xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); + NodeList xmlProperties = + ((Element) xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); for (int k = 0; k < xmlProperties.getLength(); k++) { - String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name").getNodeValue(); + String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name") + .getNodeValue(); if ("uniqueProps".equals(xmlProp)) { - String xmlPropValue = xmlProperties.item(k).getAttributes().getNamedItem("value").getNodeValue(); + String xmlPropValue = xmlProperties.item(k).getAttributes() + .getNamedItem("value").getNodeValue(); - List uniqueProps = Arrays - .stream(xmlPropValue.split(",")) - .collect(Collectors.toList()); + List uniqueProps = + Arrays.stream(xmlPropValue.split(",")).collect(Collectors.toList()); for (String uniqueProp : uniqueProps) { if (!properties.contains(uniqueProp)) { @@ -287,9 +312,11 @@ public class ValidateOXMTest { msg.append("\n"); msg.append("File: " + file.getAbsolutePath().replaceAll(".*aai-schema", "")); msg.append("\n"); - for (Map.Entry> nodeTypeBadUnique : nodeTypeBadUniqueProps.entrySet()) { + for (Map.Entry> nodeTypeBadUnique : nodeTypeBadUniqueProps + .entrySet()) { msg.append("NodeType: " + nodeTypeBadUnique.getKey()); - msg.append(" contains following unique props that are not properties in object: "); + msg.append( + " contains following unique props that are not properties in object: "); msg.append(String.join(",", nodeTypeBadUnique.getValue())); msg.append("\n"); } @@ -302,91 +329,99 @@ public class ValidateOXMTest { } } - /** - * Verifies that all of the top level node types in the oxm's have their namespace in uri templates. + * Verifies that all of the top level node types in the oxm's have their namespace in uri + * templates. + * * @throws XPathExpressionException * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ @Test - public void verifyAllUriTemplateHaveNamespace() - throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { - boolean foundIssue = false; - List fileList = getOxmSchemaFiles(); - fileList.addAll(getOnapOxmSchemaFiles()); - StringBuilder msg = new StringBuilder(); - for (File file : fileList) { - msg.append(file.getAbsolutePath().replaceAll(".*aai-schema", "")); - msg.append("\n"); - Document xmlDocument = getDocument(file); - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type[" - + "count(xml-properties/xml-property[@name='namespace']) > 0 " + "]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); - - for (int i = 0; i < nodeList.getLength(); i++) { - String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - - NodeList childNodeList = (NodeList) nodeList.item(i).getChildNodes(); - for (int j = 0; j < childNodeList.getLength(); j++) { - - String nodeName = childNodeList.item(j).getNodeName(); - NodeList xmlPropertyNodeList = childNodeList.item(j).getChildNodes(); - if (XMLPROPERTIES.equals(nodeName)) { - - String namespaceVal = ""; - String uriTemplateVal = ""; - for (int k = 0; k < xmlPropertyNodeList.getLength(); k++) { - - if ("xml-property".equals(xmlPropertyNodeList.item(k).getNodeName())) { - - NamedNodeMap attributes = xmlPropertyNodeList.item(k).getAttributes(); - - if ("namespace".equals(attributes.getNamedItem("name").getNodeValue())) { - namespaceVal = attributes.getNamedItem("value").getNodeValue(); - } - if ("uriTemplate".equals(attributes.getNamedItem("name").getNodeValue())) { - uriTemplateVal = attributes.getNamedItem("value").getNodeValue(); - } + public void verifyAllUriTemplateHaveNamespace() + throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { + boolean foundIssue = false; + List fileList = getOxmSchemaFiles(); + fileList.addAll(getOnapOxmSchemaFiles()); + StringBuilder msg = new StringBuilder(); + for (File file : fileList) { + msg.append(file.getAbsolutePath().replaceAll(".*aai-schema", "")); + msg.append("\n"); + Document xmlDocument = getDocument(file); + XPath xPath = XPathFactory.newInstance().newXPath(); + String expression = "/xml-bindings/java-types/java-type[" + + "count(xml-properties/xml-property[@name='namespace']) > 0 " + "]"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); - } + for (int i = 0; i < nodeList.getLength(); i++) { + String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - } + NodeList childNodeList = (NodeList) nodeList.item(i).getChildNodes(); + for (int j = 0; j < childNodeList.getLength(); j++) { - if (!uriTemplateVal.startsWith("/" + namespaceVal + "/")) { - foundIssue = true; - msg.append("\t"); - msg.append(uriTemplateVal); - msg.append("\n"); - } + String nodeName = childNodeList.item(j).getNodeName(); + NodeList xmlPropertyNodeList = childNodeList.item(j).getChildNodes(); + if (XMLPROPERTIES.equals(nodeName)) { - } - } + String namespaceVal = ""; + String uriTemplateVal = ""; + for (int k = 0; k < xmlPropertyNodeList.getLength(); k++) { - } - } - if (foundIssue) { - System.out.println(msg.toString()); - fail("uriTemplate doesnt start with /namespace/."); - } + if ("xml-property".equals(xmlPropertyNodeList.item(k).getNodeName())) { + + NamedNodeMap attributes = + xmlPropertyNodeList.item(k).getAttributes(); + + if ("namespace" + .equals(attributes.getNamedItem("name").getNodeValue())) { + namespaceVal = attributes.getNamedItem("value").getNodeValue(); + } + if ("uriTemplate" + .equals(attributes.getNamedItem("name").getNodeValue())) { + uriTemplateVal = + attributes.getNamedItem("value").getNodeValue(); + } + + } + + } + + if (!uriTemplateVal.startsWith("/" + namespaceVal + "/")) { + foundIssue = true; + msg.append("\t"); + msg.append(uriTemplateVal); + msg.append("\n"); + } + + } + } - } + } + } + if (foundIssue) { + System.out.println(msg.toString()); + fail("uriTemplate doesnt start with /namespace/."); + } + } /** * Verifies that all specified properties are indexed - * Currently set to check that "model-invariant-id","model-version-id" which are aliased are indexed + * Currently set to check that "model-invariant-id","model-version-id" which are aliased are + * indexed + * * @throws XPathExpressionException * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ @Test - public void aliasedIndexedPropsAreInIndexedListWithPropName() throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { + public void aliasedIndexedPropsAreInIndexedListWithPropName() + throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { - final List props = Arrays.asList("model-invariant-id","model-version-id"); + final List props = Arrays.asList("model-invariant-id", "model-version-id"); boolean foundIssue = false; List fileList = getLatestFiles(); @@ -398,31 +433,32 @@ public class ValidateOXMTest { for (String prop : props) { Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type[" + - "(" + - "count(xml-properties/xml-property[@name='container']) > 0 " + - "or count(xml-properties/xml-property[@name='dependentOn']) > 0" + - ") " + - "and count(xml-properties/xml-property[@name='indexedProps' and not(contains(@value,'" + prop + "'))]) > 0 " + //prop is not in indexed props list - "and count(java-attributes/xml-element[@name='" + prop + "']) > 0 " + // prop is a property on obj + String expression = "/xml-bindings/java-types/java-type[" + "(" + + "count(xml-properties/xml-property[@name='container']) > 0 " + + "or count(xml-properties/xml-property[@name='dependentOn']) > 0" + ") " + + "and count(xml-properties/xml-property[@name='indexedProps' and not(contains(@value,'" + + prop + "'))]) > 0 " + // prop is not in indexed props list + "and count(java-attributes/xml-element[@name='" + prop + "']) > 0 " + // prop is + // a + // property + // on obj "]"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, + XPathConstants.NODESET); if (nodeList.getLength() > 0) { - msg.append("\t") - .append(prop) - .append("\n"); + msg.append("\t").append(prop).append("\n"); } for (int i = 0; i < nodeList.getLength(); i++) { - String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); - if (name.equals("InstanceFilter") || name.equals("InventoryResponseItems") || name.equals("InventoryResponseItem")) { + String name = + nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); + if (name.equals("InstanceFilter") || name.equals("InventoryResponseItems") + || name.equals("InventoryResponseItem")) { continue; } foundIssue = true; - msg.append("\t\t") - .append(name) - .append("\n"); + msg.append("\t\t").append(name).append("\n"); } } } @@ -441,9 +477,11 @@ public class ValidateOXMTest { */ @Ignore @Test - public void testSchemaValidationAgainstEdgeRules() throws XPathExpressionException, IOException, SAXException, ParserConfigurationException, ParseException { + public void testSchemaValidationAgainstEdgeRules() throws XPathExpressionException, IOException, + SAXException, ParserConfigurationException, ParseException { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - List subDirs = Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); + List subDirs = + Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); boolean success = true; for (File subDir : subDirs) { List oxmSchemaList = new ArrayList<>(); @@ -474,33 +512,27 @@ public class ValidateOXMTest { } }).ifPresent(dbEdgeRulesList::add); - List oxmSchemaFileList = new ArrayList<>(); List dbEdgeRulesFileList = new ArrayList<>(); - oxmSchemaList.forEach(s -> - FileUtils.listFiles( - new File(s), - new RegexFileFilter(".*\\.xml"), + oxmSchemaList.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.xml"), DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) - .forEach(oxmSchemaFileList::add)); - - dbEdgeRulesList.forEach(s -> - FileUtils.listFiles( - new File(s), - new RegexFileFilter(".*\\.json"), + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) + .forEach(oxmSchemaFileList::add)); + + dbEdgeRulesList.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.json"), DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) - .forEach(dbEdgeRulesFileList::add)); + .stream().filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) + .forEach(dbEdgeRulesFileList::add)); // Map the dbEdgeRules json file into a HashMap for reference Map> dbEdgeRules = new HashMap<>(); JSONParser jsonParser = new JSONParser(); for (File file : dbEdgeRulesFileList) { FileReader reader = new FileReader(file); - // Read JSON file. Expecting JSON file to read an object with a JSONArray names "rules" + // Read JSON file. Expecting JSON file to read an object with a JSONArray names + // "rules" JSONObject jsonObj = (JSONObject) jsonParser.parse(reader); JSONArray rules = (JSONArray) jsonObj.get(DBEDGERULES_RULES); for (int i = 0; i < rules.size(); i++) { @@ -534,25 +566,30 @@ public class ValidateOXMTest { for (File file : oxmSchemaFileList) { Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String parentNodeExpression = "/xml-bindings/java-types/java-type/xml-properties/xml-property[@name='dependentOn']"; - NodeList parentNodeList = (NodeList) xPath.compile(parentNodeExpression).evaluate(xmlDocument, XPathConstants.NODESET); - String childNodeExpression = "/xml-bindings/java-types/java-type[" + - "(" + - "count(xml-properties/xml-property[@name='dependentOn']) > 0" + - ")]"; - NodeList childNodeList = (NodeList) xPath.compile(childNodeExpression).evaluate(xmlDocument, XPathConstants.NODESET); + String parentNodeExpression = + "/xml-bindings/java-types/java-type/xml-properties/xml-property[@name='dependentOn']"; + NodeList parentNodeList = (NodeList) xPath.compile(parentNodeExpression) + .evaluate(xmlDocument, XPathConstants.NODESET); + String childNodeExpression = "/xml-bindings/java-types/java-type[" + "(" + + "count(xml-properties/xml-property[@name='dependentOn']) > 0" + ")]"; + NodeList childNodeList = (NodeList) xPath.compile(childNodeExpression) + .evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < parentNodeList.getLength(); i++) { - // Obtain the xml-root-element field by tracing the childNodes from the java-type parent node + // Obtain the xml-root-element field by tracing the childNodes from the + // java-type parent node for (int j = 0; j < childNodeList.item(i).getChildNodes().getLength(); j++) { - if (childNodeList.item(i).getChildNodes().item(j).getNodeName().equals(XMLROOTELEMENT)) { + if (childNodeList.item(i).getChildNodes().item(j).getNodeName() + .equals(XMLROOTELEMENT)) { // The parent node - String dependentOn = parentNodeList.item(i).getAttributes().getNamedItem("value").getNodeValue(); + String dependentOn = parentNodeList.item(i).getAttributes() + .getNamedItem("value").getNodeValue(); // The child node - String xmlRootElement = childNodeList.item(i).getChildNodes().item(j).getAttributes().getNamedItem("name").getNodeValue(); + String xmlRootElement = childNodeList.item(i).getChildNodes().item(j) + .getAttributes().getNamedItem("name").getNodeValue(); Set childSet; String[] parents = dependentOn.split(","); @@ -572,7 +609,8 @@ public class ValidateOXMTest { } } - // Compare the OXM file against the dbEdgeRules file. check what is missing in dbEdgeRules from the oxm files. + // Compare the OXM file against the dbEdgeRules file. check what is missing in + // dbEdgeRules from the oxm files. Set oxmKeySet = oxmSchemaFile.keySet(); for (String key : oxmKeySet) { Set oxmChildren = oxmSchemaFile.get(key); @@ -581,7 +619,9 @@ public class ValidateOXMTest { // Check if the parent vertex exists at all in the dbEdgeRules file if (dbEdgeRulesChildren == null || dbEdgeRulesChildren.isEmpty()) { for (String oxmChild : oxmChildren) { - System.out.println("ERROR: dbEdgeRules under directory '" + subDir.toString() + "' does not contain parent '" + key + "' and child '" + oxmChild + "' relationship"); + System.out.println("ERROR: dbEdgeRules under directory '" + + subDir.toString() + "' does not contain parent '" + key + + "' and child '" + oxmChild + "' relationship"); } success = false; continue; @@ -591,7 +631,9 @@ public class ValidateOXMTest { if (!oxmChildren.equals(dbEdgeRulesChildren)) { for (String oxmChild : oxmChildren) { if (!dbEdgeRulesChildren.contains(oxmChild)) { - System.out.println("ERROR: dbEdgeRules under directory '" + subDir.toString() + "' does not contain parent '" + key + "' and child '" + oxmChild + "' relationship"); + System.out.println("ERROR: dbEdgeRules under directory '" + + subDir.toString() + "' does not contain parent '" + key + + "' and child '" + oxmChild + "' relationship"); success = false; } } @@ -607,7 +649,9 @@ public class ValidateOXMTest { // Check if the parent vertex exists at all in the dbEdgeRules file if (oxmChildren == null || oxmChildren.isEmpty()) { for (String dbEdgeRuleChild : dbEdgeRulesChildren) { - System.out.println("ERROR: oxms under directory '" + subDir.toString() + "' do not contain parent '" + key + "' and child '" + dbEdgeRuleChild + "' relationship"); + System.out.println("ERROR: oxms under directory '" + subDir.toString() + + "' do not contain parent '" + key + "' and child '" + dbEdgeRuleChild + + "' relationship"); } success = false; continue; @@ -617,7 +661,9 @@ public class ValidateOXMTest { if (!dbEdgeRulesChildren.equals(oxmChildren)) { for (String dbEdgeRuleChild : dbEdgeRulesChildren) { if (!oxmChildren.contains(dbEdgeRuleChild)) { - System.out.println("ERROR: oxms under directory '" + subDir.toString() + "' do not contain parent '" + key + "' and child '" + dbEdgeRuleChild + "' relationship"); + System.out.println("ERROR: oxms under directory '" + subDir.toString() + + "' do not contain parent '" + key + "' and child '" + + dbEdgeRuleChild + "' relationship"); success = false; } } @@ -632,27 +678,34 @@ public class ValidateOXMTest { * */ @Test - public void testDataOwnerWithOwnerCheck() throws XPathExpressionException, IOException, SAXException, ParserConfigurationException, ParseException { + public void testDataOwnerWithOwnerCheck() throws XPathExpressionException, IOException, + SAXException, ParserConfigurationException, ParseException { List fileList = getLatestFiles(); for (File file : fileList) { Document xmlDocument = getDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/xml-bindings/java-types/java-type/java-attributes/xml-element[@name='data-owner']"; - NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + String expression = + "/xml-bindings/java-types/java-type/java-attributes/xml-element[@name='data-owner']"; + NodeList nodeList = + (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); List typeMissingOwnerCheck = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { - String type = nodeList.item(i).getParentNode().getParentNode().getAttributes().getNamedItem("name").getNodeValue(); - NodeList xmlPropertiesList = ((Element) nodeList.item(i)).getElementsByTagName("xml-properties"); + String type = nodeList.item(i).getParentNode().getParentNode().getAttributes() + .getNamedItem("name").getNodeValue(); + NodeList xmlPropertiesList = + ((Element) nodeList.item(i)).getElementsByTagName("xml-properties"); boolean missingOwnerCheck = true; for (int j = 0; j < xmlPropertiesList.getLength(); j++) { - NodeList xmlProperties = ((Element) xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); + NodeList xmlProperties = + ((Element) xmlPropertiesList.item(j)).getElementsByTagName("xml-property"); for (int k = 0; k < xmlProperties.getLength(); k++) { - String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name").getNodeValue(); + String xmlProp = xmlProperties.item(k).getAttributes().getNamedItem("name") + .getNodeValue(); if ("ownerCheck".equals(xmlProp)) { missingOwnerCheck = false; @@ -671,13 +724,15 @@ public class ValidateOXMTest { } if (!typeMissingOwnerCheck.isEmpty()) { - fail(file.getAbsolutePath().replaceAll(".*aai-schema", "") + ": " + String.join(", ", typeMissingOwnerCheck)); + fail(file.getAbsolutePath().replaceAll(".*aai-schema", "") + ": " + + String.join(", ", typeMissingOwnerCheck)); } } } /** * Null check for strings + * * @param s * @return */ @@ -687,13 +742,17 @@ public class ValidateOXMTest { /** * Creating a hashmap to map what child nodes are associated to which parent nodes - * according to the dbEdgeRules json files. A HashMap was chosen for the value of the map for O(1) lookup time. + * according to the dbEdgeRules json files. A HashMap was chosen for the value of the map for + * O(1) lookup time. + * * @param from this variable will act as the key or value depending on the direction * @param to this variable will act as the key or value depending on the direction * @param direction dictates the direction of which vertex is dependent on which - * @return The map returned will act as a dictionary to keep track of the parent nodes. Value of the map is a hashmap to help handle collision of multiple children to one parent + * @return The map returned will act as a dictionary to keep track of the parent nodes. Value of + * the map is a hashmap to help handle collision of multiple children to one parent */ - private Map> dbEdgeRulesMapPut(Map> dbEdgeRules, String from, String to, String direction) { + private Map> dbEdgeRulesMapPut(Map> dbEdgeRules, + String from, String to, String direction) { if (isStringEmpty(from) || isStringEmpty(to) || isStringEmpty(direction)) return dbEdgeRules; @@ -722,12 +781,10 @@ public class ValidateOXMTest { private List getFiles() { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - return FileUtils.listFiles( - currentRelativePath.toFile(), - new RegexFileFilter(".*\\.xml"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) + return FileUtils + .listFiles(currentRelativePath.toFile(), new RegexFileFilter(".*\\.xml"), + DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) .filter(file -> !file.getAbsolutePath().contains("onap")) // skips onap for checks .collect(Collectors.toList()); } @@ -735,68 +792,64 @@ public class ValidateOXMTest { private List getOxmSchemaFiles() { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - return FileUtils.listFiles( - currentRelativePath.toFile(), - new RegexFileFilter(".*\\.xml"), + return FileUtils + .listFiles(currentRelativePath.toFile(), new RegexFileFilter(".*\\.xml"), DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) - .filter(file -> file.getAbsolutePath().contains("aai_schema_oxm")) - .filter(file -> !file.getAbsolutePath().contains("onap")) // skips onap for checks - .collect(Collectors.toList()); + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) + .filter(file -> file.getAbsolutePath().contains("aai_schema_oxm")) + .filter(file -> !file.getAbsolutePath().contains("onap")) // skips onap for checks + .collect(Collectors.toList()); } private List getOnapOxmSchemaFiles() { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - return FileUtils.listFiles( - currentRelativePath.toFile(), - new RegexFileFilter(".*\\.xml"), + return FileUtils + .listFiles(currentRelativePath.toFile(), new RegexFileFilter(".*\\.xml"), DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) - .filter(file -> file.getAbsolutePath().contains("aai_oxm")) - .collect(Collectors.toList()); + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) + .filter(file -> file.getAbsolutePath().contains("aai_oxm")) + .collect(Collectors.toList()); } private List getAaiSchemaOxmFiles() { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - return FileUtils.listFiles( - currentRelativePath.toFile(), - new RegexFileFilter(".*\\.xml"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) + return FileUtils + .listFiles(currentRelativePath.toFile(), new RegexFileFilter(".*\\.xml"), + DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) .filter(file -> !file.getAbsolutePath().contains("onap")) // skips onap for checks .collect(Collectors.toList()); } private List getDbEdgeRulesFiles() { Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - return FileUtils.listFiles( - currentRelativePath.toFile(), - new RegexFileFilter(".*\\.json"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) + return FileUtils + .listFiles(currentRelativePath.toFile(), new RegexFileFilter(".*\\.json"), + DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) .filter(file -> !file.getAbsolutePath().contains("onap")) // skips onap for checks .collect(Collectors.toList()); } /** * Finds all of the oxm files for the latest version. + * * @return list of the latest version of the oxm files. */ private List getLatestDbEdgeRulesFiles(String fileDirectory) { List latest = new ArrayList<>(); - String currentRelativePath = Paths.get("../aai-schema/src/main/resources/" + fileDirectory + "/dbedgerules").toAbsolutePath().toString(); + String currentRelativePath = + Paths.get("../aai-schema/src/main/resources/" + fileDirectory + "/dbedgerules") + .toAbsolutePath().toString(); File[] oxms = new File(currentRelativePath).listFiles(File::isDirectory); Arrays.stream(oxms).map(File::getAbsolutePath).max(new Comparator() { public int compare(String o1, String o2) { return extractInt(o1) - extractInt(o2); } + int extractInt(String s) { String num = s.replaceAll("\\D", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); @@ -804,26 +857,24 @@ public class ValidateOXMTest { }).ifPresent(latest::add); List latestFiles = new ArrayList<>(); - latest.forEach(s -> - FileUtils.listFiles( - new File(s), - new RegexFileFilter(".*\\.json"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) - .forEach(latestFiles::add)); + latest.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.json"), DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("DbEdgeRules")) + .forEach(latestFiles::add)); return latestFiles; } /** * Finds all of the oxm files for the latest version. + * * @return list of the latest version of the oxm files. */ private List getLatestFiles() { List latest = new ArrayList<>(); Path currentRelativePath = Paths.get("../aai-schema/src/main/resources/").toAbsolutePath(); - List subDirs = Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); + List subDirs = + Arrays.asList(currentRelativePath.toFile().listFiles(File::isDirectory)); for (File subDir : subDirs) { String oxm = subDir.getAbsolutePath() + "/oxm"; File[] oxms = new File(oxm).listFiles(File::isDirectory); @@ -831,6 +882,7 @@ public class ValidateOXMTest { public int compare(String o1, String o2) { return extractInt(o1) - extractInt(o2); } + int extractInt(String s) { String num = s.replaceAll("\\D", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); @@ -839,30 +891,30 @@ public class ValidateOXMTest { } List latestFiles = new ArrayList<>(); - latest.forEach(s -> - FileUtils.listFiles( - new File(s), - new RegexFileFilter(".*\\.xml"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) - .forEach(latestFiles::add)); + latest.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.xml"), DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) + .forEach(latestFiles::add)); return latestFiles; } /** * Finds all of the oxm files for the latest version. + * * @return list of the latest version of the oxm files. */ private List getLatestFiles(String fileDirectory) { List latest = new ArrayList<>(); - String currentRelativePath = Paths.get("../aai-schema/src/main/resources/" + fileDirectory + "/oxm").toAbsolutePath().toString(); + String currentRelativePath = + Paths.get("../aai-schema/src/main/resources/" + fileDirectory + "/oxm").toAbsolutePath() + .toString(); File[] oxms = new File(currentRelativePath).listFiles(File::isDirectory); Arrays.stream(oxms).map(File::getAbsolutePath).max(new Comparator() { public int compare(String o1, String o2) { return extractInt(o1) - extractInt(o2); } + int extractInt(String s) { String num = s.replaceAll("\\D", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); @@ -870,21 +922,15 @@ public class ValidateOXMTest { }).ifPresent(latest::add); List latestFiles = new ArrayList<>(); - latest.forEach(s -> - FileUtils.listFiles( - new File(s), - new RegexFileFilter(".*\\.xml"), - DirectoryFileFilter.DIRECTORY) - .stream() - .filter(file -> file.getAbsolutePath().contains("oxm")) - .forEach(latestFiles::add)); + latest.forEach(s -> FileUtils + .listFiles(new File(s), new RegexFileFilter(".*\\.xml"), DirectoryFileFilter.DIRECTORY) + .stream().filter(file -> file.getAbsolutePath().contains("oxm")) + .forEach(latestFiles::add)); return latestFiles; } - //TODO test that all oxm xml are valid xml - - + // TODO test that all oxm xml are valid xml public String printNodeList(NodeList nodeList, Document doc) throws IOException { StringBuilder stringBuilder = new StringBuilder(); @@ -900,7 +946,8 @@ public class ValidateOXMTest { } - private Document getDocument(File file) throws ParserConfigurationException, SAXException, IOException { + private Document getDocument(File file) + throws ParserConfigurationException, SAXException, IOException { InputStream fileIS = new FileInputStream(file); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); -- 2.16.6