diff options
14 files changed, 298 insertions, 176 deletions
diff --git a/cps-ncmp-rest/docs/openapi/components.yaml b/cps-ncmp-rest/docs/openapi/components.yaml index 021a79037d..22453f367b 100644 --- a/cps-ncmp-rest/docs/openapi/components.yaml +++ b/cps-ncmp-rest/docs/openapi/components.yaml @@ -382,3 +382,13 @@ components: NoContent: description: No Content content: {} + InternalServerError: + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorMessage" + example: + status: 500 + message: Internal Server Error + details: Internal Server Error occurred diff --git a/cps-ncmp-rest/docs/openapi/ncmp-inventory.yml b/cps-ncmp-rest/docs/openapi/ncmp-inventory.yml index b0a50aa83a..f3f84fed9a 100755 --- a/cps-ncmp-rest/docs/openapi/ncmp-inventory.yml +++ b/cps-ncmp-rest/docs/openapi/ncmp-inventory.yml @@ -1,5 +1,6 @@ # ============LICENSE_START======================================================= # Copyright (C) 2021 Bell Canada +# Modifications Copyright (C) 2021-2022 Nordix Foundation # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -38,3 +39,5 @@ updateDmiRegistration: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' diff --git a/cps-ncmp-rest/docs/openapi/ncmp.yml b/cps-ncmp-rest/docs/openapi/ncmp.yml index d80ec6508e..3a71aba804 100755 --- a/cps-ncmp-rest/docs/openapi/ncmp.yml +++ b/cps-ncmp-rest/docs/openapi/ncmp.yml @@ -45,8 +45,8 @@ getResourceDataForPassthroughOperational: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' resourceDataForPassthroughRunning: get: @@ -76,8 +76,8 @@ resourceDataForPassthroughRunning: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' post: tags: - network-cm-proxy @@ -112,8 +112,8 @@ resourceDataForPassthroughRunning: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' put: tags: @@ -149,8 +149,8 @@ resourceDataForPassthroughRunning: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' patch: tags: @@ -180,8 +180,8 @@ resourceDataForPassthroughRunning: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' delete: tags: @@ -204,7 +204,8 @@ resourceDataForPassthroughRunning: $ref: 'components.yaml#/components/responses/Forbidden' 404: $ref: 'components.yaml#/components/responses/NotFound' - + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' fetchModuleReferencesByCmHandle: get: @@ -230,8 +231,8 @@ fetchModuleReferencesByCmHandle: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' - 404: - $ref: 'components.yaml#/components/responses/NotFound' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' executeCmHandleSearch: post: @@ -259,3 +260,5 @@ executeCmHandleSearch: $ref: 'components.yaml#/components/responses/Unauthorized' 403: $ref: 'components.yaml#/components/responses/Forbidden' + 500: + $ref: 'components.yaml#/components/responses/InternalServerError' diff --git a/cps-ncmp-rest/src/main/java/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandler.java b/cps-ncmp-rest/src/main/java/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandler.java index ce9dd5a027..8c6f9f1d70 100755 --- a/cps-ncmp-rest/src/main/java/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandler.java +++ b/cps-ncmp-rest/src/main/java/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandler.java @@ -21,7 +21,9 @@ package org.onap.cps.ncmp.rest.exceptions; import lombok.extern.slf4j.Slf4j; +import org.onap.cps.ncmp.api.impl.exception.DmiRequestException; import org.onap.cps.ncmp.api.impl.exception.NcmpException; +import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException; import org.onap.cps.ncmp.rest.controller.NetworkCmProxyController; import org.onap.cps.ncmp.rest.model.ErrorMessage; import org.onap.cps.spi.exceptions.CpsException; @@ -56,11 +58,16 @@ public class NetworkCmProxyRestExceptionHandler { return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception); } - @ExceptionHandler({NcmpException.class}) - public static ResponseEntity<Object> handleNcmpExceptions(final NcmpException exception) { + @ExceptionHandler({ServerNcmpException.class}) + public static ResponseEntity<Object> handleServerNcmpExceptions(final ServerNcmpException exception) { return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception); } + @ExceptionHandler({DmiRequestException.class}) + public static ResponseEntity<Object> handleDmiRequestExceptions(final DmiRequestException exception) { + return buildErrorResponse(HttpStatus.BAD_REQUEST, exception); + } + private static ResponseEntity<Object> buildErrorResponse(final HttpStatus status, final Exception exception) { if (exception.getCause() != null || !(exception instanceof CpsException)) { log.error("Exception occurred", exception); diff --git a/cps-ncmp-rest/src/test/groovy/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandlerSpec.groovy b/cps-ncmp-rest/src/test/groovy/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandlerSpec.groovy index 7b3cd89145..1b72b8c084 100644 --- a/cps-ncmp-rest/src/test/groovy/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandlerSpec.groovy +++ b/cps-ncmp-rest/src/test/groovy/org/onap/cps/ncmp/rest/exceptions/NetworkCmProxyRestExceptionHandlerSpec.groovy @@ -23,7 +23,8 @@ package org.onap.cps.ncmp.rest.exceptions import groovy.json.JsonSlurper import org.modelmapper.ModelMapper import org.onap.cps.ncmp.api.NetworkCmProxyDataService -import org.onap.cps.ncmp.api.impl.exception.NcmpException +import org.onap.cps.ncmp.api.impl.exception.DmiRequestException +import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException import org.onap.cps.spi.exceptions.CpsException import org.onap.cps.utils.JsonObjectMapper import org.spockframework.spring.SpringBean @@ -34,6 +35,7 @@ import org.springframework.test.web.servlet.MockMvc import spock.lang.Shared import spock.lang.Specification +import static org.springframework.http.HttpStatus.BAD_REQUEST import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get @@ -66,17 +68,18 @@ class NetworkCmProxyRestExceptionHandlerSpec extends Specification { dataNodeBaseEndpoint = "$basePath/v1" } - def 'Get request with generic #scenario exception returns HTTP Status Internal Server Error.'() { - when: 'generic CPS exception is thrown by the service' + def 'Get request with generic #scenario exception returns correct HTTP Status.'() { + when: 'an exception is thrown by the service' setupTestException(exception) def response = performTestRequest() - then: 'an HTTP Internal Server Error response is returned with correct message and details' - assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, expectedErrorDetails) + then: 'an HTTP response is returned with correct message and details' + assertTestResponse(response, expectedErrorCode, errorMessage, expectedErrorDetails) where: - scenario | exception || expectedErrorDetails - 'CPS' | new CpsException(errorMessage, errorDetails) || errorDetails - 'NCMP' | new NcmpException(errorMessage, errorDetails) || null - 'other' | new IllegalStateException(errorMessage) || null + scenario | exception || expectedErrorDetails | expectedErrorCode + 'CPS' | new CpsException(errorMessage, errorDetails) || errorDetails | INTERNAL_SERVER_ERROR + 'NCMP-server' | new ServerNcmpException(errorMessage, errorDetails) || null | INTERNAL_SERVER_ERROR + 'NCMP-client' | new DmiRequestException(errorMessage, errorDetails) || null | BAD_REQUEST + 'other' | new IllegalStateException(errorMessage) || null | INTERNAL_SERVER_ERROR } def setupTestException(exception){ diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java index 82145efc3d..6a156b8972 100755 --- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java +++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImpl.java @@ -39,7 +39,7 @@ import org.onap.cps.api.CpsAdminService; import org.onap.cps.api.CpsDataService; import org.onap.cps.api.CpsModuleService; import org.onap.cps.ncmp.api.NetworkCmProxyDataService; -import org.onap.cps.ncmp.api.impl.exception.NcmpException; +import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException; import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations; import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations; import org.onap.cps.ncmp.api.impl.operations.DmiOperations; @@ -170,7 +170,7 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity.getBody(); } else { - throw new NcmpException(exceptionMessage, + throw new ServerNcmpException(exceptionMessage, "DMI status code: " + responseEntity.getStatusCodeValue() + ", DMI response body: " + responseEntity.getBody()); } diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/DmiRequestException.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/DmiRequestException.java new file mode 100644 index 0000000000..d41ca70bca --- /dev/null +++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/DmiRequestException.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.ncmp.api.impl.exception; + +/** + * Client Based Network CM Proxy exception. + */ +public class DmiRequestException extends NcmpException { + + /** + * Constructor. + * + * @param message the error message + * @param details the error details + */ + public DmiRequestException(final String message, final String details) { + super(message, details); + } +} diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/ServerNcmpException.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/ServerNcmpException.java new file mode 100644 index 0000000000..a03a2d3e6c --- /dev/null +++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/impl/exception/ServerNcmpException.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.ncmp.api.impl.exception; + +/** + * Server Based Network CM Proxy exception. + */ +public class ServerNcmpException extends NcmpException { + + /** + * Constructor. + * + * @param message the error message + * @param details the error details + */ + public ServerNcmpException(final String message, final String details) { + super(message, details); + } +} diff --git a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/DmiPluginRegistration.java b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/DmiPluginRegistration.java index 9faf7331e7..f1b3888c6e 100644 --- a/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/DmiPluginRegistration.java +++ b/cps-ncmp-service/src/main/java/org/onap/cps/ncmp/api/models/DmiPluginRegistration.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021-2022 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,6 +28,7 @@ import com.google.common.base.Strings; import java.util.List; import lombok.Getter; import lombok.Setter; +import org.onap.cps.ncmp.api.impl.exception.DmiRequestException; import org.onap.cps.ncmp.api.impl.exception.NcmpException; /** @@ -80,7 +81,7 @@ public class DmiPluginRegistration { } if (errorMessage != null) { - throw new NcmpException(errorMessage, "Please supply correct plugin information."); + throw new DmiRequestException(errorMessage, "Please supply correct plugin information."); } } diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplRegistrationSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplRegistrationSpec.groovy index 3ec6f3a00d..9f1203d64d 100644 --- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplRegistrationSpec.groovy +++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplRegistrationSpec.groovy @@ -25,6 +25,7 @@ import com.fasterxml.jackson.databind.ObjectMapper import org.onap.cps.api.CpsAdminService import org.onap.cps.api.CpsDataService import org.onap.cps.api.CpsModuleService +import org.onap.cps.ncmp.api.impl.exception.DmiRequestException import org.onap.cps.ncmp.api.impl.exception.NcmpException import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations @@ -176,8 +177,8 @@ class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification { dmiPluginRegistration.createdCmHandles = [persistenceCmHandle] when: 'registration is called with incorrect DMI plugin information' objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration) - then: 'an NcmpException is thrown with correct message details' - def exceptionThrown = thrown(NcmpException) + then: 'a DMI Request Exception is thrown with correct message details' + def exceptionThrown = thrown(DmiRequestException.class) assert exceptionThrown.getMessage().contains(expectedMessageDetails) and: 'registration is not called' 0 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration) diff --git a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy index 7f127003d2..9c79d4fcf1 100644 --- a/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy +++ b/cps-ncmp-service/src/test/groovy/org/onap/cps/ncmp/api/impl/NetworkCmProxyDataServiceImplSpec.groovy @@ -35,7 +35,7 @@ import com.fasterxml.jackson.databind.ObjectMapper import org.onap.cps.api.CpsAdminService import org.onap.cps.api.CpsDataService import org.onap.cps.api.CpsModuleService -import org.onap.cps.ncmp.api.impl.exception.NcmpException +import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations import org.onap.cps.spi.FetchDescendantsOption import org.onap.cps.spi.model.DataNode @@ -88,12 +88,11 @@ class NetworkCmProxyDataServiceImplSpec extends Specification { 'testResourceId', CREATE, '{some-json}', 'application/json') then: 'exception is thrown' - def exceptionThrown = thrown(NcmpException.class) + def exceptionThrown = thrown(ServerNcmpException.class) and: 'details contains (not found) error code: 404' exceptionThrown.details.contains('404') } - def 'Get resource data for pass-through operational from DMI.'() { given: 'get data node is called' mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry', @@ -129,7 +128,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification { 'testAcceptParam', '(a=1,b=2)') then: 'exception is thrown with the expected details' - def exceptionThrown = thrown(NcmpException.class) + def exceptionThrown = thrown(ServerNcmpException.class) exceptionThrown.details == 'DMI status code: 404, DMI response body: NOK-json' } @@ -150,7 +149,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification { 'testAcceptParam', '(a=1,b=2)') then: 'exception is thrown' - def exceptionThrown = thrown(NcmpException.class) + def exceptionThrown = thrown(ServerNcmpException.class) and: 'details contains the original response' exceptionThrown.details.contains('NOK-json') } @@ -191,7 +190,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification { 'testAcceptParam', '(a=1,b=2)') then: 'exception is thrown' - def exceptionThrown = thrown(NcmpException.class) + def exceptionThrown = thrown(ServerNcmpException.class) and: 'details contains the original response' exceptionThrown.details.contains('NOK-json') } @@ -236,7 +235,7 @@ class NetworkCmProxyDataServiceImplSpec extends Specification { '{some-json}', 'application/json') then: 'an exception is thrown with the expected error message detailsd with correct operation' - def exceptionThrown = thrown(NcmpException.class) + def exceptionThrown = thrown(ServerNcmpException.class) exceptionThrown.getMessage().contains(expectedResponseMessage) where: scenario | givenOperation || expectedResponseMessage 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 85b0cb73fa..ed414fc30c 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 @@ -48,6 +48,7 @@ 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.CpsAdminException; import org.onap.cps.spi.exceptions.CpsPathException; import org.onap.cps.spi.exceptions.DataNodeNotFoundException; import org.onap.cps.spi.model.DataNode; @@ -392,6 +393,10 @@ public class CpsDataPersistenceServiceImpl implements CpsDataPersistenceService } private static String getListElementXpathPrefix(final Collection<DataNode> newListElements) { + if (newListElements.isEmpty()) { + throw new CpsAdminException("Invalid list replacement", + "Cannot replace list elements with empty collection"); + } final String firstChildNodeXpath = newListElements.iterator().next().getXpath(); return firstChildNodeXpath.substring(0, firstChildNodeXpath.lastIndexOf("[") + 1); } 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 index 3150188d0f..41e7a419a5 100755 --- 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 @@ -27,6 +27,7 @@ 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.CpsAdminException import org.onap.cps.spi.exceptions.DataNodeNotFoundException import org.onap.cps.spi.exceptions.DataspaceNotFoundException import org.onap.cps.spi.model.DataNode @@ -35,7 +36,6 @@ import org.onap.cps.utils.JsonObjectMapper import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.jdbc.Sql import javax.validation.ConstraintViolationException -import java.util.stream.Collectors import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS @@ -57,10 +57,8 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L static final long LIST_DATA_NODE_PARENT201_FRAGMENT_ID = 4206L static final long LIST_DATA_NODE_PARENT203_FRAGMENT_ID = 4214L - static final long LIST_DATA_NODE_PARENT204_FRAGMENT_ID = 4219L - static final long LIST_DATA_NODE_PARENT205_FRAGMENT_ID = 4221L - static final long LIST_DATA_NODE_CHILD202_FRAGMENT_ID = 4204L static final long LIST_DATA_NODE_PARENT202_FRAGMENT_ID = 4211L + static final long PARENT_3_FRAGMENT_ID = 4003L static final DataNode newDataNode = new DataNodeBuilder().build() static DataNode existingDataNode @@ -137,11 +135,11 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 + parentFragment.childFragments.size() == 2 and: 'it still has the old child' - parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath }) + parentFragment.childFragments.find({ it.xpath == expectedExistingChildPath }) and: 'it has the new child' - parentFragment.getChildFragments().find({ it.xpath == newChild.xpath }) + parentFragment.childFragments.find({ it.xpath == newChild.xpath }) } @Sql([CLEAR_DATA, SET_DATA]) @@ -159,16 +157,16 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { @Sql([CLEAR_DATA, SET_DATA]) def 'Add multiple list elements including an element with a child datanode.'() { given: 'two new data nodes for an existing list' - def listElementXpaths = ['/parent-201/child-204[@key="B"]', '/parent-201/child-204[@key="C"]'] + def listElementXpaths = ['/parent-201/child-204[@key="NEW1"]', '/parent-201/child-204[@key="NEW2"]'] def listElements = toDataNodes(listElementXpaths) and: 'a child node for one of the new data nodes' - def childDataNode = buildDataNode('/parent-201/child-204[@key="C"]/grand-child-204[@key2="Z"]', [leave:'value'], []) + def childDataNode = buildDataNode('/parent-201/child-204[@key="NEW1"]/grand-child-204[@key2="NEW1-CHILD"]', [leave:'value'], []) listElements[0].childDataNodes = [childDataNode] when: 'the data nodes (list elements) are added to existing parent node' objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listElements) then: 'new entries successfully persisted, parent node now contains 5 children (2 new + 3 existing before)' def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT201_FRAGMENT_ID) - def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() } + def allChildXpaths = parentFragment.childFragments.collect { it.xpath } assert allChildXpaths.size() == 5 assert allChildXpaths.containsAll(listElementXpaths) and: 'the child node of the new list entry is also present' @@ -190,23 +188,6 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { scenario | parentNodeXpath | listElementXpaths || 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]) @@ -215,10 +196,10 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 + assert result.xpath == XPATH_DATA_NODE_WITH_LEAVES and: 'expected leaves' - assert result.getChildDataNodes().size() == 0 - assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES]) + assert result.childDataNodes.size() == 0 + assertLeavesMaps(result.leaves, expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES]) where: 'the following data is used' scenario | inputXPath 'some xpath' | '/parent-100' @@ -234,12 +215,12 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 + assert result.childDataNodes.size() == 2 + assert mappedResult.get('/parent-100/child-001').childDataNodes.size() == 0 + assert mappedResult.get('/parent-100/child-002').childDataNodes.size() == 1 and: 'extracted leaves maps are matching expected' mappedResult.forEach( - (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath])) + (xPath, dataNode) -> assertLeavesMaps(dataNode.leaves, expectedLeavesByXpathMap[xPath])) where: 'the following data is used' scenario | inputXPath 'some xpath' | '/parent-100' @@ -271,9 +252,9 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { assert updatedLeaves.size() == 1 assert updatedLeaves.'leaf-value' == 'new' and: 'existing child entry remains as is' - def childFragment = updatedFragment.getChildFragments().iterator().next() + def childFragment = updatedFragment.childFragments.iterator().next() def childLeaves = getLeavesMap(childFragment) - assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID + assert childFragment.id == UPDATE_DATA_NODE_SUB_FRAGMENT_ID assert childLeaves.'leaf-value' == 'original' } @@ -302,7 +283,7 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { assert updatedLeaves.size() == 1 assert updatedLeaves.'leaf-value' == 'new' and: 'updated entry has no children' - updatedFragment.getChildFragments().isEmpty() + updatedFragment.childFragments.isEmpty() and: 'previously attached child entry is removed from database' fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty() } @@ -321,8 +302,8 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 childFragment = updatedFragment.childFragments.iterator().next() + childFragment.xpath == '/parent-200/child-201/grand-child' def childLeaves = getLeavesMap(childFragment) assert childLeaves.'leaf-value' == 'original' } @@ -341,8 +322,8 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 childFragment = updatedFragment.childFragments.iterator().next() + childFragment.xpath == '/parent-200/child-201/grand-child' def childLeaves = getLeavesMap(childFragment) assert childLeaves.'leaf-value' == 'new' } @@ -363,8 +344,8 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { 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 childFragment = updatedFragment.childFragments.iterator().next() + childFragment.xpath == '/parent-200/child-201/grand-child-new' def childLeaves = getLeavesMap(childFragment) assert childLeaves.'leaf-value' == 'new' } @@ -385,92 +366,95 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { } @Sql([CLEAR_DATA, SET_DATA]) - def 'Replace list content of #scenario.'() { - given: 'list element as a collection of data nodes' - def listElementCollection = toDataNodes(listElementXpaths) - when: 'list elements are replaced within the existing parent node' - objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, parentXpath, listElementCollection) - then: 'list elements are updated as expected, non-list element remains as is' - def parentFragment = fragmentRepository.getById(listElementFragmentID) - def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() } - assert allChildXpaths.size() == expectedChildXpaths.size() - assert allChildXpaths.containsAll(expectedChildXpaths) - where: 'following parameters were used' - scenario | listElementXpaths | parentXpath | listElementFragmentID || expectedChildXpaths - 'existing list element with non existing key' | ['/parent-201/child-204[@key="B"]'] | '/parent-201' | LIST_DATA_NODE_PARENT201_FRAGMENT_ID || ['/parent-201/child-203', '/parent-201/child-204[@key="B"]'] - 'non existing list element with non existing key' | ['/parent-201/child-205[@key="1"]'] | '/parent-201' | LIST_DATA_NODE_PARENT201_FRAGMENT_ID || ['/parent-201/child-203', '/parent-201/child-204[@key="A"]', '/parent-201/child-204[@key="X"]', '/parent-201/child-205[@key="1"]'] - 'list element with 1 existing key' | ['/parent-201/child-204[@key="X"]'] | '/parent-201' | LIST_DATA_NODE_PARENT201_FRAGMENT_ID || ['/parent-201/child-203', '/parent-201/child-204[@key="X"]'] - 'list element with combined keys' | ['/parent-202/child-205[@key="A"]'] | '/parent-202' | LIST_DATA_NODE_PARENT202_FRAGMENT_ID || ['/parent-202/child-206[@key="A"]', '/parent-202/child-205[@key="A"]'] - 'grandchild list element' | ['/parent-200/child-202/grand-child-202[@key="E"]'] | '/parent-200/child-202' | LIST_DATA_NODE_CHILD202_FRAGMENT_ID || ['/parent-200/child-202/grand-child-202[@key="E"]'] - 'list element with two list elements' | ['/parent-201/child-204[@key="new X"]', '/parent-201/child-204[@key="Y"]'] | '/parent-201' | LIST_DATA_NODE_PARENT201_FRAGMENT_ID || ['/parent-201/child-203', '/parent-201/child-204[@key="new X"]', '/parent-201/child-204[@key="Y"]'] - 'list element with compounded list element' | ['/parent-202/child-205[@key="A" and @key2="B"]'] | '/parent-202' | LIST_DATA_NODE_PARENT202_FRAGMENT_ID || ['/parent-202/child-206[@key="A"]', '/parent-202/child-205[@key="A" and @key2="B"]'] - 'list element with list element with parent with key value' | ['/parent-204[@key="L"]/child-210[@key="N"]'] | '/parent-204[@key="L"]' | LIST_DATA_NODE_PARENT204_FRAGMENT_ID || ['/parent-204[@key="L"]/child-210[@key="N"]'] + def 'Update existing list with #scenario.'() { + given: 'a parent having a list of data nodes containing: #originalKeys (ech list element has a child too)' + def parentXpath = '/parent-3' + if (originalKeys.size() > 0) { + def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'original value', originalKeys, true) + objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes) + } + and: 'each original list element has one child' + def originalParentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID) + originalParentFragment.childFragments.each {assert it.childFragments.size() == 1 } + when: 'it is updated with #scenario' + def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new value', replacementKeys, false) + objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes) + then: 'the result list ONLY contains the expected replacement elements' + def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID) + def allChildXpaths = parentFragment.childFragments.collect { it.xpath } + def expectedListEntriesAfterUpdateAsXpaths = keysToXpaths(parentXpath, replacementKeys) + assert allChildXpaths.size() == replacementKeys.size() + assert allChildXpaths.containsAll(expectedListEntriesAfterUpdateAsXpaths) + and: 'all the list elements have the new values' + assert parentFragment.childFragments.stream().allMatch(childFragment -> childFragment.attributes.contains('new value')) + and: 'there are no more grandchildren as none of the replacement list entries had a child' + parentFragment.childFragments.each {assert it.childFragments.size() == 0 } + where: 'the following replacement lists are applied' + scenario | originalKeys | replacementKeys + 'one existing entry only' | [] | ['NEW'] + 'multiple new entries' | [] | ['NEW1', 'NEW2'] + 'one new entry only (existing entries are deleted)' | ['A', 'B'] | ['NEW1', 'NEW2'] + 'one existing on new entry' | ['A', 'B'] | ['A', 'NEW'] + 'one existing entry only' | ['A', 'B'] | ['A'] } @Sql([CLEAR_DATA, SET_DATA]) - def 'Replace list content that has #scenario'() { - given: 'list element with child list element as a collection of data nodes' - def grandChildDataNodes = toDataNodes(grandChildXpaths) - def listElementCollection = new DataNodeBuilder().withXpath(childXpath).withChildDataNodes(grandChildDataNodes).build() - when: 'list elements replaced within the existing parent node' - objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, parentXpath, [listElementCollection ]) - then: 'list elements are updated as expected with non-list elements remaining as is' - def parentFragment = fragmentRepository.getById(listElementFragmentId) - def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() } - assert allChildXpaths.size() == expectedRemainingChildXpaths.size() - assert allChildXpaths.containsAll(expectedRemainingChildXpaths) - and: 'grandchild list elements are updated as expected' - def allGrandChildXpaths = parentFragment.getChildFragments().collect(){ - it.getChildFragments().collect(){ - it.getXpath()}} - allGrandChildXpaths.removeIf(list -> list.isEmpty()) - def grandChildXpathsToList = allGrandChildXpaths.stream().flatMap(List::stream).collect(Collectors.toList()) - def expectedGrandChildXpaths = grandChildXpaths - assert grandChildXpathsToList.size() == expectedGrandChildXpaths.size() - assert grandChildXpathsToList.containsAll(expectedGrandChildXpaths) - where: 'the following parameters are used' - scenario | parentXpath | childXpath | grandChildXpaths | listElementFragmentId || expectedRemainingChildXpaths - 'grandchild of list' | '/parent-203' | '/parent-203/child-204[@key="X"]' | ['/parent-203/child-204/grandchild[@key="2"]'] | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="X"]'] - 'grandchild of list with two new element' | '/parent-203' | '/parent-203/child-204[@key="X"]' | ['/parent-203/child-204/grandchild[@key="2"]' , '/parent-203/child-204/grandchild[@key="3"]'] | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="X"]'] - 'grandchild with compound list elements' | '/parent-205' | '/parent-205/child-205[@key="X"]' | ['/parent-205/child-205/grand-child-206[@key="Y" and @key2="Z"]'] | LIST_DATA_NODE_PARENT205_FRAGMENT_ID || ['/parent-205/child-205', '/parent-205/child-205[@key="X"]'] + def 'Replacing existing list element with attributes and (grand)child.'() { + given: 'a parent with list elements A and B with attribute and grandchild tagged as "org"' + def parentXpath = '/parent-3' + def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'org', ['A','B'], true) + objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes) + when: 'A is replaced with an entry with attribute and grandchild tagged tagged as "new" (B is not in replacement list)' + def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new', ['A'], true) + objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes) + then: 'The updated fragment has a child-list with ONLY element "A"' + def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID) + parentFragment.childFragments.size() == 1 + def childListElementA = parentFragment.childFragments[0] + childListElementA.xpath == "/parent-3/child-list[@key='A']" + and: 'element "A" has an attribute with the "new" (tag) value' + childListElementA.attributes == '{"attr1": "new"}' + and: 'element "A" has a only one (grand)child' + childListElementA.childFragments.size() == 1 + and: 'the grandchild is the new grandchild (tag)' + def grandChild = childListElementA.childFragments[0] + grandChild.xpath == "/parent-3/child-list[@key='A']/new-grand-child" + and: 'the grandchild has an attribute with the "new" (tag) value' + grandChild.attributes == '{"attr1": "new"}' } @Sql([CLEAR_DATA, SET_DATA]) - def 'Replace list content of #scenario with grandchildren.'() { - given: 'list element as a collection of data nodes' - def listElementCollection = toDataNodes(listElementXpaths) - when: 'list elements are replaced within the existing parent node' - objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, parentXpath, listElementCollection) - then: 'child list elements are updated as expected with non-list elements remaining as is' - def parentFragment = fragmentRepository.getById(listElementFragmentID) - def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() } - assert allChildXpaths.size() == expectedChildXpaths.size() - assert allChildXpaths.containsAll(expectedChildXpaths) - and: 'grandchild list elements are updated as expected' - def allGrandChildXpaths = parentFragment.getChildFragments().collect { - it.getChildFragments().collect { - it.getXpath()}} - allGrandChildXpaths.removeIf(list -> list.isEmpty()) - assert allGrandChildXpaths.size() == expectedGrandChildXpaths.size() - assert allGrandChildXpaths.containsAll(expectedGrandChildXpaths) - where: 'following parameters were used' - scenario | listElementXpaths | parentXpath | listElementFragmentID || expectedChildXpaths | expectedGrandChildXpaths - 'existing list element with existing keys' | ['/parent-203/child-204[@key="X"]'] | '/parent-203' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="X"]'] | [] - 'non existing list element with existing keys' | ['/parent-203/child-204[@key="V"]'] | '/parent-203' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="V"]'] | [] + def 'Replace list element for a parent (parent-1) with existing one (non-list) child'() { + when: 'a list element is added under the parent' + def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(XPATH_DATA_NODE_WITH_DESCENDANTS, 'new', ['A','B'], false) + objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, replacementListEntriesAsDataNodes) + then: 'the parent will have 3 children after the replacement' + def parentFragment = fragmentRepository.getById(ID_DATA_NODE_WITH_DESCENDANTS) + parentFragment.childFragments.size() == 3 + def xpaths = parentFragment.childFragments.collect {it.xpath} + and: 'one of the children is the original child fragment' + xpaths.contains('/parent-1/child-1') + and: 'it has the two new list elements' + xpaths.containsAll("/parent-1/child-list[@key='A']", "/parent-1/child-list[@key='B']") } - @Sql([CLEAR_DATA, SET_DATA]) - def 'Replace content error scenario: #scenario.'() { + def 'Replace list content using unknown parent'() { given: 'list element as a collection of data nodes' - def listElementCollection = toDataNodes(listElementXpaths) - when: 'list elements were replaced under existing parent node' - objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listElementCollection) - then: 'a #expectedException is thrown' - thrown(expectedException) - where: 'following parameters were used' - scenario | parentNodeXpath | listElementXpaths || expectedException - 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException + def listElementCollection = toDataNodes(['irrelevant']) + when: 'attempt to replace list elements under unknown parent node' + objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/unknown', listElementCollection) + then: 'a datanode not found exception is thrown' + thrown(DataNodeNotFoundException) + } + + @Sql([CLEAR_DATA, SET_DATA]) + def 'Replace list content with empty collection is not supported'() { + when: 'attempt to replace list elements with empty collection' + objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/parent-203', []) + then: 'a CPS admin exception is thrown' + def thrown = thrown(CpsAdminException) + assert thrown.message == 'Invalid list replacement' } @Sql([CLEAR_DATA, SET_DATA]) @@ -479,15 +463,15 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths) then: 'only the expected children remain' def parentFragment = fragmentRepository.getById(parentFragmentId) - def remainingChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() } + def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath } assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size() assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths) where: 'following parameters were used' scenario | targetXpaths | parentFragmentId || expectedRemainingChildXpaths - 'list element with key' | '/parent-203/child-204[@key="A"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="X"]'] + 'list element with key' | '/parent-203/child-204[@key="A"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="B"]'] 'list element with combined keys' | '/parent-202/child-205[@key="A" and @key2="B"]' | LIST_DATA_NODE_PARENT202_FRAGMENT_ID || ['/parent-202/child-206[@key="A"]'] 'whole list' | '/parent-203/child-204' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203'] - 'list element under list element' | '/parent-203/child-204[@key="X"]/grand-child-204[@key2="Y"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="X"]', '/parent-203/child-204[@key="A"]'] + 'list element under list element' | '/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203', '/parent-203/child-204[@key="A"]', '/parent-203/child-204[@key="B"]'] } @Sql([CLEAR_DATA, SET_DATA]) @@ -516,7 +500,7 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { then: 'verify data nodes are removed' try { dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, getDataNodesXpaths, INCLUDE_ALL_DESCENDANTS) - dataNodeXpath = dataNode.getXpath() + dataNodeXpath = dataNode.xpath assert dataNodeXpath == expectedXpaths } catch (DataNodeNotFoundException) { assert dataNodeXpath == expectedXpaths @@ -564,7 +548,7 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { } static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) { - return jsonObjectMapper.convertJsonString(fragmentEntity.getAttributes(), Map<String, Object>.class) + return jsonObjectMapper.convertJsonString(fragmentEntity.attributes, Map<String, Object>.class) } def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) { @@ -581,10 +565,51 @@ class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase { } def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) { - flatMap.put(dataNodeTree.getXpath(), dataNodeTree) - dataNodeTree.getChildDataNodes() + flatMap.put(dataNodeTree.xpath, dataNodeTree) + dataNodeTree.childDataNodes .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode)) return flatMap } + def keysToXpaths(parent, Collection keys) { + return keys.collect { "${parent}/child-list[@key='${it}']".toString() } + } + + def static 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() + } + + + def createChildListAllHavingAttributeValue(parentXpath, tag, Collection keys, boolean addGrandChild) { + def listElementAsDataNodes = keysToXpaths(parentXpath, keys).collect { + new DataNodeBuilder() + .withXpath(it) + .withLeaves([attr1: tag]) + .build() + } + if (addGrandChild) { + listElementAsDataNodes.each {it.childDataNodes = [createGrandChild(it.xpath, tag)]} + } + return listElementAsDataNodes + } + + def createGrandChild(parentXPath, tag) { + new DataNodeBuilder() + .withXpath("${parentXPath}/${tag}-grand-child") + .withLeaves([attr1: tag]) + .build() + } + } diff --git a/cps-ri/src/test/resources/data/fragment.sql b/cps-ri/src/test/resources/data/fragment.sql index 5d3a328327..49c4c9f3ee 100755 --- a/cps-ri/src/test/resources/data/fragment.sql +++ b/cps-ri/src/test/resources/data/fragment.sql @@ -48,29 +48,20 @@ INSERT INTO FRAGMENT (ID, DATASPACE_ID, ANCHOR_ID, PARENT_ID, XPATH, ATTRIBUTES) (4201, 1001, 3003, null, '/parent-200', '{"leaf-value": "original"}'), (4202, 1001, 3003, 4201, '/parent-200/child-201', '{"leaf-value": "original"}'), (4203, 1001, 3003, 4202, '/parent-200/child-201/grand-child', '{"leaf-value": "original"}'), - (4204, 1001, 3003, 4201, '/parent-200/child-202', '{"common-leaf-name": "common-leaf value", "common-leaf-name-int" : 5}'), - (4205, 1001, 3003, 4204, '/parent-200/child-202/grand-child-202[@key="D"]', '{"common-leaf-name": "common-leaf value", "common-leaf-name-int" : 5}'), (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"}'), + (4209, 1001, 3003, 4206, '/parent-201/child-204[@key="B"]', '{"key": "B"}'), (4211, 1001, 3003, null, '/parent-202', '{"leaf-value": "original"}'), (4212, 1001, 3003, 4211, '/parent-202/child-205[@key="A" and @key2="B"]', '{"key": "A", "key2": "B"}'), (4213, 1001, 3003, 4211, '/parent-202/child-206[@key="A"]', '{"key": "A"}'), (4214, 1001, 3003, null, '/parent-203', '{"leaf-value": "original"}'), (4215, 1001, 3003, 4214, '/parent-203/child-203', '{}'), (4216, 1001, 3003, 4214, '/parent-203/child-204[@key="A"]', '{"key": "A"}'), - (4217, 1001, 3003, 4214, '/parent-203/child-204[@key="X"]', '{"key": "X"}'), - (4218, 1001, 3003, 4217, '/parent-203/child-204[@key="X"]/grand-child-204[@key2="Y"]', '{"key": "X", "key2": "Y"}'), - (4219, 1001, 3003, null, '/parent-204[@key="L"]', '{"key": "L"}'), - (4220, 1001, 3003, 4219, '/parent-204[@key="L"]/child-210[@key="M"]', '{"key": "M"}'), - (4221, 1001, 3003, null, '/parent-205', '{"leaf-value": "original"}'), - (4222, 1001, 3003, 4221, '/parent-205/child-205', '{}'), - (4223, 1001, 3003, 4221, '/parent-205/child-205[@key="X"]', '{"key": "X"}'), - (4224, 1001, 3003, 4223, '/parent-205/child-205[@key="X"]/grand-child-206[@key="Y"]', '{"key": "Y", "key2": "Z"}'), - (4225, 1001, 3003, 4223, '/parent-205/child-205[@key="X"]/grand-child-206[@key="Y" and @key2="Z"]', '{"key": "Y", "key2": "Z"}'), + (4217, 1001, 3003, 4214, '/parent-203/child-204[@key="B"]', '{"key": "B"}'), + (4218, 1001, 3003, 4217, '/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]', '{"key": "B", "key2": "Y"}'), (4226, 1001, 3003, null, '/parent-206', '{"leaf-value": "original"}'), (4227, 1001, 3003, 4226, '/parent-206/child-206', '{}'), (4228, 1001, 3003, 4227, '/parent-206/child-206/grand-child-206', '{}'), (4229, 1001, 3003, 4227, '/parent-206/child-206/grand-child-206[@key="A"]', '{"key": "A"}'), - (4230, 1001, 3003, 4227, '/parent-206/child-206/grand-child-206[@key="X"]', '{"key": "X"}');
\ No newline at end of file + (4230, 1001, 3003, 4227, '/parent-206/child-206/grand-child-206[@key="X"]', '{"key": "X"}'); |