summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rwxr-xr-xcps-application/pom.xml4
-rw-r--r--cps-application/src/main/resources/application.yml15
-rwxr-xr-xcps-dependencies/pom.xml12
-rw-r--r--cps-events/pom.xml1
-rwxr-xr-xcps-parent/pom.xml5
-rw-r--r--cps-path-parser/src/main/antlr4/org/onap/cps/cpspath/parser/antlr4/CpsPath.g454
-rw-r--r--cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathBuilder.java52
-rw-r--r--cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathPrefixType.java (renamed from cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQueryType.java)17
-rw-r--r--cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQuery.java28
-rw-r--r--cps-path-parser/src/test/groovy/org/onap/cps/cpspath/parser/CpsPathQuerySpec.groovy63
-rwxr-xr-xcps-rest/pom.xml7
-rw-r--r--cps-rest/src/main/resources/static/components.yml (renamed from cps-rest/docs/openapi/components.yml)1
-rw-r--r--cps-rest/src/main/resources/static/cpsAdmin.yml (renamed from cps-rest/docs/openapi/cpsAdmin.yml)0
-rw-r--r--cps-rest/src/main/resources/static/cpsData.yml (renamed from cps-rest/docs/openapi/cpsData.yml)7
-rw-r--r--cps-rest/src/main/resources/static/cpsQuery.yml (renamed from cps-rest/docs/openapi/cpsQuery.yml)0
-rw-r--r--cps-rest/src/main/resources/static/openapi.yml (renamed from cps-rest/docs/openapi/openapi.yml)2
-rw-r--r--cps-ri/pom.xml9
-rw-r--r--cps-ri/src/main/java/org/onap/cps/spi/impl/CpsDataPersistenceServiceImpl.java85
-rwxr-xr-xcps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java3
-rwxr-xr-xcps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepository.java41
-rw-r--r--cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQuery.java29
-rw-r--r--cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQueryImpl.java120
-rw-r--r--cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceQueryDataNodeSpec.groovy46
-rwxr-xr-xcps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceIntegrationSpec.groovy436
-rw-r--r--[-rwxr-xr-x]cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceSpec.groovy422
-rw-r--r--cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceSpec.groovy (renamed from cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceUnitSpec.groovy)2
-rwxr-xr-xcps-ri/src/test/java/org/onap/cps/DatabaseTestContainer.java6
-rw-r--r--cps-ri/src/test/resources/data/anchor.sql24
-rw-r--r--cps-ri/src/test/resources/data/clear-all.sql22
-rw-r--r--cps-ri/src/test/resources/data/cps-path-query.sql27
-rwxr-xr-xcps-ri/src/test/resources/data/fragment.sql24
-rw-r--r--cps-ri/src/test/resources/data/schemaset.sql22
-rw-r--r--cps-service/src/main/java/org/onap/cps/spi/exceptions/ConcurrencyException.java27
-rw-r--r--cps-service/src/main/java/org/onap/cps/utils/YangUtils.java3
-rwxr-xr-xcps-service/src/test/groovy/org/onap/cps/api/impl/CpsAdminServiceImplSpec.groovy10
-rw-r--r--cps-service/src/test/groovy/org/onap/cps/model/DataNodeBuilderSpec.groovy14
-rw-r--r--cps-service/src/test/resources/test-tree.json8
-rw-r--r--cps-service/src/test/resources/test-tree.yang12
-rwxr-xr-xcsit/plans/default/setup.sh8
-rw-r--r--csit/tests/actuator/actuator.robot8
-rw-r--r--csit/tests/cps-admin/cps-admin.robot14
-rw-r--r--csit/tests/cps-data/cps-data.robot6
-rwxr-xr-xdocker-compose/docker-compose.yml3
-rw-r--r--docs/cps-path.rst153
-rwxr-xr-xdocs/release-notes.rst6
45 files changed, 1199 insertions, 659 deletions
diff --git a/cps-application/pom.xml b/cps-application/pom.xml
index 1ea5d330d..9ce0006ce 100755
--- a/cps-application/pom.xml
+++ b/cps-application/pom.xml
@@ -66,6 +66,10 @@
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
+ <groupId>io.micrometer</groupId>
+ <artifactId>micrometer-registry-prometheus</artifactId>
+ </dependency>
+ <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
diff --git a/cps-application/src/main/resources/application.yml b/cps-application/src/main/resources/application.yml
index 5ae6786ef..ac620f6cb 100644
--- a/cps-application/src/main/resources/application.yml
+++ b/cps-application/src/main/resources/application.yml
@@ -73,28 +73,33 @@ notification:
enabled: false
topic: ${CPS_CHANGE_EVENT_TOPIC:cps.cfg-state-events}
+springdoc:
+ swagger-ui:
+ url: /openapi.yml
+ path: /swagger-ui/index.html
+
security:
# comma-separated uri patterns which do not require authorization
- permit-uri: /manage/health/**,/manage/info,/swagger-ui/**,/swagger-resources/**,/v3/api-docs
+ permit-uri: /manage/**,/swagger-ui/**,/swagger-resources/**,/v3/api-docs
auth:
username: ${CPS_USERNAME}
password: ${CPS_PASSWORD}
# Actuator
management:
+ server:
+ port: 8081
endpoints:
web:
base-path: /manage
- exposure:
- include: info,health,loggers
+ exposure:
+ include: info,health,loggers,prometheus
endpoint:
health:
show-details: always
# kubernetes probes: liveness and readiness
probes:
enabled: true
- loggers:
- enabled: true
logging:
level:
diff --git a/cps-dependencies/pom.xml b/cps-dependencies/pom.xml
index 8be6e1ccc..8d147abeb 100755
--- a/cps-dependencies/pom.xml
+++ b/cps-dependencies/pom.xml
@@ -29,6 +29,14 @@
<name>${project.groupId}:${project.artifactId}</name>
<description>This artifact contains dependencyManagement declarations of upstream versions.</description>
+ <repositories>
+ <repository>
+ <id>nordix-liquibase-repo</id>
+ <name>liquibase</name>
+ <url>https://artifactory.nordix.org/artifactory/liquibase</url>
+ </repository>
+ </repositories>
+
<properties>
<groovy.version>3.0.8</groovy.version>
<nexusproxy>https://nexus.onap.org</nexusproxy>
@@ -70,7 +78,7 @@
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>5.0.7</version>
+ <version>6.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -158,7 +166,7 @@
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
- <version>4.3.1</version>
+ <version>4.4.2-nordix</version>
</dependency>
<dependency>
<groupId>com.tngtech.archunit</groupId>
diff --git a/cps-events/pom.xml b/cps-events/pom.xml
index 7c7fec77e..384440846 100644
--- a/cps-events/pom.xml
+++ b/cps-events/pom.xml
@@ -59,6 +59,7 @@
<sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
<targetPackage>org.onap.cps.event.model</targetPackage>
<generateBuilders>true</generateBuilders>
+ <serializable>true</serializable>
</configuration>
</plugin>
<plugin>
diff --git a/cps-parent/pom.xml b/cps-parent/pom.xml
index 40840db75..59b42903c 100755
--- a/cps-parent/pom.xml
+++ b/cps-parent/pom.xml
@@ -113,6 +113,11 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>3.0.0-M5</version>
+ </plugin>
<!-- Swagger code generation. -->
<plugin>
<groupId>io.swagger.codegen.v3</groupId>
diff --git a/cps-path-parser/src/main/antlr4/org/onap/cps/cpspath/parser/antlr4/CpsPath.g4 b/cps-path-parser/src/main/antlr4/org/onap/cps/cpspath/parser/antlr4/CpsPath.g4
index 198cede0d..cefeac438 100644
--- a/cps-path-parser/src/main/antlr4/org/onap/cps/cpspath/parser/antlr4/CpsPath.g4
+++ b/cps-path-parser/src/main/antlr4/org/onap/cps/cpspath/parser/antlr4/CpsPath.g4
@@ -20,56 +20,50 @@
grammar CpsPath ;
-cpsPath: (cpsPathWithSingleLeafCondition | cpsPathWithDescendant | cpsPathWithDescendantAndLeafConditions) ancestorAxis? ;
+cpsPath : ( prefix | descendant | incorrectPrefix ) multipleLeafConditions? textFunctionCondition? ancestorAxis? ;
-ancestorAxis: SLASH KW_ANCESTOR COLONCOLON ancestorPath ;
+ancestorAxis : SLASH KW_ANCESTOR COLONCOLON ancestorPath ;
-ancestorPath: yangElement (SLASH yangElement)* ;
+ancestorPath : yangElement ( SLASH yangElement)* ;
-cpsPathWithSingleLeafCondition: prefix singleValueCondition postfix? ;
+textFunctionCondition : SLASH leafName OB KW_TEXT_FUNCTION EQ StringLiteral CB ;
-/*
-No need to ditinguish between cpsPathWithDescendant | cpsPathWithDescendantAndLeafConditions really!
-See https://jira.onap.org/browse/CPS-436
-*/
-
-cpsPathWithDescendant: descendant ;
-
-cpsPathWithDescendantAndLeafConditions: descendant multipleValueConditions ;
+prefix : ( SLASH yangElement)* SLASH containerName ;
-descendant: SLASH prefix ;
+descendant : SLASH prefix ;
-prefix: (SLASH yangElement)* SLASH containerName ;
+incorrectPrefix : SLASH SLASH SLASH+ ;
-postfix: (SLASH yangElement)+ ;
+yangElement : containerName listElementRef? ;
-yangElement: containerName listElementRef? ;
+containerName : QName ;
-containerName: QName ;
+listElementRef : OB leafCondition ( KW_AND leafCondition)* CB ;
-listElementRef: multipleValueConditions ;
+multipleLeafConditions : OB leafCondition ( KW_AND leafCondition)* CB ;
-singleValueCondition: '[' leafCondition ']' ;
+leafCondition : AT leafName EQ ( IntegerLiteral | StringLiteral) ;
-multipleValueConditions: '[' leafCondition (' and ' leafCondition)* ']' ;
-
-leafCondition: '@' leafName '=' (IntegerLiteral | StringLiteral ) ;
-
-//To Confirm: defintion of Lefname with external xPath grammar
-leafName: QName ;
+leafName : QName ;
/*
* Lexer Rules
- * Most of the lexer rules below are 'imporetd' from
+ * Most of the lexer rules below are inspired by
* https://raw.githubusercontent.com/antlr/grammars-v4/master/xpath/xpath31/XPath31.g4
*/
-SLASH : '/';
+AT : '@' ;
+CB : ']' ;
COLONCOLON : '::' ;
+EQ : '=' ;
+OB : '[' ;
+SLASH : '/' ;
// KEYWORDS
KW_ANCESTOR : 'ancestor' ;
+KW_AND : 'and' ;
+KW_TEXT_FUNCTION: 'text()' ;
IntegerLiteral : FragDigits ;
// Add below type definitions for leafvalue comparision in https://jira.onap.org/browse/CPS-440
@@ -77,7 +71,7 @@ DecimalLiteral : ('.' FragDigits) | (FragDigits '.' [0-9]*) ;
DoubleLiteral : (('.' FragDigits) | (FragDigits ('.' [0-9]*)?)) [eE] [+-]? FragDigits ;
StringLiteral : ('"' (FragEscapeQuot | ~[^"])*? '"') | ('\'' (FragEscapeApos | ~['])*? '\'') ;
fragment FragEscapeQuot : '""' ;
-fragment FragEscapeApos : '\'';
+fragment FragEscapeApos : '\'' ;
fragment FragDigits : [0-9]+ ;
QName : FragQName ;
@@ -109,7 +103,7 @@ fragment FragNCNameChar
| '\u00B7' | '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
-fragment FragmentNCName : FragNCNameStartChar FragNCNameChar* ;
+fragment FragmentNCName : FragNCNameStartChar FragNCNameChar* ;
// https://www.w3.org/TR/REC-xml/#NT-Char
@@ -117,7 +111,7 @@ fragment FragChar : '\u0009' | '\u000a' | '\u000d'
| '\u0020'..'\ud7ff'
| '\ue000'..'\ufffd'
| '\u{10000}'..'\u{10ffff}'
- ;
+ ;
// Skip all Whitespace
Whitespace : ('\u000d' | '\u000a' | '\u0020' | '\u0009')+ -> skip ;
diff --git a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathBuilder.java b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathBuilder.java
index b9d0c25b1..ebf6fd3c9 100644
--- a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathBuilder.java
+++ b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathBuilder.java
@@ -20,18 +20,18 @@
package org.onap.cps.cpspath.parser;
+import static org.onap.cps.cpspath.parser.CpsPathPrefixType.DESCENDANT;
+
import java.util.HashMap;
import java.util.Map;
import org.onap.cps.cpspath.parser.antlr4.CpsPathBaseListener;
import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.AncestorAxisContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.CpsPathWithDescendantAndLeafConditionsContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.CpsPathWithDescendantContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.CpsPathWithSingleLeafConditionContext;
+import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.DescendantContext;
+import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.IncorrectPrefixContext;
import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.LeafConditionContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.MultipleValueConditionsContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.PostfixContext;
+import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.MultipleLeafConditionsContext;
import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.PrefixContext;
-import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.SingleValueConditionContext;
+import org.onap.cps.cpspath.parser.antlr4.CpsPathParser.TextFunctionConditionContext;
public class CpsPathBuilder extends CpsPathBaseListener {
@@ -45,8 +45,8 @@ public class CpsPathBuilder extends CpsPathBaseListener {
}
@Override
- public void exitPostfix(final PostfixContext ctx) {
- throw new IllegalStateException(String.format("Unsupported postfix %s encountered in CpsPath.", ctx.getText()));
+ public void exitIncorrectPrefix(final IncorrectPrefixContext ctx) {
+ throw new IllegalStateException("CPS path can only start with one or two slashes (/)");
}
@Override
@@ -64,38 +64,18 @@ public class CpsPathBuilder extends CpsPathBaseListener {
}
@Override
- public void enterSingleValueCondition(final SingleValueConditionContext ctx) {
- leavesData.clear();
+ public void exitDescendant(final DescendantContext ctx) {
+ cpsPathQuery.setCpsPathPrefixType(DESCENDANT);
+ cpsPathQuery.setDescendantName(ctx.getText().substring(2));
}
@Override
- public void enterMultipleValueConditions(final MultipleValueConditionsContext ctx) {
+ public void enterMultipleLeafConditions(final MultipleLeafConditionsContext ctx) {
leavesData.clear();
}
@Override
- public void exitSingleValueCondition(final SingleValueConditionContext ctx) {
- final String leafName = ctx.leafCondition().leafName().getText();
- cpsPathQuery.setLeafName(leafName);
- cpsPathQuery.setLeafValue(leavesData.get(leafName));
- }
-
- @Override
- public void exitCpsPathWithSingleLeafCondition(final CpsPathWithSingleLeafConditionContext ctx) {
- cpsPathQuery.setCpsPathQueryType(CpsPathQueryType.XPATH_LEAF_VALUE);
- }
-
- @Override
- public void exitCpsPathWithDescendant(final CpsPathWithDescendantContext ctx) {
- cpsPathQuery.setCpsPathQueryType(CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE);
- cpsPathQuery.setDescendantName(cpsPathQuery.getXpathPrefix().substring(1));
- }
-
- @Override
- public void exitCpsPathWithDescendantAndLeafConditions(
- final CpsPathWithDescendantAndLeafConditionsContext ctx) {
- cpsPathQuery.setCpsPathQueryType(CpsPathQueryType.XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES);
- cpsPathQuery.setDescendantName(cpsPathQuery.getXpathPrefix().substring(1));
+ public void exitMultipleLeafConditions(final MultipleLeafConditionsContext ctx) {
cpsPathQuery.setLeavesData(leavesData);
}
@@ -104,6 +84,12 @@ public class CpsPathBuilder extends CpsPathBaseListener {
cpsPathQuery.setAncestorSchemaNodeIdentifier(ctx.ancestorPath().getText());
}
+ @Override
+ public void exitTextFunctionCondition(final TextFunctionConditionContext ctx) {
+ cpsPathQuery.setTextFunctionConditionLeafName(ctx.leafName().getText());
+ cpsPathQuery.setTextFunctionConditionValue(stripFirstAndLastCharacter(ctx.StringLiteral().getText()));
+ }
+
CpsPathQuery build() {
return cpsPathQuery;
}
diff --git a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQueryType.java b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathPrefixType.java
index ac3e31334..dfac9b0c8 100644
--- a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQueryType.java
+++ b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathPrefixType.java
@@ -22,19 +22,16 @@
package org.onap.cps.cpspath.parser;
/**
- * The enum Cps path query type.
+ * The enum Cps path prefix type.
*/
-public enum CpsPathQueryType {
+public enum CpsPathPrefixType {
/**
- * Xpath descendant anywhere type e.g. //nodeName .
+ * Fully qualified Xpath starting from root with single slash e.g. /parent/child .
*/
- XPATH_HAS_DESCENDANT_ANYWHERE,
- /**
- * Xpath descendant anywhere type e.g. //nodeName[@leafName="value"] .
- */
- XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES,
+ ABSOLUTE,
+
/**
- * Xpath leaf value cps path query type e.g. /cps-path[@leaf1="leafValue" and @leaf2=123] .
+ * Xpath descendant anywhere starting with double slash type e.g. //child/grandchild .
*/
- XPATH_LEAF_VALUE
+ DESCENDANT
}
diff --git a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQuery.java b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQuery.java
index 107bfa3e3..de7adf2b7 100644
--- a/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQuery.java
+++ b/cps-path-parser/src/main/java/org/onap/cps/cpspath/parser/CpsPathQuery.java
@@ -20,6 +20,8 @@
package org.onap.cps.cpspath.parser;
+import static org.onap.cps.cpspath.parser.CpsPathPrefixType.ABSOLUTE;
+
import java.util.Map;
import lombok.AccessLevel;
import lombok.Getter;
@@ -36,13 +38,13 @@ import org.onap.cps.cpspath.parser.antlr4.CpsPathParser;
@Setter(AccessLevel.PACKAGE)
public class CpsPathQuery {
- private CpsPathQueryType cpsPathQueryType;
private String xpathPrefix;
- private String leafName;
- private Object leafValue;
+ private CpsPathPrefixType cpsPathPrefixType = ABSOLUTE;
private String descendantName;
private Map<String, Object> leavesData;
private String ancestorSchemaNodeIdentifier = "";
+ private String textFunctionConditionLeafName;
+ private String textFunctionConditionValue;
/**
* Returns a cps path query.
@@ -68,7 +70,7 @@ public class CpsPathQuery {
}
/**
- * Has ancestor axis been populated.
+ * Has ancestor axis been included in cpsPath.
*
* @return boolean value.
*/
@@ -76,4 +78,22 @@ public class CpsPathQuery {
return !(ancestorSchemaNodeIdentifier.isEmpty());
}
+ /**
+ * Have leaf value conditions been included in cpsPath.
+ *
+ * @return boolean value.
+ */
+ public boolean hasLeafConditions() {
+ return leavesData != null;
+ }
+
+ /**
+ * Has text function condition been included in cpsPath.
+ *
+ * @return boolean value.
+ */
+ public boolean hasTextFunctionCondition() {
+ return textFunctionConditionLeafName != null;
+ }
+
}
diff --git a/cps-path-parser/src/test/groovy/org/onap/cps/cpspath/parser/CpsPathQuerySpec.groovy b/cps-path-parser/src/test/groovy/org/onap/cps/cpspath/parser/CpsPathQuerySpec.groovy
index b7826f67b..bfec574eb 100644
--- a/cps-path-parser/src/test/groovy/org/onap/cps/cpspath/parser/CpsPathQuerySpec.groovy
+++ b/cps-path-parser/src/test/groovy/org/onap/cps/cpspath/parser/CpsPathQuerySpec.groovy
@@ -22,17 +22,21 @@ package org.onap.cps.cpspath.parser
import spock.lang.Specification
+import static org.onap.cps.cpspath.parser.CpsPathPrefixType.ABSOLUTE
+import static org.onap.cps.cpspath.parser.CpsPathPrefixType.DESCENDANT
+
class CpsPathQuerySpec extends Specification {
def 'Parse cps path with valid cps path and a filter with #scenario.'() {
when: 'the given cps path is parsed'
def result = CpsPathQuery.createFrom(cpsPath)
- then: 'the query has the right type'
- result.cpsPathQueryType == CpsPathQueryType.XPATH_LEAF_VALUE
+ then: 'the query has the right xpath type'
+ result.cpsPathPrefixType == ABSOLUTE
and: 'the right query parameters are set'
result.xpathPrefix == expectedXpathPrefix
- result.leafName == expectedLeafName
- result.leafValue == expectedLeafValue
+ result.hasLeafConditions() == true
+ result.leavesData.containsKey(expectedLeafName) == true
+ result.leavesData.get(expectedLeafName) == expectedLeafValue
where: 'the following data is used'
scenario | cpsPath || expectedXpathPrefix | expectedLeafName | expectedLeafValue
'leaf of type String' | '/parent/child[@common-leaf-name="common-leaf-value"]' || '/parent/child' | 'common-leaf-name' | 'common-leaf-value'
@@ -46,8 +50,8 @@ class CpsPathQuerySpec extends Specification {
def 'Parse cps path of type ends with a #scenario.'() {
when: 'the given cps path is parsed'
def result = CpsPathQuery.createFrom(cpsPath)
- then: 'the query has the right type'
- result.cpsPathQueryType == CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE
+ then: 'the query has the right xpath type'
+ result.cpsPathPrefixType == DESCENDANT
and: 'the right ends with parameters are set'
result.descendantName == expectedDescendantName
where: 'the following data is used'
@@ -59,9 +63,9 @@ class CpsPathQuerySpec extends Specification {
def 'Parse cps path that ends with a yang list containing #scenario.'() {
when: 'the given cps path is parsed'
def result = CpsPathQuery.createFrom(cpsPath)
- then: 'the query has the right type'
- result.cpsPathQueryType == CpsPathQueryType.XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES
- and: 'the right ends with parameters are set'
+ then: 'the query has the right xpath type'
+ result.cpsPathPrefixType == DESCENDANT
+ and: 'the right parameters are set'
result.descendantName == "child"
result.leavesData.size() == expectedNumberOfLeaves
where: 'the following data is used'
@@ -70,6 +74,27 @@ class CpsPathQuerySpec extends Specification {
'more than one attribute' | '//child[@int-leaf=5 and @leaf-name="leaf value"]' || 2
}
+ def 'Parse #scenario cps path with text function condition'() {
+ when: 'the given cps path is parsed'
+ def result = CpsPathQuery.createFrom(cpsPath)
+ then: 'the query has the right xpath type'
+ result.cpsPathPrefixType == DESCENDANT
+ and: 'leaf conditions are only present when expected'
+ result.hasLeafConditions() == expectLeafConditions
+ and: 'the right text function condition is set'
+ result.hasTextFunctionCondition()
+ result.textFunctionConditionLeafName == 'leaf-name'
+ result.textFunctionConditionValue == 'search'
+ and: 'the ancestor is only present when expected'
+ assert result.hasAncestorAxis() == expectHasAncestorAxis
+ where: 'the following data is used'
+ scenario | cpsPath || expectLeafConditions | expectHasAncestorAxis
+ 'descendant anywhere' | '//someContainer/leaf-name[text()="search"]' || false | false
+ 'descendant with leaf value' | '//child[@other-leaf=1]/leaf-name[text()="search"]' || true | false
+ 'descendant anywhere and ancestor' | '//someContainer/leaf-name[text()="search"]/ancestor::parent' || false | true
+ 'descendant with leaf value and ancestor' | '//child[@other-leaf=1]/leaf-name[text()="search"]/ancestor::parent' || true | true
+ }
+
def 'Parse cps path with error: #scenario.'() {
when: 'the given cps path is parsed'
CpsPathQuery.createFrom(cpsPath)
@@ -85,18 +110,20 @@ class CpsPathQuerySpec extends Specification {
'end with descendant and more than one attribute separated by "or"' | '//child[@int-leaf=5 or @leaf-name="leaf value"]'
'missing attribute value' | '//child[@int-leaf=5 and @name]'
'incomplete ancestor value' | '//books/ancestor::'
- 'unsupported postfix after single value condition (JIRA CPS-450)' | '/parent/child[@id=1]/somePostFix'
+// DISCUSS WITH TEAM : 'unsupported postfix after value condition (JIRA CPS-450)' | '/parent/child[@id=1]/somePostFix'
}
def 'Parse cps path using ancestor by schema node identifier with a #scenario.'() {
when: 'the given cps path is parsed'
def result = CpsPathQuery.createFrom('//descendant/ancestor::' + ancestorPath)
then: 'the query has the right type'
- result.cpsPathQueryType == CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE
+ result.cpsPathPrefixType == DESCENDANT
and: 'the result has ancestor axis'
result.hasAncestorAxis()
and: 'the correct ancestor schema node identifier is set'
result.ancestorSchemaNodeIdentifier == ancestorPath
+ and: 'there are no leaves conditions'
+ result.hasLeafConditions() == false
where:
scenario | ancestorPath
'basic container' | 'someContainer'
@@ -109,18 +136,20 @@ class CpsPathQuerySpec extends Specification {
when: 'the given cps path is parsed'
def result = CpsPathQuery.createFrom(cpsPath + '/ancestor::someAncestor')
then: 'the query has the right type'
- result.cpsPathQueryType == expectedCpsPathQueryType
+ result.cpsPathPrefixType == DESCENDANT
+ and: 'leaf conditions are only present when expected'
+ result.hasLeafConditions() == expectLeafConditions
and: 'the result has ancestor axis'
result.hasAncestorAxis()
and: 'the correct ancestor schema node identifier is set'
result.ancestorSchemaNodeIdentifier == 'someAncestor'
result.descendantName == expectedDescendantName
where:
- scenario | cpsPath || expectedDescendantName | expectedCpsPathQueryType
- 'basic container' | '//someContainer' || 'someContainer' | CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE
- 'container with parent' | '//parent/child' || 'parent/child' | CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE
- 'container with list-parent' | '//parent[@id=1]/child' || 'parent[@id=1]/child' | CpsPathQueryType.XPATH_HAS_DESCENDANT_ANYWHERE
- 'container with list-parent' | '//parent[@id=1]/child[@name="test"]' || 'parent[@id=1]/child' | CpsPathQueryType.XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES
+ scenario | cpsPath || expectedDescendantName | expectLeafConditions
+ 'basic container' | '//someContainer' || 'someContainer' | false
+ 'container with parent' | '//parent/child' || 'parent/child' | false
+ 'container with list-parent' | '//parent[@id=1]/child' || 'parent[@id=1]/child' | false
+ 'container with list-parent' | '//parent[@id=1]/child[@name="test"]' || 'parent[@id=1]/child' | true
}
}
diff --git a/cps-rest/pom.xml b/cps-rest/pom.xml
index 4b42656e8..9a131176d 100755
--- a/cps-rest/pom.xml
+++ b/cps-rest/pom.xml
@@ -75,6 +75,11 @@
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-ui</artifactId>
+ <version>1.5.9</version>
+ </dependency>
+ <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
@@ -133,7 +138,7 @@
<goal>generate</goal>
</goals>
<configuration>
- <inputSpec>${project.basedir}/docs/openapi/openapi.yml</inputSpec>
+ <inputSpec>${project.basedir}/src/main/resources/static/openapi.yml</inputSpec>
<invokerPackage>org.onap.cps.rest.controller</invokerPackage>
<modelPackage>org.onap.cps.rest.model</modelPackage>
<apiPackage>org.onap.cps.rest.api</apiPackage>
diff --git a/cps-rest/docs/openapi/components.yml b/cps-rest/src/main/resources/static/components.yml
index 6543fcab6..51a49a6e9 100644
--- a/cps-rest/docs/openapi/components.yml
+++ b/cps-rest/src/main/resources/static/components.yml
@@ -196,6 +196,7 @@ components:
application/json:
schema:
type: object
+ example: { "key": "value" }
Created:
description: Created
content:
diff --git a/cps-rest/docs/openapi/cpsAdmin.yml b/cps-rest/src/main/resources/static/cpsAdmin.yml
index 35b2e4ca6..35b2e4ca6 100644
--- a/cps-rest/docs/openapi/cpsAdmin.yml
+++ b/cps-rest/src/main/resources/static/cpsAdmin.yml
diff --git a/cps-rest/docs/openapi/cpsData.yml b/cps-rest/src/main/resources/static/cpsData.yml
index fb21f757a..7e9f71d62 100644
--- a/cps-rest/docs/openapi/cpsData.yml
+++ b/cps-rest/src/main/resources/static/cpsData.yml
@@ -28,7 +28,12 @@ nodeByDataspaceAndAnchor:
- $ref: 'components.yml#/components/parameters/includeDescendantsOptionInQuery'
responses:
'200':
- $ref: 'components.yml#/components/responses/Ok'
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ example: { "child": my_child,"leafList": "leafListElement1, leafListElement2", "leaf": my_leaf }
'400':
$ref: 'components.yml#/components/responses/BadRequest'
'401':
diff --git a/cps-rest/docs/openapi/cpsQuery.yml b/cps-rest/src/main/resources/static/cpsQuery.yml
index f45f3f41a..f45f3f41a 100644
--- a/cps-rest/docs/openapi/cpsQuery.yml
+++ b/cps-rest/src/main/resources/static/cpsQuery.yml
diff --git a/cps-rest/docs/openapi/openapi.yml b/cps-rest/src/main/resources/static/openapi.yml
index caaad68b6..8fa640cf9 100644
--- a/cps-rest/docs/openapi/openapi.yml
+++ b/cps-rest/src/main/resources/static/openapi.yml
@@ -35,7 +35,7 @@ info:
url: "cps_logo.png"
servers:
- - url: //localhost:8088
+ - url: /cps/api
tags:
- name: cps-admin
description: cps Admin
diff --git a/cps-ri/pom.xml b/cps-ri/pom.xml
index 033b2e211..273cb2e72 100644
--- a/cps-ri/pom.xml
+++ b/cps-ri/pom.xml
@@ -32,6 +32,14 @@
<artifactId>cps-ri</artifactId>
+ <repositories>
+ <repository>
+ <id>nordix-liquibase-repo</id>
+ <name>liquibase</name>
+ <url>https://artifactory.nordix.org/artifactory/liquibase</url>
+ </repository>
+ </repositories>
+
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
@@ -78,6 +86,7 @@
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
+ <version>4.4.2-nordix</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
diff --git a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsDataPersistenceServiceImpl.java b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsDataPersistenceServiceImpl.java
index 844ad8474..fdbafd4be 100644
--- a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsDataPersistenceServiceImpl.java
+++ b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsDataPersistenceServiceImpl.java
@@ -37,36 +37,49 @@ import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
+import lombok.extern.slf4j.Slf4j;
+import org.hibernate.StaleStateException;
import org.onap.cps.cpspath.parser.CpsPathQuery;
-import org.onap.cps.cpspath.parser.CpsPathQueryType;
import org.onap.cps.spi.CpsDataPersistenceService;
import org.onap.cps.spi.FetchDescendantsOption;
import org.onap.cps.spi.entities.AnchorEntity;
import org.onap.cps.spi.entities.DataspaceEntity;
import org.onap.cps.spi.entities.FragmentEntity;
import org.onap.cps.spi.exceptions.AlreadyDefinedException;
+import org.onap.cps.spi.exceptions.ConcurrencyException;
import org.onap.cps.spi.exceptions.CpsPathException;
import org.onap.cps.spi.model.DataNode;
import org.onap.cps.spi.model.DataNodeBuilder;
import org.onap.cps.spi.repository.AnchorRepository;
import org.onap.cps.spi.repository.DataspaceRepository;
import org.onap.cps.spi.repository.FragmentRepository;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
@Service
+@Slf4j
public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService {
- @Autowired
private DataspaceRepository dataspaceRepository;
- @Autowired
private AnchorRepository anchorRepository;
- @Autowired
private FragmentRepository fragmentRepository;
+ /**
+ * Constructor.
+ *
+ * @param dataspaceRepository dataspaceRepository
+ * @param anchorRepository anchorRepository
+ * @param fragmentRepository fragmentRepository
+ */
+ public CpsDataPersistenceServiceImpl(final DataspaceRepository dataspaceRepository,
+ final AnchorRepository anchorRepository, final FragmentRepository fragmentRepository) {
+ this.dataspaceRepository = dataspaceRepository;
+ this.anchorRepository = anchorRepository;
+ this.fragmentRepository = fragmentRepository;
+ }
+
private static final Gson GSON = new GsonBuilder().create();
private static final String REG_EX_FOR_OPTIONAL_LIST_INDEX = "(\\[@\\S+?]){0,1})";
@@ -179,20 +192,8 @@ public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService
} catch (final IllegalStateException e) {
throw new CpsPathException(e.getMessage());
}
- List<FragmentEntity> fragmentEntities;
- if (CpsPathQueryType.XPATH_LEAF_VALUE.equals(cpsPathQuery.getCpsPathQueryType())) {
- fragmentEntities = fragmentRepository
- .getByAnchorAndXpathAndLeafAttributes(anchorEntity.getId(), cpsPathQuery.getXpathPrefix(),
- cpsPathQuery.getLeafName(), cpsPathQuery.getLeafValue());
- } else if (CpsPathQueryType.XPATH_HAS_DESCENDANT_WITH_LEAF_VALUES.equals(cpsPathQuery.getCpsPathQueryType())) {
- final String leafDataAsJson = GSON.toJson(cpsPathQuery.getLeavesData());
- fragmentEntities = fragmentRepository
- .getByAnchorAndDescendentNameAndLeafValues(anchorEntity.getId(), cpsPathQuery.getDescendantName(),
- leafDataAsJson);
- } else {
- fragmentEntities = fragmentRepository
- .getByAnchorAndXpathEndsInDescendantName(anchorEntity.getId(), cpsPathQuery.getDescendantName());
- }
+ List<FragmentEntity> fragmentEntities =
+ fragmentRepository.findByAnchorAndCpsPath(anchorEntity.getId(), cpsPathQuery);
if (cpsPathQuery.hasAncestorAxis()) {
final Set<String> ancestorXpaths = processAncestorXpath(fragmentEntities, cpsPathQuery);
fragmentEntities = ancestorXpaths.isEmpty()
@@ -247,18 +248,41 @@ public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService
}
@Override
- public void replaceDataNodeTree(final String dataspaceName, final String anchorName, final DataNode dataNode) {
+ public void replaceDataNodeTree(final String dataspaceName, final String anchorName,
+ final DataNode dataNode) {
final var fragmentEntity = getFragmentByXpath(dataspaceName, anchorName, dataNode.getXpath());
- removeExistingDescendants(fragmentEntity);
+ replaceDataNodeTree(fragmentEntity, dataNode);
+ try {
+ fragmentRepository.save(fragmentEntity);
+ } catch (final StaleStateException staleStateException) {
+ throw new ConcurrencyException("Concurrent Transactions",
+ String.format("dataspace :'%s', Anchor : '%s' and xpath: '%s' is updated by another transaction.",
+ dataspaceName, anchorName, dataNode.getXpath()),
+ staleStateException);
+ }
+ }
- fragmentEntity.setAttributes(GSON.toJson(dataNode.getLeaves()));
- final Set<FragmentEntity> childFragmentEntities = dataNode.getChildDataNodes().stream().map(
- childDataNode -> convertToFragmentWithAllDescendants(
- fragmentEntity.getDataspace(), fragmentEntity.getAnchor(), childDataNode)
- ).collect(Collectors.toUnmodifiableSet());
- fragmentEntity.setChildFragments(childFragmentEntities);
+ private void replaceDataNodeTree(final FragmentEntity existingFragmentEntity, final DataNode submittedDataNode) {
- fragmentRepository.save(fragmentEntity);
+ existingFragmentEntity.setAttributes(GSON.toJson(submittedDataNode.getLeaves()));
+
+ final Map<String, FragmentEntity> existingChildrenByXpath = existingFragmentEntity.getChildFragments()
+ .stream().collect(Collectors.toMap(FragmentEntity::getXpath, childFragmentEntity -> childFragmentEntity));
+
+ final var updatedChildFragments = new HashSet<FragmentEntity>();
+
+ for (final DataNode submittedChildDataNode : submittedDataNode.getChildDataNodes()) {
+ final FragmentEntity childFragment;
+ if (existingChildrenByXpath.containsKey(submittedChildDataNode.getXpath())) {
+ childFragment = existingChildrenByXpath.get(submittedChildDataNode.getXpath());
+ replaceDataNodeTree(childFragment, submittedChildDataNode);
+ } else {
+ childFragment = convertToFragmentWithAllDescendants(
+ existingFragmentEntity.getDataspace(), existingFragmentEntity.getAnchor(), submittedChildDataNode);
+ }
+ updatedChildFragments.add(childFragment);
+ }
+ existingFragmentEntity.setChildFragments(updatedChildFragments);
}
@Override
@@ -285,11 +309,6 @@ public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService
}
}
- private void removeExistingDescendants(final FragmentEntity fragmentEntity) {
- fragmentEntity.setChildFragments(Collections.emptySet());
- fragmentRepository.save(fragmentEntity);
- }
-
private static boolean isRootXpath(final String xpath) {
return "/".equals(xpath) || "".equals(xpath);
}
diff --git a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java
index 972807b72..1b3dc2486 100755
--- a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java
+++ b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java
@@ -29,7 +29,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
@@ -186,7 +185,7 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
*/
private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
String checksum = null;
- final Matcher matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
+ final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
if (matcher.find() && matcher.groupCount() == 1) {
checksum = matcher.group(1);
}
diff --git a/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepository.java b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepository.java
index 4d7e7ff54..c48c79ef6 100755
--- a/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepository.java
+++ b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepository.java
@@ -1,6 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2020-201 Nordix Foundation.
+ * Copyright (C) 2020-2021 Nordix Foundation.
* Modifications Copyright (C) 2020-2021 Bell Canada.
* Modifications Copyright (C) 2020-2021 Pantheon.tech.
* ================================================================================
@@ -38,13 +38,15 @@ import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
-public interface FragmentRepository extends JpaRepository<FragmentEntity, Long> {
+public interface FragmentRepository extends JpaRepository<FragmentEntity, Long>, FragmentRepositoryCpsPathQuery {
Optional<FragmentEntity> findByDataspaceAndAnchorAndXpath(@NonNull DataspaceEntity dataspaceEntity,
- @NonNull AnchorEntity anchorEntity, @NonNull String xpath);
+ @NonNull AnchorEntity anchorEntity,
+ @NonNull String xpath);
default FragmentEntity getByDataspaceAndAnchorAndXpath(@NonNull DataspaceEntity dataspaceEntity,
- @NonNull AnchorEntity anchorEntity, @NonNull String xpath) {
+ @NonNull AnchorEntity anchorEntity,
+ @NonNull String xpath) {
return findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, xpath)
.orElseThrow(() -> new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName(), xpath));
}
@@ -52,42 +54,19 @@ public interface FragmentRepository extends JpaRepository<FragmentEntity, Long>
@Query(
value = "SELECT * FROM FRAGMENT WHERE anchor_id = :anchor AND dataspace_id = :dataspace AND parent_id is NULL",
nativeQuery = true)
- List<FragmentEntity> findRootsByDataspaceAndAnchor(
- @Param("dataspace") int dataspaceId, @Param("anchor") int anchorId);
+ List<FragmentEntity> findRootsByDataspaceAndAnchor(@Param("dataspace") int dataspaceId,
+ @Param("anchor") int anchorId);
default FragmentEntity findFirstRootByDataspaceAndAnchor(@NonNull DataspaceEntity dataspaceEntity,
- @NonNull AnchorEntity anchorEntity) {
+ @NonNull AnchorEntity anchorEntity) {
return findRootsByDataspaceAndAnchor(dataspaceEntity.getId(), anchorEntity.getId()).stream().findFirst()
.orElseThrow(() -> new DataNodeNotFoundException(dataspaceEntity.getName(), anchorEntity.getName()));
}
List<FragmentEntity> findAllByAnchorAndXpathIn(@NonNull AnchorEntity anchorEntity,
- @NonNull Collection<String> xpath);
+ @NonNull Collection<String> xpath);
@Modifying
@Query("DELETE FROM FragmentEntity fe WHERE fe.anchor IN (:anchors)")
void deleteByAnchorIn(@NotNull @Param("anchors") Collection<AnchorEntity> anchorEntities);
-
- @Query(value =
- "SELECT * FROM FRAGMENT WHERE (anchor_id = :anchor) AND (xpath = (:xpath) OR xpath LIKE "
- + "CONCAT(:xpath,'\\[@%]')) AND attributes @> jsonb_build_object(:leafName , :leafValue)",
- nativeQuery = true)
- // Above query will match an xpath with or without the index for a list [@key=value] and match anchor id,
- // leaf name and leaf value
- List<FragmentEntity> getByAnchorAndXpathAndLeafAttributes(@Param("anchor") int anchorId, @Param("xpath")
- String xpathPrefix, @Param("leafName") String leafName, @Param("leafValue") Object leafValue);
-
- @Query(value = "SELECT * FROM FRAGMENT WHERE anchor_id = :anchor AND xpath LIKE CONCAT('%/',:descendantName)",
- nativeQuery = true)
- // Above query will match the anchor id and last descendant name
- List<FragmentEntity> getByAnchorAndXpathEndsInDescendantName(@Param("anchor") int anchorId,
- @Param("descendantName") String descendantName);
-
- @Query(value = "SELECT * FROM FRAGMENT WHERE anchor_id = :anchor AND (xpath LIKE CONCAT('%/',:descendantName) OR "
- + "xpath LIKE CONCAT('%/', :descendantName,'\\[@%]')) AND attributes @> :leafDataAsJson\\:\\:jsonb",
- nativeQuery = true)
- // Above query will match the anchor id, last descendant name and all parameters passed into leafDataASJson with the
- // attribute values of the requested data node eg: {"leaf_name":"value", "another_leaf_name":"another value"}​​​​​​
- List<FragmentEntity> getByAnchorAndDescendentNameAndLeafValues(@Param("anchor") int anchorId,
- @Param("descendantName") String descendantName, @Param("leafDataAsJson") String leafDataAsJson);
}
diff --git a/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQuery.java b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQuery.java
new file mode 100644
index 000000000..04138ecc6
--- /dev/null
+++ b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQuery.java
@@ -0,0 +1,29 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.spi.repository;
+
+import java.util.List;
+import org.onap.cps.cpspath.parser.CpsPathQuery;
+import org.onap.cps.spi.entities.FragmentEntity;
+
+public interface FragmentRepositoryCpsPathQuery {
+ List<FragmentEntity> findByAnchorAndCpsPath(int anchorId, CpsPathQuery cpsPathQuery);
+}
diff --git a/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQueryImpl.java b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQueryImpl.java
new file mode 100644
index 000000000..4aa3e5fb3
--- /dev/null
+++ b/cps-ri/src/main/java/org/onap/cps/spi/repository/FragmentRepositoryCpsPathQueryImpl.java
@@ -0,0 +1,120 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.spi.repository;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.onap.cps.cpspath.parser.CpsPathPrefixType;
+import org.onap.cps.cpspath.parser.CpsPathQuery;
+import org.onap.cps.spi.entities.FragmentEntity;
+
+public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCpsPathQuery {
+
+ public static final String SIMILAR_TO_ABSOLUTE_PATH_PREFIX = "%/";
+ public static final String SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[[^/]*])?";
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ private static final Gson GSON = new GsonBuilder().create();
+
+ @Override
+ public List<FragmentEntity> findByAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
+ final var sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
+ final Map<String, Object> queryParameters = new HashMap<>();
+ queryParameters.put("anchorId", anchorId);
+ sqlStringBuilder.append(" AND xpath SIMILAR TO :xpathRegex");
+ final String xpathRegex = getSimilarToXpathSqlRegex(cpsPathQuery);
+ queryParameters.put("xpathRegex", xpathRegex);
+ if (cpsPathQuery.hasLeafConditions()) {
+ sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
+ queryParameters.put("leafDataAsJson", GSON.toJson(cpsPathQuery.getLeavesData()));
+ }
+
+ addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
+ final var query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
+ setQueryParameters(query, queryParameters);
+ return query.getResultList();
+ }
+
+ @NotNull
+ private static String getSimilarToXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
+ final var xpathRegexBuilder = new StringBuilder();
+ if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
+ xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
+ } else {
+ xpathRegexBuilder.append(SIMILAR_TO_ABSOLUTE_PATH_PREFIX);
+ xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
+ }
+ xpathRegexBuilder.append(SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX);
+ return xpathRegexBuilder.toString();
+ }
+
+ @NotNull
+ private static String escapeXpath(final String xpath) {
+ // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
+ return xpath.replace("[@", "\\[@");
+ }
+
+ @Nullable
+ private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
+ try {
+ return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
+ } catch (final NumberFormatException e) {
+ return null;
+ }
+ }
+
+ private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
+ final Map<String, Object> queryParameters) {
+ if (cpsPathQuery.hasTextFunctionCondition()) {
+ sqlStringBuilder.append(" AND (");
+ sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
+ sqlStringBuilder
+ .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
+ queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
+ queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
+ final var textValueAsInt = getTextValueAsInt(cpsPathQuery);
+ if (textValueAsInt != null) {
+ sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
+ sqlStringBuilder
+ .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
+ queryParameters.put("textValueAsInt", textValueAsInt);
+ }
+ sqlStringBuilder.append(")");
+ }
+ }
+
+ private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
+ for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
+ query.setParameter(queryParameter.getKey(), queryParameter.getValue());
+ }
+ }
+
+}
diff --git a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceQueryDataNodeSpec.groovy b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceQueryDataNodeSpec.groovy
index 8dc9b7f3c..ae88d302b 100644
--- a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceQueryDataNodeSpec.groovy
+++ b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceQueryDataNodeSpec.groovy
@@ -23,7 +23,6 @@ package org.onap.cps.spi.impl
import org.onap.cps.spi.CpsDataPersistenceService
import org.onap.cps.spi.exceptions.CpsPathException
-import org.onap.cps.spi.model.DataNode
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.jdbc.Sql
@@ -38,23 +37,25 @@ class CpsDataPersistenceQueryDataNodeSpec extends CpsPersistenceSpecBase {
static final String SET_DATA = '/data/cps-path-query.sql'
@Sql([CLEAR_DATA, SET_DATA])
- def 'Cps Path query for single leaf value with type: #type.'() {
+ def 'Cps Path query for leaf value(s) with : #scenario.'() {
when: 'a query is executed to get a data node by the given cps path'
def result = objectUnderTest.queryDataNodes(DATASPACE_NAME, ANCHOR_FOR_SHOP_EXAMPLE, cpsPath, includeDescendantsOption)
+ then: 'the correct number of parent nodes are returned'
+ result.size() == expectedNumberOfParentNodes
then: 'the correct data is returned'
- def leaves = '[price:15.0, title:Dune]'
- DataNode dataNode = result.stream().findFirst().get()
- dataNode.getLeaves().toString() == leaves
- dataNode.getChildDataNodes().size() == expectedNumberOfChidlNodes
+ result.each {
+ assert it.getChildDataNodes().size() == expectedNumberOfChildNodes
+ }
where: 'the following data is used'
- type | cpsPath | includeDescendantsOption || expectedNumberOfChidlNodes
- 'String and no descendants' | '/shops/shop[@id=1]/categories[@code=1]/book[@title="Dune"]' | OMIT_DESCENDANTS || 0
- 'Integer and descendants' | '/shops/shop[@id=1]/categories[@code=1]/book[@price=15]' | INCLUDE_ALL_DESCENDANTS || 1
+ scenario | cpsPath | includeDescendantsOption || expectedNumberOfParentNodes | expectedNumberOfChildNodes
+ 'String and no descendants' | '/shops/shop[@id=1]/categories[@code=1]/book[@title="Dune"]' | OMIT_DESCENDANTS || 1 | 0
+ 'Integer and descendants' | '/shops/shop[@id=1]/categories[@code=1]/book[@price=5]' | INCLUDE_ALL_DESCENDANTS || 1 | 1
+ 'No condition no descendants' | '/shops/shop[@id=1]/categories' | OMIT_DESCENDANTS || 2 | 0
}
@Sql([CLEAR_DATA, SET_DATA])
def 'Query for attribute by cps path with cps paths that return no data because of #scenario.'() {
- when: 'a query is executed to get datanodes for the given cps path'
+ when: 'a query is executed to get data nodes for the given cps path'
def result = objectUnderTest.queryDataNodes(DATASPACE_NAME, ANCHOR_FOR_SHOP_EXAMPLE, cpsPath, OMIT_DESCENDANTS)
then: 'no data is returned'
result.isEmpty()
@@ -71,7 +72,7 @@ class CpsDataPersistenceQueryDataNodeSpec extends CpsPersistenceSpecBase {
def cpsPath = '//categories[@code=1]'
def result = objectUnderTest.queryDataNodes(DATASPACE_NAME, ANCHOR_FOR_SHOP_EXAMPLE, cpsPath, includeDescendantsOption)
then: 'the data node has the correct number of children'
- DataNode dataNode = result.stream().findFirst().get()
+ def dataNode = result.stream().findFirst().get()
dataNode.getChildDataNodes().size() == expectedNumberOfChildNodes
where: 'the following data is used'
type | includeDescendantsOption || expectedNumberOfChildNodes
@@ -90,9 +91,16 @@ class CpsDataPersistenceQueryDataNodeSpec extends CpsPersistenceSpecBase {
assert result[i].getXpath() == expectedXPaths[i]
}
where: 'the following data is used'
- scenario | cpsPath || expectedXPaths
- 'fully unique descendant name' | '//categories[@code=2]' || ['/shops/shop[@id=1]/categories[@code=2]', '/shops/shop[@id=2]/categories[@code=1]', '/shops/shop[@id=2]/categories[@code=2]']
- 'descendant name match end of other node' | '//book' || ['/shops/shop[@id=1]/categories[@code=1]/book', '/shops/shop[@id=1]/categories[@code=2]/book']
+ scenario | cpsPath || expectedXPaths
+ 'fully unique descendant name' | '//categories[@code=2]' || ['/shops/shop[@id=1]/categories[@code=2]', '/shops/shop[@id=2]/categories[@code=1]', '/shops/shop[@id=2]/categories[@code=2]']
+ 'descendant name match end of other node' | '//book' || ['/shops/shop[@id=1]/categories[@code=1]/book', '/shops/shop[@id=1]/categories[@code=2]/book']
+ 'descendant with text condition on leaf' | '//book/title[text()="Chapters"]' || ['/shops/shop[@id=1]/categories[@code=2]/book']
+ 'descendant with text condition case mismatch' | '//book/title[text()="chapters"]' || []
+ 'descendant with text condition on int leaf' | '//book/price[text()="5"]' || ['/shops/shop[@id=1]/categories[@code=1]/book']
+ 'descendant with text condition on leaf-list' | '//book/labels[text()="special offer"]' || ['/shops/shop[@id=1]/categories[@code=1]/book']
+ 'descendant with text condition partial match' | '//book/labels[text()="special"]' || []
+ 'descendant with text condition (existing) empty string' | '//book/labels[text()=""]' || ['/shops/shop[@id=1]/categories[@code=1]/book']
+ 'descendant with text condition on int leaf-list' | '//book/editions[text()="2000"]' || ['/shops/shop[@id=1]/categories[@code=2]/book']
}
@Sql([CLEAR_DATA, SET_DATA])
@@ -106,10 +114,11 @@ class CpsDataPersistenceQueryDataNodeSpec extends CpsPersistenceSpecBase {
assert result[i].getXpath() == expectedXPaths[i]
}
where: 'the following data is used'
- scenario | cpsPath || expectedXPaths
- 'one leaf' | '//author[@FirstName="Joe"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]', '/shops/shop[@id=1]/categories[@code=2]/book/author[@FirstName="Joe" and @Surname="Smith"]']
- 'more than one leaf' | '//author[@FirstName="Joe" and @Surname="Bloggs"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]']
- 'leaves reversed in order' | '//author[@Surname="Bloggs" and @FirstName="Joe"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]']
+ scenario | cpsPath || expectedXPaths
+ 'one leaf' | '//author[@FirstName="Joe"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]', '/shops/shop[@id=1]/categories[@code=2]/book/author[@FirstName="Joe" and @Surname="Smith"]']
+ 'more than one leaf' | '//author[@FirstName="Joe" and @Surname="Bloggs"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]']
+ 'leaves reversed in order' | '//author[@Surname="Bloggs" and @FirstName="Joe"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]']
+ 'leaf and text condition' | '//author[@FirstName="Joe"]/Surname[text()="Bloggs"]' || ['/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]']
}
@Sql([CLEAR_DATA, SET_DATA])
@@ -146,6 +155,7 @@ class CpsDataPersistenceQueryDataNodeSpec extends CpsPersistenceSpecBase {
'list with index value in the xpath prefix' | '//categories[@code=1]/book/ancestor::shop[@id=1]' || ['/shops/shop[@id=1]']
'ancestor with parent list' | '//book/ancestor::shop[@id=1]/categories[@code=2]' || ['/shops/shop[@id=1]/categories[@code=2]']
'ancestor with parent' | '//phonenumbers[@type="mob"]/ancestor::info/contact' || ['/shops/shop[@id=3]/info/contact']
+ 'ancestor combined with text condition' | '//book/title[text()="Dune"]/ancestor::shop' || ['/shops/shop[@id=1]']
'ancestor with parent that does not exist' | '//book/ancestor::parentDoesNoExist/categories' || []
'ancestor does not exist' | '//book/ancestor::ancestorDoesNotExist' || []
}
diff --git a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceIntegrationSpec.groovy b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceIntegrationSpec.groovy
new file mode 100755
index 000000000..ad8db766f
--- /dev/null
+++ b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceIntegrationSpec.groovy
@@ -0,0 +1,436 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation
+ * Modifications Copyright (C) 2021 Pantheon.tech
+ * Modifications Copyright (C) 2021 Bell Canada.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.cps.spi.impl
+
+import org.onap.cps.spi.exceptions.ConcurrencyException
+
+import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
+import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
+
+import com.google.common.collect.ImmutableSet
+import com.google.gson.Gson
+import com.google.gson.GsonBuilder
+import org.onap.cps.spi.CpsDataPersistenceService
+import org.onap.cps.spi.entities.FragmentEntity
+import org.onap.cps.spi.exceptions.AlreadyDefinedException
+import org.onap.cps.spi.exceptions.AnchorNotFoundException
+import org.onap.cps.spi.exceptions.DataNodeNotFoundException
+import org.onap.cps.spi.exceptions.DataspaceNotFoundException
+import org.onap.cps.spi.model.DataNode
+import org.onap.cps.spi.model.DataNodeBuilder
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.test.context.jdbc.Sql
+
+import javax.validation.ConstraintViolationException
+
+class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
+
+ @Autowired
+ CpsDataPersistenceService objectUnderTest
+
+ static final Gson GSON = new GsonBuilder().create()
+
+ static final String SET_DATA = '/data/fragment.sql'
+ static final long ID_DATA_NODE_WITH_DESCENDANTS = 4001
+ static final String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
+ static final String XPATH_DATA_NODE_WITH_LEAVES = '/parent-100'
+ static final long UPDATE_DATA_NODE_FRAGMENT_ID = 4202L
+ static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L
+ static final long LIST_DATA_NODE_PARENT_FRAGMENT_ID = 4206L
+
+ static final DataNode newDataNode = new DataNodeBuilder().build()
+ static DataNode existingDataNode
+ static DataNode existingChildDataNode
+
+ def expectedLeavesByXpathMap = [
+ '/parent-100' : ['parent-leaf': 'parent-leaf value'],
+ '/parent-100/child-001' : ['first-child-leaf': 'first-child-leaf value'],
+ '/parent-100/child-002' : ['second-child-leaf': 'second-child-leaf value'],
+ '/parent-100/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
+ ]
+
+ static {
+ existingDataNode = createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)
+ existingChildDataNode = createDataNodeTree('/parent-1/child-1')
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'StoreDataNode with descendants.'() {
+ when: 'a fragment with descendants is stored'
+ def parentXpath = "/parent-new"
+ def childXpath = "/parent-new/child-new"
+ def grandChildXpath = "/parent-new/child-new/grandchild-new"
+ objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1,
+ createDataNodeTree(parentXpath, childXpath, grandChildXpath))
+ then: 'it can be retrieved by its xpath'
+ def parentFragment = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, parentXpath)
+ and: 'it contains the children'
+ parentFragment.childFragments.size() == 1
+ def childFragment = parentFragment.childFragments[0]
+ childFragment.xpath == childXpath
+ and: "and its children's children"
+ childFragment.childFragments.size() == 1
+ def grandchildFragment = childFragment.childFragments[0]
+ grandchildFragment.xpath == grandChildXpath
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Store data node for multiple anchors using the same schema.'() {
+ def xpath = "/parent-new"
+ given: 'a fragment is stored for an anchor'
+ objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1, createDataNodeTree(xpath))
+ when: 'another fragment is stored for an other anchor, using the same schema set'
+ objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME3, createDataNodeTree(xpath))
+ then: 'both fragments can be retrieved by their xpath'
+ def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
+ fragment1.anchor.name == ANCHOR_NAME1
+ fragment1.xpath == xpath
+ def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
+ fragment2.anchor.name == ANCHOR_NAME3
+ fragment2.xpath == xpath
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Store datanode error scenario: #scenario.'() {
+ when: 'attempt to store a data node with #scenario'
+ objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'the following data is used'
+ scenario | dataspaceName | anchorName | dataNode || expectedException
+ 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNode || DataspaceNotFoundException
+ 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNode || AnchorNotFoundException
+ 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNode || ConstraintViolationException
+ 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNode || AlreadyDefinedException
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Add a child to a Fragment that already has a child.'() {
+ given: ' a new child node'
+ def newChild = createDataNodeTree('xpath for new child')
+ when: 'the child is added to an existing parent with 1 child'
+ objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
+ then: 'the parent is now has to 2 children'
+ def expectedExistingChildPath = '/parent-1/child-1'
+ def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
+ parentFragment.getChildFragments().size() == 2
+ and: 'it still has the old child'
+ parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
+ and: 'it has the new child'
+ parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Add child error scenario: #scenario.'() {
+ when: 'attempt to add a child data node with #scenario'
+ objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'the following data is used'
+ scenario | parentXpath | dataNode || expectedException
+ 'parent does not exist' | 'unknown' | newDataNode || DataNodeNotFoundException
+ 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || AlreadyDefinedException
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Add list-node fragment with multiple elements.'() {
+ given: 'list node data fragment as a collection of data nodes'
+ def listNodeXpaths = ['/parent-201/child-204[@key="B"]', '/parent-201/child-204[@key="C"]']
+ def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
+ when: 'list-node elements added to existing parent node'
+ objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
+ then: 'new entries successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
+ def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
+ def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
+ assert allChildXpaths.size() == 5
+ assert allChildXpaths.containsAll(listNodeXpaths)
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Add list-node fragment error scenario: #scenario.'() {
+ given: 'list node data fragment as a collection of data nodes'
+ def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
+ when: 'list-node elements added to existing parent node'
+ objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'following parameters were used'
+ scenario | parentNodeXpath | listNodeXpaths || expectedException
+ 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
+ 'already existing fragment' | '/parent-201' | ['/parent-201/child-204[@key="A"]'] || AlreadyDefinedException
+
+ }
+
+ static def createDataNodeTree(String... xpaths) {
+ def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
+ if (xpaths.length > 1) {
+ def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
+ def childDataNode = createDataNodeTree(xPathsDescendant)
+ dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
+ }
+ dataNodeBuilder.build()
+ }
+
+ def getFragmentByXpath(dataspaceName, anchorName, xpath) {
+ def dataspace = dataspaceRepository.getByName(dataspaceName)
+ def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
+ return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Get data node by xpath without descendants.'() {
+ when: 'data node is requested'
+ def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
+ inputXPath, OMIT_DESCENDANTS)
+ then: 'data node is returned with no descendants'
+ assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
+ and: 'expected leaves'
+ assert result.getChildDataNodes().size() == 0
+ assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
+ where: 'the following data is used'
+ scenario | inputXPath
+ 'some xpath' | '/parent-100'
+ 'root xpath' | '/'
+ 'empty xpath' | ''
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Get data node by xpath with all descendants.'() {
+ when: 'data node is requested with all descendants'
+ def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
+ inputXPath, INCLUDE_ALL_DESCENDANTS)
+ def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
+ then: 'data node is returned with all the descendants populated'
+ assert mappedResult.size() == 4
+ assert result.getChildDataNodes().size() == 2
+ assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
+ assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
+ and: 'extracted leaves maps are matching expected'
+ mappedResult.forEach(
+ (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath]))
+ where: 'the following data is used'
+ scenario | inputXPath
+ 'some xpath' | '/parent-100'
+ 'root xpath' | '/'
+ 'empty xpath' | ''
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Get data node error scenario: #scenario.'() {
+ when: 'attempt to get data node with #scenario'
+ objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'the following data is used'
+ scenario | dataspaceName | anchorName | xpath || expectedException
+ 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
+ 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
+ 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH' || DataNodeNotFoundException
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Update data node leaves.'() {
+ when: 'update is performed for leaves'
+ objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
+ "/parent-200/child-201", ['leaf-value': 'new'])
+ then: 'leaves are updated for selected data node'
+ def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
+ def updatedLeaves = getLeavesMap(updatedFragment)
+ assert updatedLeaves.size() == 1
+ assert updatedLeaves.'leaf-value' == 'new'
+ and: 'existing child entry remains as is'
+ def childFragment = updatedFragment.getChildFragments().iterator().next()
+ def childLeaves = getLeavesMap(childFragment)
+ assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
+ assert childLeaves.'leaf-value' == 'original'
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Update data leaves error scenario: #scenario.'() {
+ when: 'attempt to update data node for #scenario'
+ objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'the following data is used'
+ scenario | dataspaceName | anchorName | xpath || expectedException
+ 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
+ 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
+ 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace data node tree with descendants removal.'() {
+ given: 'data node object with leaves updated, no children'
+ def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
+ when: 'replace data node tree is performed'
+ objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
+ then: 'leaves have been updated for selected data node'
+ def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
+ def updatedLeaves = getLeavesMap(updatedFragment)
+ assert updatedLeaves.size() == 1
+ assert updatedLeaves.'leaf-value' == 'new'
+ and: 'updated entry has no children'
+ updatedFragment.getChildFragments().isEmpty()
+ and: 'previously attached child entry is removed from database'
+ fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace data node tree with descendants.'() {
+ given: 'data node object with leaves updated, having child with old content'
+ def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
+ buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
+ ])
+ when: 'update is performed including descendants'
+ objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
+ then: 'leaves have been updated for selected data node'
+ def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
+ def updatedLeaves = getLeavesMap(updatedFragment)
+ assert updatedLeaves.size() == 1
+ assert updatedLeaves.'leaf-value' == 'new'
+ and: 'existing child entry is not updated as content is same'
+ def childFragment = updatedFragment.getChildFragments().iterator().next()
+ childFragment.getXpath() == '/parent-200/child-201/grand-child'
+ def childLeaves = getLeavesMap(childFragment)
+ assert childLeaves.'leaf-value' == 'original'
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace data node tree with same descendants but changed leaf value.'() {
+ given: 'data node object with leaves updated, having child with old content'
+ def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
+ buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'new'], [])
+ ])
+ when: 'update is performed including descendants'
+ objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
+ then: 'leaves have been updated for selected data node'
+ def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
+ def updatedLeaves = getLeavesMap(updatedFragment)
+ assert updatedLeaves.size() == 1
+ assert updatedLeaves.'leaf-value' == 'new'
+ and: 'existing child entry is updated with the new content'
+ def childFragment = updatedFragment.getChildFragments().iterator().next()
+ childFragment.getXpath() == '/parent-200/child-201/grand-child'
+ def childLeaves = getLeavesMap(childFragment)
+ assert childLeaves.'leaf-value' == 'new'
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace data node tree with different descendants xpath'() {
+ given: 'data node object with leaves updated, having child with old content'
+ def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
+ buildDataNode("/parent-200/child-201/grand-child-new", ['leaf-value': 'new'], [])
+ ])
+ when: 'update is performed including descendants'
+ objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
+ then: 'leaves have been updated for selected data node'
+ def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
+ def updatedLeaves = getLeavesMap(updatedFragment)
+ assert updatedLeaves.size() == 1
+ assert updatedLeaves.'leaf-value' == 'new'
+ and: 'previously attached child entry is removed from database'
+ fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
+ and: 'new child entry is persisted'
+ def childFragment = updatedFragment.getChildFragments().iterator().next()
+ childFragment.getXpath() == '/parent-200/child-201/grand-child-new'
+ def childLeaves = getLeavesMap(childFragment)
+ assert childLeaves.'leaf-value' == 'new'
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace data node tree error scenario: #scenario.'() {
+ given: 'data node object'
+ def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
+ when: 'attempt to update data node for #scenario'
+ objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'the following data is used'
+ scenario | dataspaceName | anchorName | xpath || expectedException
+ 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
+ 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
+ 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace list-node content of #scenario.'() {
+ given: 'list node data fragment as a collection of data nodes'
+ def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
+ when: 'list-node elements replaced within the existing parent node'
+ objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
+ then: 'child list elements are updated as expected, non-list element remains as is'
+ def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
+ def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
+ assert allChildXpaths.size() == expectedChildXpaths.size()
+ assert allChildXpaths.containsAll(expectedChildXpaths)
+ where: 'following parameters were used'
+ scenario | listNodeXpaths || expectedChildXpaths
+ 'existing list-node' | ['/parent-201/child-204[@key="B"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="B"]']
+ 'non-existing list-node' | ['/parent-201/child-205[@key="1"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="A"]', '/parent-201/child-204[@key="X"]', '/parent-201/child-205[@key="1"]']
+ }
+
+ @Sql([CLEAR_DATA, SET_DATA])
+ def 'Replace list-node fragment error scenario: #scenario.'() {
+ given: 'list node data fragment as a collection of data nodes'
+ def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
+ when: 'list-node elements were replaced under existing parent node'
+ objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
+ then: 'a #expectedException is thrown'
+ thrown(expectedException)
+ where: 'following parameters were used'
+ scenario | parentNodeXpath | listNodeXpaths || expectedException
+ 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
+ }
+
+ static Collection<DataNode> buildDataNodeCollection(xpaths) {
+ return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
+ }
+
+ static DataNode buildDataNode(xpath, leaves, childDataNodes) {
+ return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
+ }
+
+ static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
+ return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
+ }
+
+ def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
+ expectedLeavesMap.forEach((key, value) -> {
+ def actualValue = actualLeavesMap[key]
+ if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
+ assert value.size() == actualValue.size()
+ assert value.containsAll(actualValue)
+ } else {
+ assert value == actualValue
+ }
+ })
+ return true
+ }
+
+ def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
+ flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
+ dataNodeTree.getChildDataNodes()
+ .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
+ return flatMap
+ }
+
+}
diff --git a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceSpec.groovy b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceSpec.groovy
index 0ad67d541..5ed3ae3e8 100755..100644
--- a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceSpec.groovy
+++ b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsDataPersistenceServiceSpec.groovy
@@ -1,394 +1,72 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation
- * Modifications Copyright (C) 2021 Pantheon.tech
- * Modifications Copyright (C) 2021 Bell Canada.
- * ================================================================================
- * 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
+ * ============LICENSE_START=======================================================
+ * Copyright (c) 2021 Bell Canada.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-package org.onap.cps.spi.impl
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+*/
-import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
-import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
+package org.onap.cps.spi.impl
-import com.google.common.collect.ImmutableSet
-import com.google.gson.Gson
-import com.google.gson.GsonBuilder
-import org.onap.cps.spi.CpsDataPersistenceService
+import org.hibernate.StaleStateException
import org.onap.cps.spi.entities.FragmentEntity
-import org.onap.cps.spi.exceptions.AlreadyDefinedException
-import org.onap.cps.spi.exceptions.AnchorNotFoundException
-import org.onap.cps.spi.exceptions.DataNodeNotFoundException
-import org.onap.cps.spi.exceptions.DataspaceNotFoundException
-import org.onap.cps.spi.model.DataNode
+import org.onap.cps.spi.exceptions.ConcurrencyException
import org.onap.cps.spi.model.DataNodeBuilder
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.test.context.jdbc.Sql
-
-import javax.validation.ConstraintViolationException
-
-class CpsDataPersistenceServiceSpec extends CpsPersistenceSpecBase {
-
- @Autowired
- CpsDataPersistenceService objectUnderTest
-
- static final Gson GSON = new GsonBuilder().create()
-
- static final String SET_DATA = '/data/fragment.sql'
- static final long ID_DATA_NODE_WITH_DESCENDANTS = 4001
- static final String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
- static final String XPATH_DATA_NODE_WITH_LEAVES = '/parent-100'
- static final long UPDATE_DATA_NODE_FRAGMENT_ID = 4202L
- static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L
- static final long LIST_DATA_NODE_PARENT_FRAGMENT_ID = 4206L
-
- static final DataNode newDataNode = new DataNodeBuilder().build()
- static DataNode existingDataNode
- static DataNode existingChildDataNode
-
- def expectedLeavesByXpathMap = [
- '/parent-100' : ['parent-leaf': 'parent-leaf value'],
- '/parent-100/child-001' : ['first-child-leaf': 'first-child-leaf value'],
- '/parent-100/child-002' : ['second-child-leaf': 'second-child-leaf value'],
- '/parent-100/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
- ]
-
- static {
- existingDataNode = createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)
- existingChildDataNode = createDataNodeTree('/parent-1/child-1')
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'StoreDataNode with descendants.'() {
- when: 'a fragment with descendants is stored'
- def parentXpath = "/parent-new"
- def childXpath = "/parent-new/child-new"
- def grandChildXpath = "/parent-new/child-new/grandchild-new"
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1,
- createDataNodeTree(parentXpath, childXpath, grandChildXpath))
- then: 'it can be retrieved by its xpath'
- def parentFragment = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, parentXpath)
- and: 'it contains the children'
- parentFragment.childFragments.size() == 1
- def childFragment = parentFragment.childFragments[0]
- childFragment.xpath == childXpath
- and: "and its children's children"
- childFragment.childFragments.size() == 1
- def grandchildFragment = childFragment.childFragments[0]
- grandchildFragment.xpath == grandChildXpath
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Store data node for multiple anchors using the same schema.'() {
- def xpath = "/parent-new"
- given: 'a fragment is stored for an anchor'
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1, createDataNodeTree(xpath))
- when: 'another fragment is stored for an other anchor, using the same schema set'
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME3, createDataNodeTree(xpath))
- then: 'both fragments can be retrieved by their xpath'
- def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
- fragment1.anchor.name == ANCHOR_NAME1
- fragment1.xpath == xpath
- def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
- fragment2.anchor.name == ANCHOR_NAME3
- fragment2.xpath == xpath
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Store datanode error scenario: #scenario.'() {
- when: 'attempt to store a data node with #scenario'
- objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | dataNode || expectedException
- 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNode || DataspaceNotFoundException
- 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNode || AnchorNotFoundException
- 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNode || ConstraintViolationException
- 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNode || AlreadyDefinedException
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add a child to a Fragment that already has a child.'() {
- given: ' a new child node'
- def newChild = createDataNodeTree('xpath for new child')
- when: 'the child is added to an existing parent with 1 child'
- objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
- then: 'the parent is now has to 2 children'
- def expectedExistingChildPath = '/parent-1/child-1'
- def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
- parentFragment.getChildFragments().size() == 2
- and: 'it still has the old child'
- parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
- and: 'it has the new child'
- parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add child error scenario: #scenario.'() {
- when: 'attempt to add a child data node with #scenario'
- objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | parentXpath | dataNode || expectedException
- 'parent does not exist' | 'unknown' | newDataNode || DataNodeNotFoundException
- 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || AlreadyDefinedException
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add list-node fragment with multiple elements.'() {
- given: 'list node data fragment as a collection of data nodes'
- def listNodeXpaths = ['/parent-201/child-204[@key="B"]', '/parent-201/child-204[@key="C"]']
- def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
- when: 'list-node elements added to existing parent node'
- objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
- then: 'new entries successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
- def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
- def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
- assert allChildXpaths.size() == 5
- assert allChildXpaths.containsAll(listNodeXpaths)
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add list-node fragment error scenario: #scenario.'() {
- given: 'list node data fragment as a collection of data nodes'
- def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
- when: 'list-node elements added to existing parent node'
- objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'following parameters were used'
- scenario | parentNodeXpath | listNodeXpaths || expectedException
- 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
- 'already existing fragment' | '/parent-201' | ['/parent-201/child-204[@key="A"]'] || AlreadyDefinedException
-
- }
+import org.onap.cps.spi.repository.AnchorRepository
+import org.onap.cps.spi.repository.DataspaceRepository
+import org.onap.cps.spi.repository.FragmentRepository
+import spock.lang.Specification
- static def createDataNodeTree(String... xpaths) {
- def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
- if (xpaths.length > 1) {
- def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
- def childDataNode = createDataNodeTree(xPathsDescendant)
- dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
- }
- dataNodeBuilder.build()
- }
- def getFragmentByXpath(dataspaceName, anchorName, xpath) {
- def dataspace = dataspaceRepository.getByName(dataspaceName)
- def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
- return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
- }
+class CpsDataPersistenceServiceSpec extends Specification {
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node by xpath without descendants.'() {
- when: 'data node is requested'
- def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- inputXPath, OMIT_DESCENDANTS)
- then: 'data node is returned with no descendants'
- assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
- and: 'expected leaves'
- assert result.getChildDataNodes().size() == 0
- assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
- where: 'the following data is used'
- scenario | inputXPath
- 'some xpath' | '/parent-100'
- 'root xpath' | '/'
- 'empty xpath' | ''
- }
+ def mockDataspaceRepository = Mock(DataspaceRepository)
+ def mockAnchorRepository = Mock(AnchorRepository)
+ def mockFragmentRepository = Mock(FragmentRepository)
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node by xpath with all descendants.'() {
- when: 'data node is requested with all descendants'
- def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- inputXPath, INCLUDE_ALL_DESCENDANTS)
- def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
- then: 'data node is returned with all the descendants populated'
- assert mappedResult.size() == 4
- assert result.getChildDataNodes().size() == 2
- assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
- assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
- and: 'extracted leaves maps are matching expected'
- mappedResult.forEach(
- (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath]))
- where: 'the following data is used'
- scenario | inputXPath
- 'some xpath' | '/parent-100'
- 'root xpath' | '/'
- 'empty xpath' | ''
- }
+ def objectUnderTest = new CpsDataPersistenceServiceImpl(
+ mockDataspaceRepository, mockAnchorRepository, mockFragmentRepository)
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node error scenario: #scenario.'() {
- when: 'attempt to get data node with #scenario'
- objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH' || DataNodeNotFoundException
- }
+ def 'Handling of StaleStateException (caused by concurrent updates) during data node tree update.'() {
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Update data node leaves.'() {
- when: 'update is performed for leaves'
- objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- "/parent-200/child-201", ['leaf-value': 'new'])
- then: 'leaves are updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'existing child entry remains as is'
- def childFragment = updatedFragment.getChildFragments().iterator().next()
- def childLeaves = getLeavesMap(childFragment)
- assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
- assert childLeaves.'leaf-value' == 'original'
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Update data leaves error scenario: #scenario.'() {
- when: 'attempt to update data node for #scenario'
- objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree with descendants removal.'() {
- given: 'data node object with leaves updated, no children'
- def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
- when: 'replace data node tree is performed'
- objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
- then: 'leaves have been updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'updated entry has no children'
- updatedFragment.getChildFragments().isEmpty()
- and: 'previously attached child entry is removed from database'
- fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree with descendants.'() {
- given: 'data node object with leaves updated, having child with old content'
- def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
- buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
- ])
- when: 'update is performed including descendants'
- objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
- then: 'leaves have been updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'previously attached child entry is removed from database'
- fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
- and: 'new child entry with same content is created'
- def childFragment = updatedFragment.getChildFragments().iterator().next()
- def childLeaves = getLeavesMap(childFragment)
- assert childFragment.getId() != UPDATE_DATA_NODE_SUB_FRAGMENT_ID
- assert childLeaves.'leaf-value' == 'original'
- }
+ def parentXpath = 'parent-01'
+ def myDataspaceName = 'my-dataspace'
+ def myAnchorName = 'my-anchor'
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree error scenario: #scenario.'() {
given: 'data node object'
- def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
- when: 'attempt to update data node for #scenario'
- objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace list-node content of #scenario.'() {
- given: 'list node data fragment as a collection of data nodes'
- def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
- when: 'list-node elements replaced within the existing parent node'
- objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
- then: 'child list elements are updated as expected, non-list element remains as is'
- def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
- def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
- assert allChildXpaths.size() == expectedChildXpaths.size()
- assert allChildXpaths.containsAll(expectedChildXpaths)
- where: 'following parameters were used'
- scenario | listNodeXpaths || expectedChildXpaths
- 'existing list-node' | ['/parent-201/child-204[@key="B"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="B"]']
- 'non-existing list-node' | ['/parent-201/child-205[@key="1"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="A"]', '/parent-201/child-204[@key="X"]', '/parent-201/child-205[@key="1"]']
- }
-
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace list-node fragment error scenario: #scenario.'() {
- given: 'list node data fragment as a collection of data nodes'
- def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
- when: 'list-node elements were replaced under existing parent node'
- objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'following parameters were used'
- scenario | parentNodeXpath | listNodeXpaths || expectedException
- 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
- }
-
- static Collection<DataNode> buildDataNodeCollection(xpaths) {
- return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
- }
-
- static DataNode buildDataNode(xpath, leaves, childDataNodes) {
- return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
- }
+ def submittedDataNode = new DataNodeBuilder()
+ .withXpath(parentXpath)
+ .withLeaves(['leaf-name': 'leaf-value'])
+ .build()
+ and: 'fragment to be updated'
+ mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, _) >> {
+ def fragmentEntity = new FragmentEntity()
+ fragmentEntity.setXpath(parentXpath)
+ fragmentEntity.setChildFragments(Collections.emptySet())
+ return fragmentEntity
+ }
+ and: 'data node is concurrently updated by another transaction'
+ mockFragmentRepository.save(_) >> { throw new StaleStateException("concurrent updates") }
- static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
- return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
- }
+ when: 'attempt to update data node'
+ objectUnderTest.replaceDataNodeTree(myDataspaceName, myAnchorName, submittedDataNode)
- def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
- expectedLeavesMap.forEach((key, value) -> {
- def actualValue = actualLeavesMap[key]
- if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
- assert value.size() == actualValue.size()
- assert value.containsAll(actualValue)
- } else {
- assert value == actualValue
- }
- })
- return true
+ then: 'concurrency exception is thrown'
+ def concurrencyException = thrown(ConcurrencyException)
+ assert concurrencyException.getDetails().contains(myDataspaceName)
+ assert concurrencyException.getDetails().contains(myAnchorName)
+ assert concurrencyException.getDetails().contains(parentXpath)
}
- def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
- flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
- dataNodeTree.getChildDataNodes()
- .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
- return flatMap
- }
}
diff --git a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceUnitSpec.groovy b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceSpec.groovy
index ffbac485e..4455a6fa4 100644
--- a/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceUnitSpec.groovy
+++ b/cps-ri/src/test/groovy/org/onap/cps/spi/impl/CpsModulePersistenceServiceSpec.groovy
@@ -33,7 +33,7 @@ import java.sql.SQLException
/**
* Specification unit test class for CPS module persistence service.
*/
-class CpsModulePersistenceServiceUnitSpec extends Specification {
+class CpsModulePersistenceServiceSpec extends Specification {
// Instance to test
CpsModulePersistenceService objectUnderTest
diff --git a/cps-ri/src/test/java/org/onap/cps/DatabaseTestContainer.java b/cps-ri/src/test/java/org/onap/cps/DatabaseTestContainer.java
index d3908ea80..10f8de422 100755
--- a/cps-ri/src/test/java/org/onap/cps/DatabaseTestContainer.java
+++ b/cps-ri/src/test/java/org/onap/cps/DatabaseTestContainer.java
@@ -23,8 +23,10 @@ import org.testcontainers.containers.PostgreSQLContainer;
/**
* The Postgresql database test container wrapper.
- * Singleton implementation allows saving time on database initialization which
- * otherwise would occur on each test.
+ * Singleton implementation allows saving time on database initialization which otherwise would occur on each test.
+ * for debugging/developing purposes you can suspend any test and connect to this database:
+ * docker exec -it {container-id} sh
+ * psql -d test -U test
*/
public class DatabaseTestContainer extends PostgreSQLContainer<DatabaseTestContainer> {
private static final String IMAGE_VERSION = "postgres:13.2";
diff --git a/cps-ri/src/test/resources/data/anchor.sql b/cps-ri/src/test/resources/data/anchor.sql
index a7d3e6715..dbf1a6a47 100644
--- a/cps-ri/src/test/resources/data/anchor.sql
+++ b/cps-ri/src/test/resources/data/anchor.sql
@@ -1,3 +1,25 @@
+/*
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020 Pantheon.tech
+ Modifications Copyright (C) 2020 Nordix Foundation.
+ Modifications Copyright (C) 2021 Bell Canada.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+*/
+
INSERT INTO DATASPACE (ID, NAME) VALUES
(1001, 'DATASPACE-001'), (1002, 'DATASPACE-002');
@@ -9,4 +31,4 @@ INSERT INTO ANCHOR (ID, NAME, DATASPACE_ID, SCHEMA_SET_ID) VALUES
(3002, 'ANCHOR-002', 1001, 2002);
INSERT INTO FRAGMENT (ID, DATASPACE_ID, ANCHOR_ID, PARENT_ID, XPATH, ATTRIBUTES) VALUES
- (4001, 1001, 3001, null, '/xpath', '{}'); \ No newline at end of file
+ (4001, 1001, 3001, null, '/xpath', '{}');
diff --git a/cps-ri/src/test/resources/data/clear-all.sql b/cps-ri/src/test/resources/data/clear-all.sql
index 9aee604a3..8a5e8444e 100644
--- a/cps-ri/src/test/resources/data/clear-all.sql
+++ b/cps-ri/src/test/resources/data/clear-all.sql
@@ -1,3 +1,25 @@
+/*
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020-2021 Pantheon.tech
+ Modifications Copyright (C) 2020 Nordix Foundation.
+ Modifications Copyright (C) 2020 Bell Canada.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+*/
+
DELETE FROM FRAGMENT;
DELETE FROM ANCHOR;
DELETE FROM DATASPACE;
diff --git a/cps-ri/src/test/resources/data/cps-path-query.sql b/cps-ri/src/test/resources/data/cps-path-query.sql
index 67558456e..8f525df6b 100644
--- a/cps-ri/src/test/resources/data/cps-path-query.sql
+++ b/cps-ri/src/test/resources/data/cps-path-query.sql
@@ -1,3 +1,24 @@
+/*
+ ============LICENSE_START=======================================================
+ Copyright (C) 2021 Nordix Foundation.
+ Modifications Copyright (C) 2021 Bell Canada.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+*/
+
INSERT INTO DATASPACE (ID, NAME) VALUES
(1001, 'DATASPACE-001');
@@ -12,8 +33,8 @@ INSERT INTO FRAGMENT (ID, DATASPACE_ID, ANCHOR_ID, PARENT_ID, XPATH, ATTRIBUTES)
(2, 1001, 1003, 1, '/shops/shop[@id=1]', '{"id" : 1, "type" : "bookstore"}'),
(3, 1001, 1003, 2, '/shops/shop[@id=1]/categories[@code=1]', '{"code" : 1, "type" : "bookstore", "name": "SciFi"}'),
(4, 1001, 1003, 2, '/shops/shop[@id=1]/categories[@code=2]', '{"code" : 2, "type" : "bookstore", "name": "Fiction"}'),
- (5, 1001, 1003, 3, '/shops/shop[@id=1]/categories[@code=1]/book', '{"price" : 15, "title": "Dune"}'),
- (6, 1001, 1003, 4, '/shops/shop[@id=1]/categories[@code=2]/book', '{"price" : 15, "title": "Chapters"}'),
+ (5, 1001, 1003, 3, '/shops/shop[@id=1]/categories[@code=1]/book', '{"price" : 5, "title" : "Dune", "labels" : ["special offer","classics",""]}'),
+ (6, 1001, 1003, 4, '/shops/shop[@id=1]/categories[@code=2]/book', '{"price" : 15, "title" : "Chapters", "editions" : [2000,2010,2020]}'),
(7, 1001, 1003, 5, '/shops/shop[@id=1]/categories[@code=1]/book/author[@FirstName="Joe" and @Surname="Bloggs"]', '{"FirstName" : "Joe", "Surname": "Bloggs","title": "Dune"}'),
(8, 1001, 1003, 6, '/shops/shop[@id=1]/categories[@code=2]/book/author[@FirstName="Joe" and @Surname="Smith"]', '{"FirstName" : "Joe", "Surname": "Smith","title": "Chapters"}');
@@ -30,4 +51,4 @@ INSERT INTO FRAGMENT (ID, DATASPACE_ID, ANCHOR_ID, PARENT_ID, XPATH, ATTRIBUTES)
(17, 1001, 1003, 1, '/shops/shop[@id=3]/info/contact', null),
(18, 1001, 1003, 1, '/shops/shop[@id=3]/info/contact/website', '{"address" : "myshop.ie"}'),
(19, 1001, 1003, 12, '/shops/shop[@id=3]/info/contact/phonenumbers[@type="mob"]', '{"type" : "mob", "number" : "123123456"}'),
- (20, 1001, 1003, 12, '/shops/shop[@id=3]/info/contact/phonenumbers[@type="landline"]', '{"type" : "landline", "number" : "012123456"}'); \ No newline at end of file
+ (20, 1001, 1003, 12, '/shops/shop[@id=3]/info/contact/phonenumbers[@type="landline"]', '{"type" : "landline", "number" : "012123456"}');
diff --git a/cps-ri/src/test/resources/data/fragment.sql b/cps-ri/src/test/resources/data/fragment.sql
index 1897185fa..d7109f20b 100755
--- a/cps-ri/src/test/resources/data/fragment.sql
+++ b/cps-ri/src/test/resources/data/fragment.sql
@@ -1,3 +1,25 @@
+/*
+ ============LICENSE_START=======================================================
+ Copyright (C) 2021 Nordix Foundation.
+ Modifications Copyright (C) 2021 Pantheon.tech
+ Modifications Copyright (C) 2021 Bell Canada.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+*/
+
INSERT INTO DATASPACE (ID, NAME) VALUES
(1001, 'DATASPACE-001');
@@ -31,4 +53,4 @@ INSERT INTO FRAGMENT (ID, DATASPACE_ID, ANCHOR_ID, PARENT_ID, XPATH, ATTRIBUTES)
(4206, 1001, 3003, null, '/parent-201', '{"leaf-value": "original"}'),
(4207, 1001, 3003, 4206, '/parent-201/child-203', '{}'),
(4208, 1001, 3003, 4206, '/parent-201/child-204[@key="A"]', '{"key": "A"}'),
- (4209, 1001, 3003, 4206, '/parent-201/child-204[@key="X"]', '{"key": "X"}'); \ No newline at end of file
+ (4209, 1001, 3003, 4206, '/parent-201/child-204[@key="X"]', '{"key": "X"}');
diff --git a/cps-ri/src/test/resources/data/schemaset.sql b/cps-ri/src/test/resources/data/schemaset.sql
index e6306d0d0..adfcfa172 100644
--- a/cps-ri/src/test/resources/data/schemaset.sql
+++ b/cps-ri/src/test/resources/data/schemaset.sql
@@ -1,3 +1,25 @@
+/*
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020-2021 Pantheon.tech
+ Modifications Copyright (C) 2020 Nordix Foundation.
+ Modifications Copyright (C) 2020-2021 Bell Canada.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+*/
+
INSERT INTO DATASPACE (ID, NAME) VALUES
(1001, 'DATASPACE-001'), (1002, 'DATASPACE-002');
diff --git a/cps-service/src/main/java/org/onap/cps/spi/exceptions/ConcurrencyException.java b/cps-service/src/main/java/org/onap/cps/spi/exceptions/ConcurrencyException.java
new file mode 100644
index 000000000..3a8a94b97
--- /dev/null
+++ b/cps-service/src/main/java/org/onap/cps/spi/exceptions/ConcurrencyException.java
@@ -0,0 +1,27 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (c) 2021 Bell Canada.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.spi.exceptions;
+
+public class ConcurrencyException extends CpsException {
+
+ public ConcurrencyException(final String message, final String details, final Throwable cause) {
+ super(message, details, cause);
+ }
+
+}
diff --git a/cps-service/src/main/java/org/onap/cps/utils/YangUtils.java b/cps-service/src/main/java/org/onap/cps/utils/YangUtils.java
index e6c49ac8b..8c32010d7 100644
--- a/cps-service/src/main/java/org/onap/cps/utils/YangUtils.java
+++ b/cps-service/src/main/java/org/onap/cps/utils/YangUtils.java
@@ -44,6 +44,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeS
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@Slf4j
@@ -83,7 +84,7 @@ public class YangUtils {
private static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
final Optional<DataSchemaNode> optionalParentSchemaNode) {
final var jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
- .getShared(schemaContext);
+ .getShared((EffectiveModelContext) schemaContext);
final var normalizedNodeResult = new NormalizedNodeResult();
final var normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
.from(normalizedNodeResult);
diff --git a/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsAdminServiceImplSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsAdminServiceImplSpec.groovy
index 532f44203..be213c0fa 100755
--- a/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsAdminServiceImplSpec.groovy
+++ b/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsAdminServiceImplSpec.groovy
@@ -35,16 +35,16 @@ class CpsAdminServiceImplSpec extends Specification {
}
def 'Create dataspace method invokes persistence service.'() {
- when: 'Create dataspace method is invoked'
+ when: 'create dataspace method is invoked'
objectUnderTest.createDataspace('someDataspace')
- then: 'The persistence service method is invoked with same parameters'
+ then: 'the persistence service method is invoked with same parameters'
1 * mockCpsAdminPersistenceService.createDataspace('someDataspace')
}
def 'Create anchor method invokes persistence service.'() {
- when: 'Create anchor method is invoked'
+ when: 'create anchor method is invoked'
objectUnderTest.createAnchor('someDataspace', 'someSchemaSet', 'someAnchorName')
- then: 'The persistence service method is invoked with same parameters'
+ then: 'the persistence service method is invoked with same parameters'
1 * mockCpsAdminPersistenceService.createAnchor('someDataspace', 'someSchemaSet', 'someAnchorName')
}
@@ -61,7 +61,7 @@ class CpsAdminServiceImplSpec extends Specification {
Anchor anchor = new Anchor()
mockCpsAdminPersistenceService.getAnchor('someDataspace','someAnchor') >> anchor
expect: 'the anchor provided by persistence service is returned as result'
- objectUnderTest.getAnchor('someDataspace','someAnchor') == anchor
+ assert objectUnderTest.getAnchor('someDataspace','someAnchor') == anchor
}
def 'Delete anchor.'() {
diff --git a/cps-service/src/test/groovy/org/onap/cps/model/DataNodeBuilderSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/model/DataNodeBuilderSpec.groovy
index 7f50f7f52..2751d5507 100644
--- a/cps-service/src/test/groovy/org/onap/cps/model/DataNodeBuilderSpec.groovy
+++ b/cps-service/src/test/groovy/org/onap/cps/model/DataNodeBuilderSpec.groovy
@@ -1,6 +1,7 @@
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2021 Pantheon.tech
+ * Modifications Copyright (C) 2021 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,11 +29,12 @@ import spock.lang.Specification
class DataNodeBuilderSpec extends Specification {
Map<String, Map<String, Object>> expectedLeavesByXpathMap = [
- '/test-tree' : [],
- '/test-tree/branch[@name=\'Left\']' : [name: 'Left'],
- '/test-tree/branch[@name=\'Left\']/nest' : [name: 'Small', birds: ['Sparrow', 'Robin', 'Finch']],
- '/test-tree/branch[@name=\'Right\']' : [name: 'Right'],
- '/test-tree/branch[@name=\'Right\']/nest': [name: 'Big', birds: ['Owl', 'Raven', 'Crow']]
+ '/test-tree' : [],
+ '/test-tree/branch[@name=\'Left\']' : [name: 'Left'],
+ '/test-tree/branch[@name=\'Left\']/nest' : [name: 'Small', birds: ['Sparrow', 'Robin', 'Finch']],
+ '/test-tree/branch[@name=\'Right\']' : [name: 'Right'],
+ '/test-tree/branch[@name=\'Right\']/nest' : [name: 'Big', birds: ['Owl', 'Raven', 'Crow']],
+ '/test-tree/fruit[@color=\'Green\' and @name=\'Apple\']': [color: 'Green', name: 'Apple']
]
String[] networkTopologyModelRfc8345 = [
@@ -55,7 +57,7 @@ class DataNodeBuilderSpec extends Specification {
def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).build()
def mappedResult = TestUtils.getFlattenMapByXpath(result)
then: '5 DataNode objects with unique xpath were created in total'
- mappedResult.size() == 5
+ mappedResult.size() == 6
and: 'all expected xpaths were built'
mappedResult.keySet().containsAll(expectedLeavesByXpathMap.keySet())
and: 'each data node contains the expected attributes'
diff --git a/cps-service/src/test/resources/test-tree.json b/cps-service/src/test/resources/test-tree.json
index bc9cbd7ce..e1789abc1 100644
--- a/cps-service/src/test/resources/test-tree.json
+++ b/cps-service/src/test/resources/test-tree.json
@@ -23,6 +23,12 @@
]
}
}
+ ],
+ "fruit": [
+ {
+ "name": "Apple",
+ "color": "Green"
+ }
]
}
-} \ No newline at end of file
+}
diff --git a/cps-service/src/test/resources/test-tree.yang b/cps-service/src/test/resources/test-tree.yang
index faba8a11d..63100657e 100644
--- a/cps-service/src/test/resources/test-tree.yang
+++ b/cps-service/src/test/resources/test-tree.yang
@@ -20,5 +20,17 @@ module test-tree {
}
}
}
+ list fruit {
+ key "name color";
+
+ leaf name {
+ type string;
+ }
+
+ leaf color {
+ type string;
+ }
+
+ }
}
}
diff --git a/csit/plans/default/setup.sh b/csit/plans/default/setup.sh
index 4d5d1c85c..cf29b53ac 100755
--- a/csit/plans/default/setup.sh
+++ b/csit/plans/default/setup.sh
@@ -17,6 +17,7 @@
# Modifications copyright (c) 2017 AT&T Intellectual Property
# Modifications copyright (c) 2020-2021 Samsung Electronics Co., Ltd.
# Modifications Copyright (C) 2021 Pantheon.tech
+# Modifications Copyright (C) 2021 Bell Canada.
#
# Branched from ccsdk/distribution to this repository Feb 23, 2021
#
@@ -66,8 +67,11 @@ if [ "$TIME" -gt "$TIME_OUT" ]; then
fi
# The CPS host according to docker-compose.yml
-CPS_HOST="http://localhost:8883"
+CPS_HOST="localhost"
+CPS_PORT="8883"
+
+MANAGEMENT_PORT="8887"
# Pass variables required for Robot test suites in ROBOT_VARIABLES
-ROBOT_VARIABLES="-v CPS_HOST:$CPS_HOST -v DATADIR:$WORKSPACE/data"
+ROBOT_VARIABLES="-v CPS_HOST:$CPS_HOST -v CPS_PORT:$CPS_PORT -v MANAGEMENT_PORT:$MANAGEMENT_PORT -v DATADIR:$WORKSPACE/data"
diff --git a/csit/tests/actuator/actuator.robot b/csit/tests/actuator/actuator.robot
index 3a0493d68..55ff40e07 100644
--- a/csit/tests/actuator/actuator.robot
+++ b/csit/tests/actuator/actuator.robot
@@ -1,5 +1,6 @@
# ============LICENSE_START=======================================================
# Copyright (c) 2021 Pantheon.tech.
+# Modifications Copyright (c) 2021 Bell Canada.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -22,16 +23,17 @@ Documentation CPS - Actuator endpoints
Library Collections
Library RequestsLibrary
-Suite Setup Create Session CPS_HOST ${CPS_HOST}
+Suite Setup Create Session MANAGEMENT_URL http://${CPS_HOST}:${MANAGEMENT_PORT}/manage
*** Variables ***
*** Test Cases ***
Test Liveness Probe Endpoint
- ${response}= GET On Session CPS_HOST /manage/health/liveness expected_status=200
+ ${response}= GET On Session MANAGEMENT_URL health/liveness expected_status=200
Should Be Equal As Strings ${response.json()['status']} UP
Test Readiness Probe Endpoint
- ${response}= GET On Session CPS_HOST /manage/health/readiness expected_status=200
+ ${response}= GET On Session MANAGEMENT_URL health/readiness expected_status=200
Should Be Equal As Strings ${response.json()['status']} UP
+
diff --git a/csit/tests/cps-admin/cps-admin.robot b/csit/tests/cps-admin/cps-admin.robot
index 7e944ec6f..43a46d327 100644
--- a/csit/tests/cps-admin/cps-admin.robot
+++ b/csit/tests/cps-admin/cps-admin.robot
@@ -23,7 +23,7 @@ Library Collections
Library OperatingSystem
Library RequestsLibrary
-Suite Setup Create Session CPS_HOST ${CPS_HOST}
+Suite Setup Create Session CPS_URL http://${CPS_HOST}:${CPS_PORT}
*** Variables ***
@@ -40,7 +40,7 @@ Create Dataspace
${uri}= Set Variable ${basePath}/v1/dataspaces
${params}= Create Dictionary dataspace-name=${dataspaceName}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= POST On Session CPS_HOST ${uri} params=${params} headers=${headers}
+ ${response}= POST On Session CPS_URL ${uri} params=${params} headers=${headers}
Should Be Equal As Strings ${response.status_code} 201
Create Schema Set from YANG file
@@ -50,7 +50,7 @@ Create Schema Set from YANG file
${fileTuple}= Create List test.yang ${fileData} application/zip
&{files}= Create Dictionary file=${fileTuple}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= POST On Session CPS_HOST ${uri} files=${files} params=${params} headers=${headers}
+ ${response}= POST On Session CPS_URL ${uri} files=${files} params=${params} headers=${headers}
Should Be Equal As Strings ${response.status_code} 201
Create Schema Set from ZIP file
@@ -60,13 +60,13 @@ Create Schema Set from ZIP file
${fileTuple}= Create List test.zip ${fileData} application/zip
&{files}= Create Dictionary file=${fileTuple}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= POST On Session CPS_HOST ${uri} files=${files} params=${params} headers=${headers}
+ ${response}= POST On Session CPS_URL ${uri} files=${files} params=${params} headers=${headers}
Should Be Equal As Strings ${response.status_code} 201
Get Schema Set info
${uri}= Set Variable ${basePath}/v1/dataspaces/${dataspaceName}/schema-sets/${schemaSetName}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= Get On Session CPS_HOST ${uri} headers=${headers} expected_status=200
+ ${response}= Get On Session CPS_URL ${uri} headers=${headers} expected_status=200
${responseJson}= Set Variable ${response.json()}
Should Be Equal As Strings ${responseJson['name']} ${schemaSetName}
Should Be Equal As Strings ${responseJson['dataspaceName']} ${dataspaceName}
@@ -75,13 +75,13 @@ Create Anchor
${uri}= Set Variable ${basePath}/v1/dataspaces/${dataspaceName}/anchors
${params}= Create Dictionary schema-set-name=${schemaSetName} anchor-name=${anchorName}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= POST On Session CPS_HOST ${uri} params=${params} headers=${headers}
+ ${response}= POST On Session CPS_URL ${uri} params=${params} headers=${headers}
Should Be Equal As Strings ${response.status_code} 201
Get CPS RAN Schema Set info
${uri}= Set Variable ${basePath}/v1/dataspaces/${ranDataspaceName}/schema-sets/${ranSchemaSetName}
${headers}= Create Dictionary Authorization=${auth}
- ${response}= Get On Session CPS_HOST ${uri} headers=${headers} expected_status=200
+ ${response}= Get On Session CPS_URL ${uri} headers=${headers} expected_status=200
${responseJson}= Set Variable ${response.json()}
Should Be Equal As Strings ${responseJson['name']} ${ranSchemaSetName}
Should Be Equal As Strings ${responseJson['dataspaceName']} ${ranDataspaceName}
diff --git a/csit/tests/cps-data/cps-data.robot b/csit/tests/cps-data/cps-data.robot
index 9fd8451d2..e7334ae11 100644
--- a/csit/tests/cps-data/cps-data.robot
+++ b/csit/tests/cps-data/cps-data.robot
@@ -23,7 +23,7 @@ Library Collections
Library OperatingSystem
Library RequestsLibrary
-Suite Setup Create Session CPS_HOST ${CPS_HOST}
+Suite Setup Create Session CPS_URL http://${CPS_HOST}:${CPS_PORT}
*** Variables ***
@@ -37,14 +37,14 @@ Create Data Node
${uri}= Set Variable ${basePath}/v1/dataspaces/${dataspaceName}/anchors/${anchorName}/nodes
${headers} Create Dictionary Content-Type=application/json Authorization=${auth}
${jsonData}= Get Binary File ${DATADIR}${/}test-tree.json
- ${response}= POST On Session CPS_HOST ${uri} headers=${headers} data=${jsonData}
+ ${response}= POST On Session CPS_URL ${uri} headers=${headers} data=${jsonData}
Should Be Equal As Strings ${response.status_code} 201
Get Data Node by XPath
${uri}= Set Variable ${basePath}/v1/dataspaces/${dataspaceName}/anchors/${anchorName}/node
${params}= Create Dictionary xpath=/test-tree/branch[@name='Left']/nest
${headers}= Create Dictionary Authorization=${auth}
- ${response}= Get On Session CPS_HOST ${uri} params=${params} headers=${headers} expected_status=200
+ ${response}= Get On Session CPS_URL ${uri} params=${params} headers=${headers} expected_status=200
${responseJson}= Set Variable ${response.json()}
Should Be Equal As Strings ${responseJson['name']} Small
diff --git a/docker-compose/docker-compose.yml b/docker-compose/docker-compose.yml
index e7e745096..e2185f6de 100755
--- a/docker-compose/docker-compose.yml
+++ b/docker-compose/docker-compose.yml
@@ -24,6 +24,7 @@ services:
# image: ${DOCKER_REPO:-nexus3.onap.org:10003}/onap/cps-service:${VERSION:-latest}
# ports:
# - "8881:8080"
+ # - "8887:8081"
# environment:
# CPS_USERNAME: ${CPS_USERNAME:-cpsuser}
# CPS_PASSWORD: ${CPS_PASSWORD:-cpsr0cks!}
@@ -41,6 +42,7 @@ services:
# image: ${DOCKER_REPO:-nexus3.onap.org:10003}/onap/cps-ncmp:${VERSION:-latest}
# ports:
# - "8882:8080"
+ # - "8887:8081"
# environment:
# CPS_USERNAME: ${CPS_USERNAME:-cpsuser}
# CPS_PASSWORD: ${CPS_PASSWORD:-cpsr0cks!}
@@ -58,6 +60,7 @@ services:
image: ${DOCKER_REPO:-nexus3.onap.org:10003}/onap/cps-and-ncmp:${VERSION:-latest}
ports:
- "8883:8080"
+ - "8887:8081"
environment:
CPS_USERNAME: ${CPS_USERNAME:-cpsuser}
CPS_PASSWORD: ${CPS_PASSWORD:-cpsr0cks!}
diff --git a/docs/cps-path.rst b/docs/cps-path.rst
index aec87cd43..0271d07e1 100644
--- a/docs/cps-path.rst
+++ b/docs/cps-path.rst
@@ -14,8 +14,8 @@ CPS Path
Introduction
============
-Several CPS APIs use the cps-path (or cpsPath in Java API) parameter.
-The CPS Path parameter is used for querying xpaths. CPS Path is insprired by the `XML Path Language (XPath) 3.1. <https://www.w3.org/TR/2017/REC-xpath-31-20170321/>`_
+Several CPS APIs use the CPS path (or cpsPath in Java API) parameter.
+The CPS path parameter is used for querying xpaths. CPS path is inspired by the `XML Path Language (XPath) 3.1. <https://www.w3.org/TR/2017/REC-xpath-31-20170321/>`_
This section describes the functionality currently supported by CPS Path.
@@ -28,104 +28,137 @@ The xml below describes some basic data to be used to illustrate the CPS Path fu
<shops>
<bookstore name="Chapters">
- <bookstore-name>Chapters</bookstore-name>
- <categories code="1" name="SciFi" numberOfBooks="2">
- <books>
- <book name="Space Odyssee"/>
- <book name="Dune"/>
- </books>
- </categories>
- <categories code="2" name="Kids" numberOfBooks="1">
- <books>
- <book name="Matilda"/>
- </books>
- </categories>
+ <bookstore-name>Chapters</bookstore-name>
+ <categories code="1" name="SciFi" numberOfBooks="2">
+ <books>
+ <book title="2001: A Space Odyssey" price="5">
+ <label>sale</label>
+ <label>classic</label>
+ <edition>1968</edition>
+ <edition>2018</edition>
+ </book>
+ <book title="Dune" price="5">
+ <label>classic</label>
+ <edition>1965</edition>
+ </book>
+ </books>
+ </categories>
+ <categories code="2" name="Kids" numberOfBooks="1">
+ <books>
+ <book title="Matilda" />
+ </books>
+ </categories>
</bookstore>
</shops>
-**Note.** 'categories' is a Yang List and 'code' is its key leaf. All other data nodes are Yang Containers
+**Note.** 'categories' is a Yang List and 'code' is its key leaf. All other data nodes are Yang Containers. 'label' and 'edition' are both leaf-lists.
General Notes
=============
-- String values must be wrapped in quotation marks (U+0022) or apostrophes (U+0027).
+- String values must be wrapped in quotation marks ``"`` (U+0022) or apostrophes ``'`` (U+0027).
- String comparisons are case sensitive.
+- List key-fields containing ``\`` or ``@[`` will not be processed correctly when being referenced with such key values in absolute or descendant paths. This means such entries will be omitted from any query result. See `CPS-500 <https://jira.onap.org/browse/CPS-500>`_ Special Character Limitations of cpsPath Queries
-Supported Queries
-=================
+Query Syntax
+============
-Get List Elements by Any Attribute Value
-----------------------------------------
+``( <absolute-path> | <descendant-path> ) [ <leaf-conditions> ] [ <text()-condition> ] [ <ancestor-axis> ]``
-**Syntax**: ``<xpath>/<target-node>[@<leaf-name>=<leaf-value>]``
- - ``xpath``: The xpath to the parent of the target node including all ancestors.
- - ``target-node``: The name of the (list) node which elements will queried.
- - ``leaf-name``: The name of the leaf which value needs to be compared.
- - ``leaf-value``: The required value of the leaf.
+Each CPS path expression need to start with an 'absolute' or 'descendant' xpath.
+
+absolute-path
+-------------
+
+**Syntax**: ``'/' <container-name> ( '[' <list-key> ']' )? ( '/' <containerName> ( '[' <list-key> ']' )? )*``
+
+ - ``container name``: Any yang container or list.
+ - ``list-key``: One or more key-value pairs, each preceded by the ``@`` symbol, combined using the ``and`` keyword.
+ - The above van repeated any number of times.
**Examples**
- - ``/shops/bookstore/categories[@numberOfBooks=1]``
- - ``/shops/bookstore/categories[@name="Kids"]``
- - ``/shops/bookstore/categories[@name='Kids']``
+ - ``/shops/bookstore``
+ - ``/shops/bookstore/categories[@code=1]``
+ - ``/shops/bookstore/categories[@code=1]/book``
**Limitations**
- - Only one list (last descendant) can be queried for a non-key value. Any ancestor list will have to be referenced by its key name-value pair(s).
- - Only one attribute can be queried.
- - Only string and integer values are supported (boolean and float values are not supported).
+ - Absolute paths must start with the top element (data node) as per the model tree.
+ - Each list reference must include a valid instance reference to the key for that list. Except when it is the last element.
-**Notes**
- - For performance reasons it does not make sense to query using key leaf as attribute. If the key value is known it is better to execute a get request with the complete xpath.
+descendant-path
+---------------
-Get Any Descendant
-------------------
+**Syntax**: ``'//' <container-name> ( '[' <list-key> ']' )? ( '/' <containerName> ( '[' <list-key> ']' )? )*``
-**Syntax**: ``//<direct-ancestors><target-node>``
- - ``direct-ancestors``: Optional path to direct ancestors of the target node. This can contain zero to many ancestor nodes separated by a /.
- - ``target-node``: The name of the (list) node from which element will be selected. If the target node is a Yang List he element needs to be specified using the key as normal e.g. ``categories[@code=1]``.
+ - The syntax of a descendant path is identical to a absolute path except that it is preceded by a double slash ``//``.
**Examples**
- - ``//book``
- - ``//books/book``
- - ``//categories[@code=1]``
- - ``//categories[@code=1]/books``
+ - ``//bookstore``
+ - ``//categories[@code=1]/book``
+ - ``//bookstore/categories``
**Limitations**
- - List elements can only be addressed using the list key leaf.
+ - Each list reference must include a valid instance reference to the key for that list. Except when it is the last element.
-Get Any Descendant by Any Attribute Value
------------------------------------------
+leaf-conditions
+---------------
-**Syntax**: ``//<direct-ancestors><target-node>[@<leaf-name>=<leaf-value>]``
- - ``direct-ancestors``: Optional path to direct ancestors of the target node. This can contain zero to many ancestor nodes separated by a /.
- - ``target-node``: The name of the (list) node which elements will queried.
- - ``leaf1-name .. leafN-name:``: One or more leaves whose value needs to be compared.
- - ``leaf1-value .. leafN-value:``: One or more required leaf values (multiple condition can be combined using the 'and' keyword).
+**Syntax**: ``<xpath> '[' @<leaf-name1> '=' <leaf-value1> ( ' and ' @<leaf-name> '=' <leaf-value> )* ']'``
+ - ``xpath``: Absolute or descendant or xpath to the (list) node which elements will be queried.
+ - ``leaf-name``: The name of the leaf which value needs to be compared.
+ - ``leaf-value``: The required value of the leaf.
**Examples**
+ - ``/shops/bookstore/categories[@numberOfBooks=1]``
+ - ``//categories[@name="Kids"]``
- ``//categories[@name='Kids']``
- - ``//categories[@name='Kids' and @numberOfBooks=1]``
+ - ``//categories[@code=1]/book[@title='Dune' and price=5]``
**Limitations**
- - Only string and integer values are supported (boolean and float values are not supported).
- - Multiple attributes can only be combined using 'and'. 'or' and bracketing is not supported.
+ - Only the last list or container can be queried leaf values. Any ancestor list will have to be referenced by its key name-value pair(s).
+ - Multiple attributes can only be combined using ``and``. ``or`` and bracketing is not supported.
+ - Only leaves can be used, leaf-list are not supported.
+ - Only string and integer values are supported, boolean and float values are not supported.
+
+**Notes**
+ - For performance reasons it does not make sense to query using key leaf as attribute. If the key value is known it is better to execute a get request with the complete xpath.
+
+text()-condition
+----------------
+
+The text()-condition can be added to any CPS path query.
-Query Extensions
-================
+**Syntax**: ``<cps-path> ( '/' <leaf-name> '[text()=' <string-value> ']' )?``
+ - ``cps-path``: Any CPS path query.
+ - ``leaf-name``: The name of the leaf or leaf-list which value needs to be compared.
+ - ``string-value``: The required value of the leaf or leaf-list element as a string wrapped in quotation marks (U+0022) or apostrophes (U+0027). This wil still match integer values.
+
+**Examples**
+ - ``//book/label[text()="classic"]``
+ - ``//book/edition[text()="1965"]``
+
+**Limitations**
+ - Only the last list or container can be queried for leaf values with a text() condition. Any ancestor list will have to be referenced by its key name-value pair(s).
+ - Only one leaf or leaf-list can be tested.
+ - Only string and integer values are supported, boolean and float values are not supported.
+ - Since CPS cannot return individual leaves it will always return the container with all its leaves. Ancestor-axis can be used to specify a parent higher up the tree.
+ - When querying a leaf value (instead of leaf-list) it is better, more performant to use a text value condition use @<leaf-name> as described above.
-Ancestor Axis
+ancestor-axis
-------------
-The ancestor axis can be added to any CPS path query.
+The ancestor axis can be added to any CPS path query but has to be the last part.
-**Syntax**: ``//<cps-path>/ancestor::<ancestor-path>``
+**Syntax**: ``<cps-path> ( '/ancestor::' <ancestor-path> )?``
- ``cps-path``: Any CPS path query.
- - ``ancestor-path``: Partial path to ancestors of the target node. This can contain one or more ancestor nodes separated by a /.
+ - ``ancestor-path``: Partial path to ancestors of the target node. This can contain one or more ancestor nodes separated by a ``/``.
**Examples**
- ``//book/ancestor::categories``
- ``//categories[@genre="SciFi"]/book/ancestor::bookstore``
- ``book/ancestor::categories[@code=1]/books``
+ - ``//book/label[text()="classic"]/ancestor::shop``
**Limitations**
- Ancestor list elements can only be addressed using the list key leaf.
- - List elements with compound keys are not supported. \ No newline at end of file
+ - List elements with compound keys are not supported.
diff --git a/docs/release-notes.rst b/docs/release-notes.rst
index 8d8bbe333..f213c7e4d 100755
--- a/docs/release-notes.rst
+++ b/docs/release-notes.rst
@@ -16,9 +16,9 @@ CPS Release Notes
-.. =========================
-.. * * * HONOULULU * * *
-.. =========================
+.. ========================
+.. * * * HONOLULU * * *
+.. ========================
Version: 1.0.1
==============