From acc4d6d34012c8a77a8257a0fbc10ecd7276bc64 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 7 Apr 2021 16:54:20 +0100 Subject: [PATCH 01/31] RDCC-2391: adding API & Swagger components to Controller --- .../CaseWorkerRefUsersController.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index 6bc0bfafd..b1024befc 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -10,17 +10,23 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import uk.gov.hmcts.reform.cwrdapi.controllers.advice.InvalidRequestException; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfileCreationResponse; +import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfilesDeletionResponse; import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerProfile; import uk.gov.hmcts.reform.cwrdapi.service.CaseWorkerService; @@ -29,6 +35,7 @@ import static java.lang.String.format; import static org.apache.commons.lang3.ObjectUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.BAD_REQUEST; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.FORBIDDEN_ERROR; @@ -182,4 +189,62 @@ public ResponseEntity fetchCaseworkersById(@RequestBody UserRequest user } + @ApiOperation(value = "Delete Case Worker Profiles by User ID or Email Pattern", + authorizations = { + @Authorization(value = "ServiceAuthorization"), + @Authorization(value = "Authorization") + }) + @ApiResponses({ + @ApiResponse( + code = 204, + message = "Case Worker Profiles deleted successfully", + response = CaseWorkerProfilesDeletionResponse.class + ), + @ApiResponse( + code = 400, + message = "An invalid request has been provided" + ), + @ApiResponse( + code = 401, + message = "Unauthorized Error : The requested resource is restricted and requires authentication" + ), + @ApiResponse( + code = 403, + message = "Forbidden Error: Access denied" + ), + @ApiResponse( + code = 500, + message = "Internal Server Error" + ) + }) + + @DeleteMapping( + path = "/users", + produces = APPLICATION_JSON_VALUE + ) + @ResponseStatus(value = HttpStatus.NO_CONTENT) + @ResponseBody + public ResponseEntity deleteCaseWorkerProfileByIdOrEmailPattern( + @RequestParam(value = "userId", required = false) String userId, + @RequestParam(value = "emailPattern", required = false) String emailPattern) { + + /** + * This API will need to be revisited if it is to be used for business functionality. + */ + + CaseWorkerProfilesDeletionResponse resource; + + if (isNotBlank(userId)) { + resource = caseWorkerService.deleteByUserId(userId); + + } else if (isNotBlank(emailPattern)) { + resource = caseWorkerService.deleteByEmailPattern(emailPattern); + + } else { + throw new InvalidRequestException("No User ID or Email Pattern provided to delete the User(s)"); + } + + return ResponseEntity.status(resource.getStatusCode()).body(resource); + } + } From ccedac2b3d5ee7de1b529590c729182e34a5f978 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Fri, 9 Apr 2021 16:03:38 +0100 Subject: [PATCH 02/31] RDCC-2390: adding Functional Tests --- .../cwrdapi/CaseWorkerRefFunctionalTest.java | 79 ++++++++++++++++++- .../cwrdapi/client/CaseWorkerApiClient.java | 15 ++++ 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java index 23677a345..874cc3f72 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java @@ -46,10 +46,13 @@ import static java.lang.String.format; import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.codehaus.groovy.runtime.InvokerHelper.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.springframework.http.HttpStatus.FORBIDDEN; +import static org.springframework.http.HttpStatus.NO_CONTENT; import static org.springframework.util.ResourceUtils.getFile; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.RECORDS_UPLOADED; @@ -68,8 +71,10 @@ public class CaseWorkerRefFunctionalTest extends AuthorizationFunctionalTest { public static final String CREATE_CASEWORKER_PROFILE = "CaseWorkerRefUsersController.createCaseWorkerProfiles"; public static final String FETCH_BY_CASEWORKER_ID = "CaseWorkerRefUsersController.fetchCaseworkersById"; - public static List caseWorkerIds = new ArrayList<>(); public static final String CASEWORKER_FILE_UPLOAD = "CaseWorkerRefController.caseWorkerFileUpload"; + public static final String DELETE_CASEWORKER_BY_ID_OR_EMAILPATTERN = + "CaseWorkerRefController.deleteCaseWorkerProfileByIdOrEmailPattern"; + public static List caseWorkerIds = new ArrayList<>(); @Test @ToggleEnable(mapKey = CREATE_CASEWORKER_PROFILE, withFeature = true) @@ -260,7 +265,7 @@ public void should_retrieve_403_when_Api_toggled_off() { } @Test - // this test verifies User profile are fetched from CWR when id matched what given in request rest should be ignored + //this test verifies User profile are fetched from CWR when id matched what given in request rest should be ignored @ToggleEnable(mapKey = FETCH_BY_CASEWORKER_ID, withFeature = true) public void shouldGetOnlyFewCaseWorkerDetails() { if (isEmpty(caseWorkerIds)) { @@ -414,6 +419,76 @@ public void shouldReturn403WhenUploadFileApiToggledOff() throws IOException { TYPE_XLSX, ROLE_CWD_ADMIN); } + @Test + @ToggleEnable(mapKey = DELETE_CASEWORKER_BY_ID_OR_EMAILPATTERN, withFeature = true) + //this test verifies that a User Profile is deleted by ID + public void deleteCaseworkerById() { + List caseWorkersProfileCreationRequests = + caseWorkerApiClient.createCaseWorkerProfiles(); + + // create user + Response createResponse = caseWorkerApiClient.createUserProfiles(caseWorkersProfileCreationRequests); + + CaseWorkerProfileCreationResponse caseWorkerProfileCreationResponse = + createResponse.getBody().as(CaseWorkerProfileCreationResponse.class); + + List caseWorkerIds = caseWorkerProfileCreationResponse.getCaseWorkerIds(); + assertEquals(caseWorkersProfileCreationRequests.size(), caseWorkerIds.size()); + + //delete user + caseWorkerApiClient.deleteCaseworkerByIdOrEmailPattern( + "/refdata/case-worker/users?userId=" + caseWorkerIds.get(0), NO_CONTENT); + + //search for deleted user + Response fetchResponse = caseWorkerApiClient.getMultipleAuthHeadersInternal(ROLE_CWD_SYSTEM_USER) + .body(UserRequest.builder().userIds(caseWorkerIds).build()) + .post("/refdata/case-worker/users/fetchUsersById/") + .andReturn(); + + //assert that delete user is not found + assertThat(fetchResponse.getStatusCode()).isEqualTo(404); + } + + @Test + @ToggleEnable(mapKey = DELETE_CASEWORKER_BY_ID_OR_EMAILPATTERN, withFeature = true) + //this test verifies that a User Profile is deleted by Email Pattern + public void deleteCaseworkerByEmailPattern() { + String emailPattern = "deleteTest1234"; + String email = format(EMAIL_TEMPLATE, randomAlphanumeric(10) + emailPattern).toLowerCase(); + + List caseWorkersProfileCreationRequests = + caseWorkerApiClient.createCaseWorkerProfiles(email); + + // create user with email pattern + Response createResponse = caseWorkerApiClient.createUserProfiles(caseWorkersProfileCreationRequests); + + CaseWorkerProfileCreationResponse caseWorkerProfileCreationResponse = + createResponse.getBody().as(CaseWorkerProfileCreationResponse.class); + + List caseWorkerIds = caseWorkerProfileCreationResponse.getCaseWorkerIds(); + assertEquals(caseWorkersProfileCreationRequests.size(), caseWorkerIds.size()); + + //delete user by email pattern + caseWorkerApiClient.deleteCaseworkerByIdOrEmailPattern( + "/refdata/case-worker/users?emailPattern=" + emailPattern, NO_CONTENT); + + //search for deleted user + Response fetchResponse = caseWorkerApiClient.getMultipleAuthHeadersInternal(ROLE_CWD_SYSTEM_USER) + .body(UserRequest.builder().userIds(caseWorkerIds).build()) + .post("/refdata/case-worker/users/fetchUsersById/") + .andReturn(); + + //assert that delete user is not found + assertThat(fetchResponse.getStatusCode()).isEqualTo(404); + } + + @Test + @ToggleEnable(mapKey = DELETE_CASEWORKER_BY_ID_OR_EMAILPATTERN, withFeature = false) + public void deleteCaseworkerReturns403WhenToggledOff() { + caseWorkerApiClient.deleteCaseworkerByIdOrEmailPattern( + "/refdata/case-worker/users?emailPattern=ForbiddenException", FORBIDDEN); + } + private ExtractableResponse uploadCaseWorkerFile(String filePath, int statusCode, String messageBody, diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/client/CaseWorkerApiClient.java b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/client/CaseWorkerApiClient.java index 5daf8258c..0f4d8b57d 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/client/CaseWorkerApiClient.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/client/CaseWorkerApiClient.java @@ -5,6 +5,7 @@ import io.restassured.specification.RequestSpecification; import lombok.extern.slf4j.Slf4j; import net.serenitybdd.rest.SerenityRest; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerLocationRequest; @@ -182,4 +183,18 @@ public Response createUserProfiles(List caseW return response; } + + public Response deleteCaseworkerByIdOrEmailPattern(String path, HttpStatus statusCode) { + Response response = getMultipleAuthHeadersInternal() + .delete(path) + .andReturn(); + + log.info(":: delete user profile response status code :: " + response.statusCode()); + + response.then() + .assertThat() + .statusCode(statusCode.value()); + + return response; + } } \ No newline at end of file From 728711ab18a7f7d8cdf052792315d21c5261c7ab Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:16:57 +0100 Subject: [PATCH 03/31] RDCC-2391: adding Integration Tests --- ...leteCaseWorkerProfilesIntegrationTest.java | 127 ++++++++++++++++++ .../AuthorizationEnabledIntegrationTest.java | 12 ++ .../util/CaseWorkerReferenceDataClient.java | 66 +++++++-- 3 files changed, 193 insertions(+), 12 deletions(-) create mode 100644 src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/DeleteCaseWorkerProfilesIntegrationTest.java diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/DeleteCaseWorkerProfilesIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/DeleteCaseWorkerProfilesIntegrationTest.java new file mode 100644 index 000000000..74646e520 --- /dev/null +++ b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/DeleteCaseWorkerProfilesIntegrationTest.java @@ -0,0 +1,127 @@ +package uk.gov.hmcts.reform.cwrdapi; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerLocationRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerRoleRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerWorkAreaRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; +import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerProfile; +import uk.gov.hmcts.reform.cwrdapi.repository.CaseWorkerProfileRepository; +import uk.gov.hmcts.reform.cwrdapi.util.AuthorizationEnabledIntegrationTest; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DeleteCaseWorkerProfilesIntegrationTest extends AuthorizationEnabledIntegrationTest { + + List caseWorkersProfileCreationRequests; + + @Autowired + CaseWorkerProfileRepository caseWorkerProfileRepository; + + @Before + public void setUp() { + + super.setUpClient(); + + //Set up Case worker data + Set roles = ImmutableSet.of(" tribunal_case_worker "); + List caseWorkerRoleRequests = + ImmutableList.of(CaseWorkerRoleRequest.caseWorkerRoleRequest() + .role(" role ").isPrimaryFlag(true).build()); + + List caseWorkerLocationRequests = ImmutableList.of(CaseWorkerLocationRequest + .caseWorkersLocationRequest() + .isPrimaryFlag(true).locationId(1) + .location(" location ").build()); + + List caseWorkerAreaRequests = ImmutableList.of(CaseWorkerWorkAreaRequest + .caseWorkerWorkAreaRequest() + .areaOfWork(" areaOfWork ").serviceCode(" serviceCode ") + .build()); + + caseWorkersProfileCreationRequests = ImmutableList.of(CaseWorkersProfileCreationRequest + .caseWorkersProfileCreationRequest() + .firstName(" firstName ").lastName(" lastName ").emailId("test.inttest@hmcts.gov.uk") + .regionId(1).userType("CTSC") + .region("region").suspended(false).roles(caseWorkerRoleRequests).idamRoles(roles) + .baseLocations(caseWorkerLocationRequests).workerWorkAreaRequests(caseWorkerAreaRequests).build()); + } + + @Test + public void deleteCaseWorkerProfileById() { + userProfileCreateUserWireMock(HttpStatus.CREATED); + + //Create User + Map createResponse = caseworkerReferenceDataClient + .createCaseWorkerProfile(caseWorkersProfileCreationRequests, "cwd-admin"); + + assertThat(createResponse).containsEntry("http_status", "201 CREATED"); + + CaseWorkerProfile createdProfile = caseWorkerProfileRepository.findByEmailId("test.inttest@hmcts.gov.uk"); + + //Check Created User Exists + assertThat(createdProfile).isNotNull(); + + userProfileDeleteUserWireMock(); + + //Delete User By User ID + Map deleteResponse = caseworkerReferenceDataClient + .deleteCaseWorker("/users?userId=" + createdProfile.getCaseWorkerId()); + + assertThat(deleteResponse).containsEntry("status", "204 NO_CONTENT"); + + Optional deletedProfile = + caseWorkerProfileRepository.findByCaseWorkerId(createdProfile.getCaseWorkerId()); + + //Check Deleted User Does Not Exist + assertThat(deletedProfile).isEmpty(); + } + + @Test + public void deleteCaseWorkerProfileByEmailPattern() { + userProfileCreateUserWireMock(HttpStatus.CREATED); + + //Create User + Map createResponse = caseworkerReferenceDataClient + .createCaseWorkerProfile(caseWorkersProfileCreationRequests, "cwd-admin"); + + assertThat(createResponse).containsEntry("http_status", "201 CREATED"); + + CaseWorkerProfile createdProfile = caseWorkerProfileRepository.findByEmailId("test.inttest@hmcts.gov.uk"); + + //Check Created User Exists + assertThat(createdProfile).isNotNull(); + + userProfileDeleteUserWireMock(); + + //Delete User By Email Pattern + Map deleteResponse = caseworkerReferenceDataClient + .deleteCaseWorker("/users?emailPattern=" + "test.inttest"); + + assertThat(deleteResponse).containsEntry("status", "204 NO_CONTENT"); + + CaseWorkerProfile deletedProfile = caseWorkerProfileRepository.findByEmailId("test.inttest@hmcts.gov.uk"); + + //Check Deleted User Does Not Exist + assertThat(deletedProfile).isNull(); + } + + @Test + public void deleteCaseWorkerProfileByEmailPattern_Returns404WhenNoUsersFoundWithGivenEmailPattern() { + //Delete User By Email Pattern + Map deleteResponse = caseworkerReferenceDataClient + .deleteCaseWorker("/users?emailPattern=" + "INVALID"); + + assertThat(deleteResponse).containsEntry("http_status", "404"); + } +} diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/AuthorizationEnabledIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/AuthorizationEnabledIntegrationTest.java index c0482f1fd..ab7e8c48e 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/AuthorizationEnabledIntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/AuthorizationEnabledIntegrationTest.java @@ -37,6 +37,7 @@ import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; @@ -161,6 +162,17 @@ public void userProfileGetUserWireMock(String idamStatus, String roles) { + "}"))); } + public void userProfileDeleteUserWireMock() { + userProfileService.stubFor(delete(urlPathMatching("/v1/userprofile/users.*")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withStatus(204) + .withBody("{" + + " \"response\": \"UserProfile Successfully Deleted.\"" + + "}"))); + + } + public void modifyUserRoles() throws Exception { UserProfileRolesResponse userProfileRolesResponse = new UserProfileRolesResponse(); diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerReferenceDataClient.java b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerReferenceDataClient.java index 18e3d9fd0..12e2fd8a5 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerReferenceDataClient.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerReferenceDataClient.java @@ -27,6 +27,7 @@ import java.util.Objects; import java.util.UUID; +import static org.springframework.http.HttpMethod.DELETE; import static org.springframework.http.MediaType.APPLICATION_JSON; import static uk.gov.hmcts.reform.cwrdapi.util.JwtTokenUtil.generateToken; @@ -63,6 +64,10 @@ public Map createCaseWorkerProfile(List deleteCaseWorker(String path) { + return deleteRequest(baseUrl + path, null); + } + public Map createIdamRolesAssoc(List serviceRoleMapping, String role) { return postRequest(baseUrl + "/idam-roles-mapping/", serviceRoleMapping, role, null); } @@ -73,7 +78,7 @@ public Map uploadCwFile(MultiValueMap body, httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity> request = - new HttpEntity<>(body, httpHeaders); + new HttpEntity<>(body, httpHeaders); return sendRequest(uriPath, request); } @@ -85,15 +90,22 @@ private Map postRequest(String uriPath, T requestBody, Strin return sendRequest(uriPath, request); } + private Map deleteRequest(String uriPath, String role) { + + HttpEntity request = new HttpEntity<>(null, getMultipleAuthHeaders(role, null)); + + return sendDeleteRequest(uriPath, request); + } + private Map sendRequest(String uriPath, HttpEntity request) { ResponseEntity responseEntity; try { responseEntity = restTemplate.postForEntity( - uriPath, - request, - Map.class); + uriPath, + request, + Map.class); } catch (RestClientResponseException ex) { HashMap statusAndBody = new HashMap<>(2); @@ -105,6 +117,27 @@ private Map sendRequest(String uriPath, HttpEntity reques return getResponse(responseEntity); } + private Map sendDeleteRequest(String uriPath, HttpEntity request) { + ResponseEntity responseEntity; + + try { + + responseEntity = restTemplate.exchange( + uriPath, + DELETE, + request, + Map.class); + + } catch (RestClientResponseException ex) { + HashMap statusAndBody = new HashMap<>(2); + statusAndBody.put("http_status", String.valueOf(ex.getRawStatusCode())); + statusAndBody.put("response_body", ex.getResponseBodyAsString()); + return statusAndBody; + } + + return getDeleteResponse(responseEntity); + } + private HttpHeaders getMultipleAuthHeaders(String role, String userId) { HttpHeaders headers = new HttpHeaders(); @@ -118,7 +151,7 @@ private HttpHeaders getMultipleAuthHeaders(String role, String userId) { if (StringUtils.isBlank(bearerToken)) { bearerToken = "Bearer ".concat(getBearerToken(Objects.isNull(userId) ? UUID.randomUUID().toString() - : userId, role)); + : userId, role)); } headers.add("Authorization", bearerToken); @@ -133,9 +166,9 @@ private HttpHeaders getMultipleAuthHeaders(String role) { private Map getResponse(ResponseEntity responseEntity) { Map response = objectMapper - .convertValue( - responseEntity.getBody(), - Map.class); + .convertValue( + responseEntity.getBody(), + Map.class); response.put("http_status", responseEntity.getStatusCode().toString()); response.put("headers", responseEntity.getHeaders().toString()); @@ -143,16 +176,25 @@ private Map getResponse(ResponseEntity responseEntity) { return response; } + private Map getDeleteResponse(ResponseEntity responseEntity) { + + Map response = new HashMap<>(); + + response.put("status", responseEntity.getStatusCode().toString()); + response.put("headers", responseEntity.getHeaders().toString()); + return response; + } + private final String getBearerToken(String userId, String role) { return generateToken(issuer, expiration, userId, role); } public static String generateS2SToken(String serviceName) { return Jwts.builder() - .setSubject(serviceName) - .setIssuedAt(new Date()) - .signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.encode("AA")) - .compact(); + .setSubject(serviceName) + .setIssuedAt(new Date()) + .signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.encode("AA")) + .compact(); } public static void setBearerToken(String bearerToken) { From de97293a9f19125b1634d2eaffb856c98b57b6bd Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:17:31 +0100 Subject: [PATCH 04/31] RDCC-2390: adding CaseWorkerProfilesDeletionResponse class --- .../CaseWorkerProfilesDeletionResponse.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/response/CaseWorkerProfilesDeletionResponse.java diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/response/CaseWorkerProfilesDeletionResponse.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/response/CaseWorkerProfilesDeletionResponse.java new file mode 100644 index 000000000..acf89f4e6 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/response/CaseWorkerProfilesDeletionResponse.java @@ -0,0 +1,20 @@ +package uk.gov.hmcts.reform.cwrdapi.controllers.response; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class CaseWorkerProfilesDeletionResponse { + + private int statusCode; + private String message; + + public CaseWorkerProfilesDeletionResponse(int statusCode, String message) { + this.statusCode = statusCode; + this.message = message; + + } +} From c64521e0c0d050de910fad77c7c64129e8b0a1ac Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:18:01 +0100 Subject: [PATCH 05/31] RDCC-2390: adding service methods to interface --- .../cwrdapi/service/CaseWorkerService.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/CaseWorkerService.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/CaseWorkerService.java index 71d357705..553e13a46 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/CaseWorkerService.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/CaseWorkerService.java @@ -4,6 +4,7 @@ import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.cwrdapi.client.domain.ServiceRoleMapping; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfilesDeletionResponse; import uk.gov.hmcts.reform.cwrdapi.controllers.response.IdamRolesMappingResponse; import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerProfile; @@ -37,5 +38,21 @@ List processCaseWorkerProfiles(List fetchCaseworkersById(List caseWorkerIds); + + /** + * Deletes a caseworker by their ID. + * + * @param userId String + * @return CaseWorkerProfilesDeletionResponse + */ + CaseWorkerProfilesDeletionResponse deleteByUserId(String userId); + + /** + * Deletes caseworkers by associated email pattern. + * + * @param emailPattern String + * @return CaseWorkerProfilesDeletionResponse + */ + CaseWorkerProfilesDeletionResponse deleteByEmailPattern(String emailPattern); } From a4d5eb7b18c37b5371a8c06f2ba545349d0bd187 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:18:21 +0100 Subject: [PATCH 06/31] RDCC-2390: adding implementation of new service methods --- .../service/impl/CaseWorkerServiceImpl.java | 300 +++++++++++------- 1 file changed, 186 insertions(+), 114 deletions(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java index 9935c01ab..376121658 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java @@ -8,6 +8,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.reform.cwrdapi.client.domain.Location; import uk.gov.hmcts.reform.cwrdapi.client.domain.Role; import uk.gov.hmcts.reform.cwrdapi.client.domain.ServiceRoleMapping; @@ -24,6 +25,7 @@ import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserCategory; import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserProfileCreationRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserTypeRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfilesDeletionResponse; import uk.gov.hmcts.reform.cwrdapi.controllers.response.IdamRolesMappingResponse; import uk.gov.hmcts.reform.cwrdapi.controllers.response.UserProfileCreationResponse; import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerIdamRoleAssociation; @@ -66,6 +68,7 @@ import static java.lang.String.format; import static java.lang.String.valueOf; import static java.lang.System.currentTimeMillis; +import static java.util.Collections.singletonList; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static java.util.Objects.requireNonNull; @@ -75,6 +78,8 @@ import static net.logstash.logback.encoder.org.apache.commons.lang3.BooleanUtils.isTrue; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; import static org.springframework.http.HttpStatus.CONFLICT; +import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.NO_CONTENT; import static org.springframework.util.CollectionUtils.isEmpty; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.ALREADY_SUSPENDED_ERROR_MESSAGE; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.IDAM_STATUS_SUSPENDED; @@ -150,13 +155,13 @@ public List processCaseWorkerProfiles(List processCaseWorkerProfiles(List processCaseWorkerProfiles(List persistCaseWorkerInBatch(List long time1 = currentTimeMillis(); processedCwProfiles = caseWorkerProfileRepo.saveAll(newCaseWorkerProfiles); log.info("{}:: {} case worker profiles inserted :: Job Id {}", loggingComponentName, - processedCwProfiles.size(), validationServiceFacade.getAuditJobId()); + processedCwProfiles.size(), validationServiceFacade.getAuditJobId()); log.info("{}::Time taken to save caseworker data in CRD is {}", loggingComponentName, - (currentTimeMillis() - time1)); + (currentTimeMillis() - time1)); } return processedCwProfiles; } @@ -241,7 +246,7 @@ public List updateSidamRoles(List updateCa List filteredUpdateCwProfiles = new ArrayList<>(); for (CaseWorkerProfile dbProfile : updateCaseWorkerProfiles) { boolean isAddRoleSuccess = updateUserRolesInIdam(requestMap.get(dbProfile.getEmailId()), - dbProfile.getCaseWorkerId()); + dbProfile.getCaseWorkerId()); if (isAddRoleSuccess) { filteredUpdateCwProfiles.add(dbProfile); } @@ -270,20 +275,21 @@ public IdamRolesMappingResponse buildIdamRoleMappings(List s try { idamRoleMappingService.deleteExistingRecordForServiceCode(serviceCodes); log.info("{}::" + CaseWorkerConstants.DELETE_RECORD_FOR_SERVICE_ID + " ::{}", loggingComponentName, - serviceCodes.toString()); + serviceCodes.toString()); idamRoleMappingService.buildIdamRoleAssociation(caseWorkerIdamRoleAssociations); log.info("{}::" + CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + "::{}", loggingComponentName, - serviceCodes.toString()); + serviceCodes.toString()); return IdamRolesMappingResponse.builder() - .message(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCodes.toString()) - .statusCode(HttpStatus.CREATED.value()) - .build(); + .message(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCodes.toString()) + .statusCode(HttpStatus.CREATED.value()) + .build(); } catch (Exception e) { log.error("{}::" + CaseWorkerConstants.IDAM_ROLE_MAPPINGS_FAILURE + " ::{}:: Job Id {}::Reason:: {}", - loggingComponentName, serviceCodes.toString(), validationServiceFacade.getAuditJobId(), e.getMessage()); + loggingComponentName, serviceCodes.toString(), validationServiceFacade.getAuditJobId(), + e.getMessage()); throw new IdamRolesMappingException(e.getMessage()); } } @@ -296,8 +302,8 @@ public IdamRolesMappingResponse buildIdamRoleMappings(List s @Override public void publishCaseWorkerDataToTopic(List caseWorkerData) { List caseWorkerIds = caseWorkerData.stream() - .map(CaseWorkerProfile::getCaseWorkerId) - .collect(Collectors.toUnmodifiableList()); + .map(CaseWorkerProfile::getCaseWorkerId) + .collect(Collectors.toUnmodifiableList()); topicPublisher.sendMessage(caseWorkerIds); } @@ -316,36 +322,36 @@ public ResponseEntity fetchCaseworkersById(List caseWorkerIds) { throw new ResourceNotFoundException(CaseWorkerConstants.NO_DATA_FOUND); } log.info("{}::Time taken for fetching the records from DB for FetchCaseworkersById {}", - loggingComponentName, (Math.subtractExact(System.currentTimeMillis(), startTime))); + loggingComponentName, (Math.subtractExact(System.currentTimeMillis(), startTime))); return ResponseEntity.ok().body(mapCaseWorkerProfileToDto(caseWorkerProfileList)); } private List mapCaseWorkerProfileToDto( - List caseWorkerProfileList) { + List caseWorkerProfileList) { long startTime = System.currentTimeMillis(); List caseWorkerProfilesDto = - new ArrayList<>(); + new ArrayList<>(); for (CaseWorkerProfile profile : caseWorkerProfileList) { caseWorkerProfilesDto.add(uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile.builder() - .id(profile.getCaseWorkerId()) - .firstName(profile.getFirstName()) - .lastName(profile.getLastName()) - .officialEmail(profile.getEmailId()) - .regionId(profile.getRegionId()) - .regionName(profile.getRegion()) - .userType(profile.getUserType().getDescription()) - .userId(profile.getUserTypeId()) - .suspended(profile.getSuspended().toString()) - .createdTime(profile.getCreatedDate()) - .lastUpdatedTime(profile.getLastUpdate()) - .roles(mapRolesToDto(profile.getCaseWorkerRoles())) - .locations(mapLocationsToDto(profile.getCaseWorkerLocations())) - .workAreas(mapWorkAreasToDto(profile.getCaseWorkerWorkAreas())) - .build()); + .id(profile.getCaseWorkerId()) + .firstName(profile.getFirstName()) + .lastName(profile.getLastName()) + .officialEmail(profile.getEmailId()) + .regionId(profile.getRegionId()) + .regionName(profile.getRegion()) + .userType(profile.getUserType().getDescription()) + .userId(profile.getUserTypeId()) + .suspended(profile.getSuspended().toString()) + .createdTime(profile.getCreatedDate()) + .lastUpdatedTime(profile.getLastUpdate()) + .roles(mapRolesToDto(profile.getCaseWorkerRoles())) + .locations(mapLocationsToDto(profile.getCaseWorkerLocations())) + .workAreas(mapWorkAreasToDto(profile.getCaseWorkerWorkAreas())) + .build()); } log.info("{}::Time taken By DTO for FetchCaseworkersById {}", loggingComponentName, - (Math.subtractExact(System.currentTimeMillis(), startTime))); + (Math.subtractExact(System.currentTimeMillis(), startTime))); return caseWorkerProfilesDto; } @@ -353,11 +359,11 @@ private List mapWorkAreasToDto(List caseWorkerWork List workAreasDtoList = new ArrayList<>(); for (CaseWorkerWorkArea area : caseWorkerWorkAreas) { WorkArea workAreaDto = WorkArea.builder() - .areaOfWork(area.getAreaOfWork()) - .serviceCode(area.getServiceCode()) - .createdTime(area.getCreatedDate()) - .lastUpdatedTime(area.getLastUpdate()) - .build(); + .areaOfWork(area.getAreaOfWork()) + .serviceCode(area.getServiceCode()) + .createdTime(area.getCreatedDate()) + .lastUpdatedTime(area.getLastUpdate()) + .build(); workAreasDtoList.add(workAreaDto); } @@ -368,12 +374,12 @@ private List mapLocationsToDto(List caseWorkerLoca List locationsDto = new ArrayList<>(); for (CaseWorkerLocation location : caseWorkerLocations) { Location locationDto = Location.builder() - .baseLocationId(location.getLocationId()) - .locationName(location.getLocation()) - .createdTime(location.getCreatedDate()) - .lastUpdatedTime(location.getLastUpdate()) - .isPrimary(location.getPrimaryFlag()) - .build(); + .baseLocationId(location.getLocationId()) + .locationName(location.getLocation()) + .createdTime(location.getCreatedDate()) + .lastUpdatedTime(location.getLastUpdate()) + .isPrimary(location.getPrimaryFlag()) + .build(); locationsDto.add(locationDto); } @@ -384,11 +390,11 @@ private List mapRolesToDto(List caseWorkerRoles) { List rolesDto = new ArrayList<>(); for (CaseWorkerRole caseWorkerRole : caseWorkerRoles) { Role roleDto = Role.builder() - .roleId(caseWorkerRole.getRoleId().toString()) - .roleName(caseWorkerRole.getRoleType().getDescription()) - .isPrimary(caseWorkerRole.getPrimaryFlag()) - .createdTime(caseWorkerRole.getCreatedDate()) - .lastUpdatedTime(caseWorkerRole.getLastUpdate()).build(); + .roleId(caseWorkerRole.getRoleId().toString()) + .roleName(caseWorkerRole.getRoleType().getDescription()) + .isPrimary(caseWorkerRole.getPrimaryFlag()) + .createdTime(caseWorkerRole.getCreatedDate()) + .lastUpdatedTime(caseWorkerRole.getLastUpdate()).build(); rolesDto.add(roleDto); } @@ -400,7 +406,7 @@ public CaseWorkerProfile createCaseWorkerProfile(CaseWorkersProfileCreationReque //User Profile Call ResponseEntity responseEntity = createUserProfileInIdamUP(cwrdProfileRequest); if (nonNull(responseEntity) && (responseEntity.getStatusCode().is2xxSuccessful() - || responseEntity.getStatusCode() == CONFLICT) && nonNull(responseEntity.getBody())) { + || responseEntity.getStatusCode() == CONFLICT) && nonNull(responseEntity.getBody())) { UserProfileCreationResponse upResponse = (UserProfileCreationResponse) (responseEntity.getBody()); if (nonNull(upResponse)) { @@ -408,13 +414,13 @@ public CaseWorkerProfile createCaseWorkerProfile(CaseWorkersProfileCreationReque populateCaseWorkerProfile(cwrdProfileRequest, caseWorkerProfile, upResponse.getIdamId()); if (responseEntity.getStatusCode() == CONFLICT) { UserProfileCreationResponse userProfileCreationResponse - = (UserProfileCreationResponse) requireNonNull(responseEntity.getBody()); + = (UserProfileCreationResponse) requireNonNull(responseEntity.getBody()); updateUserRolesInIdam(cwrdProfileRequest, userProfileCreationResponse.getIdamId()); } } else { validationServiceFacade.logFailures(RESPONSE_BODY_MISSING_FROM_UP, cwrdProfileRequest.getRowId()); log.error("{}:: {}:: Job Id {}:: Row Id {}", RESPONSE_BODY_MISSING_FROM_UP, loggingComponentName, - validationServiceFacade.getAuditJobId(), cwrdProfileRequest.getRowId()); + validationServiceFacade.getAuditJobId(), cwrdProfileRequest.getRowId()); } } return caseWorkerProfile; @@ -437,7 +443,7 @@ public List mapCwAreaOfWork(CaseWorkersProfileCreationReques List caseWorkerWorkAreas = new ArrayList<>(); cwrdProfileRequest.getWorkerWorkAreaRequests().forEach(caseWorkerWorkAreaRequest -> { CaseWorkerWorkArea caseWorkerWorkArea = new CaseWorkerWorkArea(idamId, - caseWorkerWorkAreaRequest.getAreaOfWork(), caseWorkerWorkAreaRequest.getServiceCode()); + caseWorkerWorkAreaRequest.getAreaOfWork(), caseWorkerWorkAreaRequest.getServiceCode()); caseWorkerWorkAreas.add(caseWorkerWorkArea); }); return caseWorkerWorkAreas; @@ -463,10 +469,10 @@ public boolean updateUserRolesInIdam(CaseWorkersProfileCreationRequest cwrProfil if (!resultResponse.isPresent() - || (isNull(((UserProfileResponse) resultResponse.get()) - .getIdamStatus())) - || (!STATUS_ACTIVE.equalsIgnoreCase(((UserProfileResponse) resultResponse.get()) - .getIdamStatus()))) { + || (isNull(((UserProfileResponse) resultResponse.get()) + .getIdamStatus())) + || (!STATUS_ACTIVE.equalsIgnoreCase(((UserProfileResponse) resultResponse.get()) + .getIdamStatus()))) { validationServiceFacade.logFailures(UP_FAILURE_ROLES, cwrProfileRequest.getRowId()); return false; } @@ -475,18 +481,18 @@ public boolean updateUserRolesInIdam(CaseWorkersProfileCreationRequest cwrProfil UserProfileResponse userProfileResponse = (UserProfileResponse) requireNonNull(responseEntity.getBody()); Set userProfileRoles = copyOf(userProfileResponse.getRoles()); Set idamRolesCwr = isNotEmpty(cwrProfileRequest.getIdamRoles()) ? cwrProfileRequest.getIdamRoles() : - new HashSet<>(); + new HashSet<>(); idamRolesCwr.addAll(mappedRoles); if (isNotTrue(userProfileRoles.equals(idamRolesCwr)) && isNotEmpty(idamRolesCwr)) { Set mergedRoles = idamRolesCwr.stream() - .filter(s -> !(userProfileRoles.contains(s))) - .map(RoleName::new) - .collect(toSet()); + .filter(s -> !(userProfileRoles.contains(s))) + .map(RoleName::new) + .collect(toSet()); if (isNotEmpty(mergedRoles)) { UserProfileUpdatedData usrProfileStatusUpdate = UserProfileUpdatedData.builder() - .rolesAdd(mergedRoles).build(); + .rolesAdd(mergedRoles).build(); return isEachRoleUpdated(usrProfileStatusUpdate, idamId, "EXUI", - cwrProfileRequest.getRowId()); + cwrProfileRequest.getRowId()); } } } catch (Exception exception) { @@ -516,7 +522,7 @@ public List mapCaseWorkerLocationRequest(String idamId, cwRequest.getBaseLocations().forEach(location -> { CaseWorkerLocation caseWorkerLocation = new CaseWorkerLocation(idamId, - location.getLocationId(), location.getLocation(), location.isPrimaryFlag()); + location.getLocationId(), location.getLocation(), location.isPrimaryFlag()); cwLocations.add(caseWorkerLocation); }); return cwLocations; @@ -526,13 +532,13 @@ public List mapCaseWorkerRoleRequestMapping(String idamId, CaseWorkersProfileCreationRequest cwrdProfileRequest) { List caseWorkerRoles = new ArrayList<>(); cwrdProfileRequest.getRoles().forEach(role -> caseWorkerStaticValueRepositoryAccessor - .getRoleTypes() - .stream().filter(roleType -> - role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) - .forEach(roleType -> { - CaseWorkerRole workerRole = new CaseWorkerRole(idamId, roleType.getRoleId(), role.isPrimaryFlag()); - caseWorkerRoles.add(workerRole); - })); + .getRoleTypes() + .stream().filter(roleType -> + role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) + .forEach(roleType -> { + CaseWorkerRole workerRole = new CaseWorkerRole(idamId, roleType.getRoleId(), role.isPrimaryFlag()); + caseWorkerRoles.add(workerRole); + })); return caseWorkerRoles; } @@ -549,7 +555,7 @@ private ResponseEntity createUserProfileInIdamUP(CaseWorkersProfileCreat log.info("{}:: Time taken to call UP is {}", loggingComponentName, (System.currentTimeMillis() - time1)); clazz = (response.status() == 201 || response.status() == 409) - ? UserProfileCreationResponse.class : ErrorResponse.class; + ? UserProfileCreationResponse.class : ErrorResponse.class; responseEntity = JsonFeignResponseUtil.toResponseEntity(response, clazz); if (clazz == ErrorResponse.class) { @@ -557,8 +563,8 @@ private ResponseEntity createUserProfileInIdamUP(CaseWorkersProfileCreat if (nonNull(responseBody) && responseBody instanceof ErrorResponse) { Optional optional = Optional.ofNullable((ErrorResponse) responseBody); validationServiceFacade.logFailures( - optional.map(ErrorResponse::getErrorDescription).orElse(UP_CREATION_FAILED), - cwrdProfileRequest.getRowId()); + optional.map(ErrorResponse::getErrorDescription).orElse(UP_CREATION_FAILED), + cwrdProfileRequest.getRowId()); } else { validationServiceFacade.logFailures(UP_CREATION_FAILED, cwrdProfileRequest.getRowId()); } @@ -566,7 +572,7 @@ private ResponseEntity createUserProfileInIdamUP(CaseWorkersProfileCreat return responseEntity; } catch (Exception ex) { log.error("{}:: UserProfile api failed:: message {}:: Job Id {}:: Row Id {}", loggingComponentName, - ex.getMessage(), validationServiceFacade.getAuditJobId(), cwrdProfileRequest.getRowId()); + ex.getMessage(), validationServiceFacade.getAuditJobId(), cwrdProfileRequest.getRowId()); //Log UP failures validationServiceFacade.logFailures(ex.getMessage(), cwrdProfileRequest.getRowId()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); @@ -577,6 +583,72 @@ private ResponseEntity createUserProfileInIdamUP(CaseWorkersProfileCreat } } + @Transactional + public CaseWorkerProfilesDeletionResponse deleteByUserId(String userId) { + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + + Response userProfileResponse = userProfileFeignClient.deleteUserProfileById(userId); + + if (userProfileResponse.status() == NO_CONTENT.value() || userProfileResponse.status() == NOT_FOUND.value()) { + Optional caseWorkerProfile = caseWorkerProfileRepo.findByCaseWorkerId(userId.trim()); + + return validateUserAfterUpDelete(caseWorkerProfile, userId, userProfileResponse.status()); + + } else { + deletionResponse.setMessage("UP Delete request failed for userId: " + userId + + ". With the following UP message: " + userProfileResponse.reason()); + deletionResponse.setStatusCode(userProfileResponse.status()); + return deletionResponse; + } + } + + @Transactional + public CaseWorkerProfilesDeletionResponse deleteByEmailPattern(String emailPattern) { + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + + List userProfiles = caseWorkerProfileRepo.findByEmailIdIgnoreCaseContaining(emailPattern); + + if (userProfiles.isEmpty()) { + throw new ResourceNotFoundException("No User Profiles found for email pattern: " + emailPattern); + } + + Response idamResponse = userProfileFeignClient.deleteUserProfileByEmailPattern(emailPattern); + + if (idamResponse.status() == NO_CONTENT.value() || idamResponse.status() == NOT_FOUND.value()) { + return deleteUserProfiles(userProfiles); + + } else { + deletionResponse.setMessage("UP Delete request failed for emailPattern: " + emailPattern); + deletionResponse.setStatusCode(idamResponse.status()); + return deletionResponse; + } + } + + public CaseWorkerProfilesDeletionResponse validateUserAfterUpDelete( + Optional caseWorkerProfile, String userId, int status) { + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + + if (caseWorkerProfile.isPresent()) { + return deleteUserProfiles(singletonList(caseWorkerProfile.get())); + + } else if (status == NO_CONTENT.value()) { + deletionResponse.setMessage("User deleted in UP but was not present in CRD with userId: " + userId); + + } else { + deletionResponse.setMessage("User was not present in UP or CRD with userId: " + userId); + } + + deletionResponse.setStatusCode(status); + return deletionResponse; + } + + public CaseWorkerProfilesDeletionResponse deleteUserProfiles(List userProfiles) { + caseWorkerProfileRepo.deleteAll(userProfiles); + + return new CaseWorkerProfilesDeletionResponse(NO_CONTENT.value(), + "Case Worker Profiles successfully deleted"); + } + public boolean isUserSuspended(UserProfileUpdatedData userProfileUpdatedData, String userId, String origin, long rowId) { @@ -586,17 +658,17 @@ public boolean isUserSuspended(UserProfileUpdatedData userProfileUpdatedData, St Optional resultResponse = getUserProfileUpdateResponse(userProfileUpdatedData, userId, origin); if (!resultResponse.isPresent() - || (isNull(((UserProfileRolesResponse) resultResponse.get()) - .getAttributeResponse())) - || (!(((UserProfileRolesResponse) resultResponse.get()) - .getAttributeResponse().getIdamStatusCode().equals(HttpStatus.OK.value())))) { + || (isNull(((UserProfileRolesResponse) resultResponse.get()) + .getAttributeResponse())) + || (!(((UserProfileRolesResponse) resultResponse.get()) + .getAttributeResponse().getIdamStatusCode().equals(HttpStatus.OK.value())))) { validationServiceFacade.logFailures(UP_FAILURE_ROLES, rowId); status = false; } } catch (Exception ex) { log.error("{}:: UserProfile modify api failed for row ID {} with error :: {}:: Job Id {}", - loggingComponentName, rowId, ex.getMessage(), validationServiceFacade.getAuditJobId()); + loggingComponentName, rowId, ex.getMessage(), validationServiceFacade.getAuditJobId()); validationServiceFacade.logFailures(UP_FAILURE_ROLES, rowId); status = false; } @@ -609,17 +681,17 @@ public boolean isEachRoleUpdated(UserProfileUpdatedData userProfileUpdatedData, Optional resultResponse = getUserProfileUpdateResponse(userProfileUpdatedData, userId, origin); if (!resultResponse.isPresent() - || (isNull(((UserProfileRolesResponse) resultResponse.get()) - .getRoleAdditionResponse())) - || (((UserProfileRolesResponse) resultResponse.get()).getRoleAdditionResponse() - .getIdamStatusCode().equals(valueOf(HttpStatus.CREATED.value())) == FALSE)) { + || (isNull(((UserProfileRolesResponse) resultResponse.get()) + .getRoleAdditionResponse())) + || (((UserProfileRolesResponse) resultResponse.get()).getRoleAdditionResponse() + .getIdamStatusCode().equals(valueOf(HttpStatus.CREATED.value())) == FALSE)) { validationServiceFacade.logFailures(UP_FAILURE_ROLES, rowId); return false; } } catch (Exception ex) { log.error("{}:: UserProfile modify api failed for row ID {} with error :: {}:: Job Id {}", - loggingComponentName, rowId, ex.getMessage(), validationServiceFacade.getAuditJobId()); + loggingComponentName, rowId, ex.getMessage(), validationServiceFacade.getAuditJobId()); validationServiceFacade.logFailures(UP_FAILURE_ROLES, rowId); return false; } @@ -630,7 +702,7 @@ private Optional getUserProfileUpdateResponse(UserProfileUpdatedData use String userId, String origin) { Response response = userProfileFeignClient.modifyUserRoles(userProfileUpdatedData, userId, origin); log.info("{}:: UserProfile update roles :: status code {}:: Job Id {}", loggingComponentName, - response.status(), validationServiceFacade.getAuditJobId()); + response.status(), validationServiceFacade.getAuditJobId()); ResponseEntity responseEntity = toResponseEntity(response, UserProfileRolesResponse.class); @@ -641,7 +713,7 @@ private Optional getUserProfileUpdateResponse(UserProfileUpdatedData use public UserProfileCreationRequest createUserProfileRequest(CaseWorkersProfileCreationRequest cwrdProfileRequest) { Set userRoles = cwrdProfileRequest.getIdamRoles() != null ? cwrdProfileRequest.getIdamRoles() : - new HashSet<>(); + new HashSet<>(); userRoles.add(ROLE_CWD_USER); Set idamRoles = getUserRolesByRoleId(cwrdProfileRequest); if (isNotEmpty(idamRoles)) { @@ -649,14 +721,14 @@ public UserProfileCreationRequest createUserProfileRequest(CaseWorkersProfileCre } //Creating user profile request return new UserProfileCreationRequest( - cwrdProfileRequest.getEmailId(), - cwrdProfileRequest.getFirstName(), - cwrdProfileRequest.getLastName(), - LanguagePreference.EN, - UserCategory.CASEWORKER, - UserTypeRequest.INTERNAL, - userRoles, - false); + cwrdProfileRequest.getEmailId(), + cwrdProfileRequest.getFirstName(), + cwrdProfileRequest.getLastName(), + LanguagePreference.EN, + UserCategory.CASEWORKER, + UserTypeRequest.INTERNAL, + userRoles, + false); } // get the roles that needs to send to idam based on the roleType in the request. @@ -665,25 +737,25 @@ Set getUserRolesByRoleId(CaseWorkersProfileCreationRequest cwProfileRequ // get Roles Types List roleTypeList = new ArrayList<>(); cwProfileRequest.getRoles().forEach(role -> roleTypeList.addAll( - caseWorkerStaticValueRepositoryAccessor - .getRoleTypes() - .stream() - .filter(roleType -> role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) - .collect(Collectors.toList())) + caseWorkerStaticValueRepositoryAccessor + .getRoleTypes() + .stream() + .filter(roleType -> role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) + .collect(Collectors.toList())) ); // get work area codes List serviceCodes = cwProfileRequest.getWorkerWorkAreaRequests() - .stream() - .map(CaseWorkerWorkAreaRequest::getServiceCode) - .collect(Collectors.toList()); + .stream() + .map(CaseWorkerWorkAreaRequest::getServiceCode) + .collect(Collectors.toList()); // get all assoc records matching role id and service code, finally return idam roles associated Set matchedRoles = roleAssocRepository.findByRoleTypeInAndServiceCodeIn(roleTypeList, serviceCodes) - .stream() - .map(CaseWorkerIdamRoleAssociation::getIdamRole) - .collect(Collectors.toSet()); + .stream() + .map(CaseWorkerIdamRoleAssociation::getIdamRole) + .collect(Collectors.toSet()); log.info("{}:: roles matched from assoc :: {}", loggingComponentName, matchedRoles); return matchedRoles; } @@ -691,10 +763,10 @@ Set getUserRolesByRoleId(CaseWorkersProfileCreationRequest cwProfileRequ // get the userTypeId by description. public Long getUserTypeIdByDesc(String userTypeReq) { Optional userTypeId = caseWorkerStaticValueRepositoryAccessor - .getUserTypes() - .stream().filter(userType -> - userType.getDescription().equalsIgnoreCase(userTypeReq.trim())) - .map(UserType::getUserTypeId).findFirst(); + .getUserTypes() + .stream().filter(userType -> + userType.getDescription().equalsIgnoreCase(userTypeReq.trim())) + .map(UserType::getUserTypeId).findFirst(); return userTypeId.orElse(0L); } From 3fbc18f02e6ac9b0b60d1cc7682a0c8f467b6a48 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:18:41 +0100 Subject: [PATCH 07/31] RDCC-2390: adding repository methods --- .../cwrdapi/repository/CaseWorkerProfileRepository.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepository.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepository.java index aa5223d87..5478c998d 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepository.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepository.java @@ -5,12 +5,16 @@ import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerProfile; import java.util.List; +import java.util.Optional; @Repository public interface CaseWorkerProfileRepository extends JpaRepository { - CaseWorkerProfile findByEmailId(String emailId); List findByCaseWorkerIdIn(List caseWorkerId); + + Optional findByCaseWorkerId(String caseWorkerId); + + List findByEmailIdIgnoreCaseContaining(String emailPattern); } From 86985d97e207b4d61132fa3f08185eba40c06344 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:19:41 +0100 Subject: [PATCH 08/31] RDCC-2390: adding UP Delete APIs to UserProfileFeignClient --- .../controllers/feign/UserProfileFeignClient.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java index 78e74b3a4..5f9dc0ee8 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java @@ -4,6 +4,7 @@ import feign.RequestLine; import feign.Response; import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -30,11 +31,22 @@ public interface UserProfileFeignClient { Response modifyUserRoles(@RequestBody UserProfileUpdatedData modifyRoles, @PathVariable("userId") String userId, @RequestParam(value = "origin") String origin); - @GetMapping(value = "/v1/userprofile/{id}/roles") @RequestLine("GET /v1/userprofile/{id}/roles") @Headers({"Authorization: {authorization}", "ServiceAuthorization: {serviceAuthorization}", "Content-Type: application/json"}) Response getUserProfileWithRolesById(@PathVariable String id); + @DeleteMapping(value = "/v1/userprofile/users?userId={userId}") + @RequestLine("DELETE /v1/userprofile/users?userId={userId}") + @Headers({"Authorization: {authorization}", "ServiceAuthorization: {serviceAuthorization}", + "Content-Type: application/json"}) + Response deleteUserProfileById(@PathVariable String userId); + + @DeleteMapping(value = "/v1/userprofile/users?emailPattern={emailPattern}") + @RequestLine("DELETE /v1/userprofile/users?emailPattern={emailPattern}") + @Headers({"Authorization: {authorization}", "ServiceAuthorization: {serviceAuthorization}", + "Content-Type: application/json"}) + Response deleteUserProfileByEmailPattern(@PathVariable String emailPattern); + } From 70e5944d7c9f677083d2f682451f11a4474577db Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:20:06 +0100 Subject: [PATCH 09/31] RDCC-2390: adding deleteCaseWorkerProfileByIdOrEmailPattern method to Controller --- .../reform/cwrdapi/controllers/CaseWorkerRefUsersController.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index b1024befc..0d49486f0 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -219,7 +219,6 @@ public ResponseEntity fetchCaseworkersById(@RequestBody UserRequest user }) @DeleteMapping( - path = "/users", produces = APPLICATION_JSON_VALUE ) @ResponseStatus(value = HttpStatus.NO_CONTENT) From 83d7da26d7c9a5b95a1cca515c95d3ce963de39b Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 12:27:33 +0100 Subject: [PATCH 10/31] RDCC-2390: resolving merge conficts with Master --- .../service/impl/CaseWorkerServiceImpl.java | 97 ++++++++++--------- 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java index 7103e5206..66debc4cc 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java @@ -249,17 +249,17 @@ public List persistCaseWorkerInBatch(List long time1 = currentTimeMillis(); processedCwProfiles = caseWorkerProfileRepo.saveAll(profilesToBePersisted); log.info("{}:: {} case worker profiles inserted :: Job Id {}", loggingComponentName, - processedCwProfiles.size(), validationServiceFacade.getAuditJobId()); + processedCwProfiles.size(), validationServiceFacade.getAuditJobId()); log.info("{}::Time taken to save caseworker data in CRD is {}", loggingComponentName, - (currentTimeMillis() - time1)); + (currentTimeMillis() - time1)); } return processedCwProfiles; } // deletes children and updates caseworker profile private List deleteChildrenAndUpdateCwProfiles(List updateCaseWorkerProfiles, - Map - emailToRequestMap) { + Map + emailToRequestMap) { List updatedProfiles = new ArrayList<>(); if (isNotEmpty(updateCaseWorkerProfiles)) { caseWorkerLocationRepository.deleteByCaseWorkerProfileIn(updateCaseWorkerProfiles); @@ -308,20 +308,21 @@ public IdamRolesMappingResponse buildIdamRoleMappings(List s try { idamRoleMappingService.deleteExistingRecordForServiceCode(serviceCodes); log.info("{}::" + CaseWorkerConstants.DELETE_RECORD_FOR_SERVICE_ID + " ::{}", loggingComponentName, - serviceCodes.toString()); + serviceCodes.toString()); idamRoleMappingService.buildIdamRoleAssociation(caseWorkerIdamRoleAssociations); log.info("{}::" + CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + "::{}", loggingComponentName, - serviceCodes.toString()); + serviceCodes.toString()); return IdamRolesMappingResponse.builder() - .message(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCodes.toString()) - .statusCode(HttpStatus.CREATED.value()) - .build(); + .message(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCodes.toString()) + .statusCode(HttpStatus.CREATED.value()) + .build(); } catch (Exception e) { log.error("{}::" + CaseWorkerConstants.IDAM_ROLE_MAPPINGS_FAILURE + " ::{}:: Job Id {}::Reason:: {}", - loggingComponentName, serviceCodes.toString(), validationServiceFacade.getAuditJobId(), e.getMessage()); + loggingComponentName, serviceCodes.toString(), validationServiceFacade.getAuditJobId(), + e.getMessage()); throw new IdamRolesMappingException(e.getMessage()); } } @@ -334,8 +335,8 @@ public IdamRolesMappingResponse buildIdamRoleMappings(List s @Override public void publishCaseWorkerDataToTopic(List caseWorkerData) { List caseWorkerIds = caseWorkerData.stream() - .map(CaseWorkerProfile::getCaseWorkerId) - .collect(Collectors.toUnmodifiableList()); + .map(CaseWorkerProfile::getCaseWorkerId) + .collect(Collectors.toUnmodifiableList()); topicPublisher.sendMessage(caseWorkerIds); } @@ -354,36 +355,36 @@ public ResponseEntity fetchCaseworkersById(List caseWorkerIds) { throw new ResourceNotFoundException(CaseWorkerConstants.NO_DATA_FOUND); } log.info("{}::Time taken for fetching the records from DB for FetchCaseworkersById {}", - loggingComponentName, (Math.subtractExact(System.currentTimeMillis(), startTime))); + loggingComponentName, (Math.subtractExact(System.currentTimeMillis(), startTime))); return ResponseEntity.ok().body(mapCaseWorkerProfileToDto(caseWorkerProfileList)); } private List mapCaseWorkerProfileToDto( - List caseWorkerProfileList) { + List caseWorkerProfileList) { long startTime = System.currentTimeMillis(); List caseWorkerProfilesDto = - new ArrayList<>(); + new ArrayList<>(); for (CaseWorkerProfile profile : caseWorkerProfileList) { caseWorkerProfilesDto.add(uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile.builder() - .id(profile.getCaseWorkerId()) - .firstName(profile.getFirstName()) - .lastName(profile.getLastName()) - .officialEmail(profile.getEmailId()) - .regionId(profile.getRegionId()) - .regionName(profile.getRegion()) - .userType(profile.getUserType().getDescription()) - .userId(profile.getUserTypeId()) - .suspended(profile.getSuspended().toString()) - .createdTime(profile.getCreatedDate()) - .lastUpdatedTime(profile.getLastUpdate()) - .roles(mapRolesToDto(profile.getCaseWorkerRoles())) - .locations(mapLocationsToDto(profile.getCaseWorkerLocations())) - .workAreas(mapWorkAreasToDto(profile.getCaseWorkerWorkAreas())) - .build()); + .id(profile.getCaseWorkerId()) + .firstName(profile.getFirstName()) + .lastName(profile.getLastName()) + .officialEmail(profile.getEmailId()) + .regionId(profile.getRegionId()) + .regionName(profile.getRegion()) + .userType(profile.getUserType().getDescription()) + .userId(profile.getUserTypeId()) + .suspended(profile.getSuspended().toString()) + .createdTime(profile.getCreatedDate()) + .lastUpdatedTime(profile.getLastUpdate()) + .roles(mapRolesToDto(profile.getCaseWorkerRoles())) + .locations(mapLocationsToDto(profile.getCaseWorkerLocations())) + .workAreas(mapWorkAreasToDto(profile.getCaseWorkerWorkAreas())) + .build()); } log.info("{}::Time taken By DTO for FetchCaseworkersById {}", loggingComponentName, - (Math.subtractExact(System.currentTimeMillis(), startTime))); + (Math.subtractExact(System.currentTimeMillis(), startTime))); return caseWorkerProfilesDto; } @@ -517,18 +518,18 @@ public boolean updateUserRolesInIdam(CaseWorkersProfileCreationRequest cwrProfil UserProfileResponse userProfileResponse = (UserProfileResponse) requireNonNull(responseEntity.getBody()); Set userProfileRoles = copyOf(userProfileResponse.getRoles()); Set idamRolesCwr = isNotEmpty(cwrProfileRequest.getIdamRoles()) ? cwrProfileRequest.getIdamRoles() : - new HashSet<>(); + new HashSet<>(); idamRolesCwr.addAll(mappedRoles); if (isNotTrue(userProfileRoles.equals(idamRolesCwr)) && isNotEmpty(idamRolesCwr)) { Set mergedRoles = idamRolesCwr.stream() - .filter(s -> !(userProfileRoles.contains(s))) - .map(RoleName::new) - .collect(toSet()); + .filter(s -> !(userProfileRoles.contains(s))) + .map(RoleName::new) + .collect(toSet()); if (isNotEmpty(mergedRoles)) { UserProfileUpdatedData usrProfileStatusUpdate = UserProfileUpdatedData.builder() - .rolesAdd(mergedRoles).build(); + .rolesAdd(mergedRoles).build(); return isEachRoleUpdated(usrProfileStatusUpdate, idamId, "EXUI", - cwrProfileRequest.getRowId()); + cwrProfileRequest.getRowId()); } } } catch (Exception exception) { @@ -561,7 +562,7 @@ public List mapCaseWorkerLocationRequest(String idamId, cwRequest.getBaseLocations().forEach(location -> { CaseWorkerLocation caseWorkerLocation = new CaseWorkerLocation(idamId, - location.getLocationId(), location.getLocation(), location.isPrimaryFlag()); + location.getLocationId(), location.getLocation(), location.isPrimaryFlag()); cwLocations.add(caseWorkerLocation); }); return cwLocations; @@ -753,7 +754,7 @@ private Optional getUserProfileUpdateResponse(UserProfileUpdatedData use String userId, String origin) { Response response = userProfileFeignClient.modifyUserRoles(userProfileUpdatedData, userId, origin); log.info("{}:: UserProfile update roles :: status code {}:: Job Id {}", loggingComponentName, - response.status(), validationServiceFacade.getAuditJobId()); + response.status(), validationServiceFacade.getAuditJobId()); ResponseEntity responseEntity = toResponseEntity(response, UserProfileRolesResponse.class); @@ -764,7 +765,7 @@ private Optional getUserProfileUpdateResponse(UserProfileUpdatedData use public UserProfileCreationRequest createUserProfileRequest(CaseWorkersProfileCreationRequest cwrdProfileRequest) { Set userRoles = cwrdProfileRequest.getIdamRoles() != null ? cwrdProfileRequest.getIdamRoles() : - new HashSet<>(); + new HashSet<>(); userRoles.add(ROLE_CWD_USER); Set idamRoles = getUserRolesByRoleId(cwrdProfileRequest); if (isNotEmpty(idamRoles)) { @@ -788,18 +789,18 @@ Set getUserRolesByRoleId(CaseWorkersProfileCreationRequest cwProfileRequ // get Roles Types List roleTypeList = new ArrayList<>(); cwProfileRequest.getRoles().forEach(role -> roleTypeList.addAll( - caseWorkerStaticValueRepositoryAccessor - .getRoleTypes() - .stream() - .filter(roleType -> role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) - .collect(toList())) + caseWorkerStaticValueRepositoryAccessor + .getRoleTypes() + .stream() + .filter(roleType -> role.getRole().equalsIgnoreCase(roleType.getDescription().trim())) + .collect(toList())) ); // get work area codes List serviceCodes = cwProfileRequest.getWorkerWorkAreaRequests() - .stream() - .map(CaseWorkerWorkAreaRequest::getServiceCode) - .collect(toList()); + .stream() + .map(CaseWorkerWorkAreaRequest::getServiceCode) + .collect(toList()); // get all assoc records matching role id and service code, finally return idam roles associated From 0129eabd5aae70f46cfc5354821ec85ed041f71d Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 14:09:11 +0100 Subject: [PATCH 11/31] RDCC-2390: adding unit tests for CaseWorkerServiceImpl --- .../service/impl/CaseWorkerServiceImpl.java | 6 +- .../impl/CaseWorkerServiceImplTest.java | 392 +++++++++++++----- 2 files changed, 296 insertions(+), 102 deletions(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java index 66debc4cc..07a5e3869 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java @@ -652,14 +652,14 @@ public CaseWorkerProfilesDeletionResponse deleteByEmailPattern(String emailPatte throw new ResourceNotFoundException("No User Profiles found for email pattern: " + emailPattern); } - Response idamResponse = userProfileFeignClient.deleteUserProfileByEmailPattern(emailPattern); + Response userProfileResponse = userProfileFeignClient.deleteUserProfileByEmailPattern(emailPattern); - if (idamResponse.status() == NO_CONTENT.value() || idamResponse.status() == NOT_FOUND.value()) { + if (userProfileResponse.status() == NO_CONTENT.value() || userProfileResponse.status() == NOT_FOUND.value()) { return deleteUserProfiles(userProfiles); } else { deletionResponse.setMessage("UP Delete request failed for emailPattern: " + emailPattern); - deletionResponse.setStatusCode(idamResponse.status()); + deletionResponse.setStatusCode(userProfileResponse.status()); return deletionResponse; } } diff --git a/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java b/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java index 80acbd5c1..522afaa43 100644 --- a/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java @@ -27,6 +27,7 @@ import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerRoleRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkerWorkAreaRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; +import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfilesDeletionResponse; import uk.gov.hmcts.reform.cwrdapi.controllers.response.IdamRolesMappingResponse; import uk.gov.hmcts.reform.cwrdapi.controllers.response.UserProfileCreationResponse; import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerLocation; @@ -53,6 +54,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.UUID; import static java.nio.charset.Charset.defaultCharset; import static java.util.Collections.emptyList; @@ -65,6 +67,9 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.NO_CONTENT; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.IDAM_STATUS_SUSPENDED; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.STATUS_ACTIVE; @@ -94,10 +99,12 @@ public class CaseWorkerServiceImplTest { @Mock IValidationService validationServiceFacade; + public static final String COMMON_EMAIL_PATTERN = "CWR-func-test-user"; private CaseWorkersProfileCreationRequest cwProfileCreationRequest; private RoleType roleType; private UserType userType; + private CaseWorkerProfile caseWorkerProfile; ObjectMapper mapper = new ObjectMapper(); @@ -111,34 +118,45 @@ public void setUp() { idamRoles.add("IdamRole2"); CaseWorkerRoleRequest caseWorkerRoleRequest = - new CaseWorkerRoleRequest("testRole", true); + new CaseWorkerRoleRequest("testRole", true); CaseWorkerLocationRequest caseWorkerLocationRequest = CaseWorkerLocationRequest - .caseWorkersLocationRequest() - .isPrimaryFlag(true) - .location("testLocation") - .locationId(1) - .build(); + .caseWorkersLocationRequest() + .isPrimaryFlag(true) + .location("testLocation") + .locationId(1) + .build(); CaseWorkerWorkAreaRequest caseWorkerWorkAreaRequest = CaseWorkerWorkAreaRequest - .caseWorkerWorkAreaRequest() - .areaOfWork("testAOW") - .serviceCode("testServiceCode") - .build(); + .caseWorkerWorkAreaRequest() + .areaOfWork("testAOW") + .serviceCode("testServiceCode") + .build(); cwProfileCreationRequest = CaseWorkersProfileCreationRequest - .caseWorkersProfileCreationRequest() - .suspended(false) - .emailId("test@test.com") - .idamRoles(idamRoles) - .firstName("testFN") - .lastName("testLN") - .region("testRegion") - .userType("testUser1") - .workerWorkAreaRequests(singletonList(caseWorkerWorkAreaRequest)) - .baseLocations(singletonList(caseWorkerLocationRequest)) - .roles(singletonList(caseWorkerRoleRequest)) - .build(); + .caseWorkersProfileCreationRequest() + .suspended(false) + .emailId("test@test.com") + .idamRoles(idamRoles) + .firstName("testFN") + .lastName("testLN") + .region("testRegion") + .userType("testUser1") + .workerWorkAreaRequests(singletonList(caseWorkerWorkAreaRequest)) + .baseLocations(singletonList(caseWorkerLocationRequest)) + .roles(singletonList(caseWorkerRoleRequest)) + .build(); + + Role caseWorkerRole = new Role(); + caseWorkerRole.setRoleId("id"); + caseWorkerRole.setRoleName("role name"); + caseWorkerRole.setPrimary(true); + + caseWorkerProfile = new CaseWorkerProfile(); + caseWorkerProfile.setCaseWorkerId("CWID1"); + caseWorkerProfile.setFirstName("CWFirstName"); + caseWorkerProfile.setLastName("CWLastName"); + caseWorkerProfile.setEmailId("CWR-func-test-user@test.com"); roleType = new RoleType(); roleType.setRoleId(1L); @@ -160,12 +178,12 @@ public void test_saveCwUserProfile() throws JsonProcessingException { when(caseWorkerStaticValueRepositoryAccessorImpl.getRoleTypes()).thenReturn(singletonList(roleType)); when(caseWorkerStaticValueRepositoryAccessorImpl.getUserTypes()).thenReturn(singletonList(userType)); when(caseWorkerProfileRepository.findByEmailIdIn(any())) - .thenReturn(new ArrayList<>()); + .thenReturn(new ArrayList<>()); when(caseWorkerIdamRoleAssociationRepository.findByRoleTypeInAndServiceCodeIn(any(), any())) - .thenReturn(new ArrayList<>()); + .thenReturn(new ArrayList<>()); when(userProfileFeignClient.createUserProfile(any())).thenReturn(Response.builder() - .request(mock(Request.class)).body(body, defaultCharset()).status(201).build()); + .request(mock(Request.class)).body(body, defaultCharset()).status(201).build()); List requests = new ArrayList<>(); requests.add(cwProfileCreationRequest); @@ -194,22 +212,22 @@ public void test_409WhileCwUserProfileCreation() throws JsonProcessingException userProfileRolesResponse.setRoleAdditionResponse(roleAdditionResponse); when(userProfileFeignClient.createUserProfile(any())).thenReturn(Response.builder() - .request(mock(Request.class)).body(mapper.writeValueAsString(userProfileCreationResponse), - defaultCharset()) - .status(409).build()); + .request(mock(Request.class)).body(mapper.writeValueAsString(userProfileCreationResponse), + defaultCharset()) + .status(409).build()); when(userProfileFeignClient.getUserProfileWithRolesById(any())) - .thenReturn(Response.builder() - .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), - null)).body(mapper.writeValueAsString(userProfileResponse), - defaultCharset()) - .status(200).build()); + .thenReturn(Response.builder() + .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), + null)).body(mapper.writeValueAsString(userProfileResponse), + defaultCharset()) + .status(200).build()); when(userProfileFeignClient.modifyUserRoles(any(), any(), any())) - .thenReturn(Response.builder() - .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), - null)).body(mapper.writeValueAsString(userProfileRolesResponse), - defaultCharset()) - .status(200).build()); + .thenReturn(Response.builder() + .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), + null)).body(mapper.writeValueAsString(userProfileRolesResponse), + defaultCharset()) + .status(200).build()); when(caseWorkerStaticValueRepositoryAccessorImpl.getRoleTypes()).thenReturn(singletonList(roleType)); when(caseWorkerStaticValueRepositoryAccessorImpl.getUserTypes()).thenReturn(singletonList(userType)); @@ -236,21 +254,20 @@ public void testSuspendCwUserProfile() throws JsonProcessingException { profile.setEmailId(cwProfileCreationRequest.getEmailId()); - UserProfileRolesResponse userProfileRolesResponse = new UserProfileRolesResponse(); AttributeResponse attributeResponse = new AttributeResponse(); attributeResponse.setIdamStatusCode(HttpStatus.OK.value()); userProfileRolesResponse.setAttributeResponse(attributeResponse); when(caseWorkerProfileRepository.findByEmailIdIn(any())) - .thenReturn(Arrays.asList(profile)); + .thenReturn(Arrays.asList(profile)); when(userProfileFeignClient.modifyUserRoles(any(), any(), any())) - .thenReturn(Response.builder() - .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), - null)).body(mapper.writeValueAsString(userProfileRolesResponse), - defaultCharset()) - .status(200).build()); + .thenReturn(Response.builder() + .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), + null)).body(mapper.writeValueAsString(userProfileRolesResponse), + defaultCharset()) + .status(200).build()); List requests = new ArrayList<>(); requests.add(cwProfileCreationRequest); @@ -265,27 +282,27 @@ public void testSuspendCwUserProfile() throws JsonProcessingException { @Test public void test_buildIdamRoleMappings_success() { ServiceRoleMapping serviceRoleMapping = ServiceRoleMapping.builder() - .serviceId("BA11") - .idamRoles("role1") - .roleId(1) - .build(); + .serviceId("BA11") + .idamRoles("role1") + .roleId(1) + .build(); List serviceRoleMappingList = singletonList(serviceRoleMapping); IdamRolesMappingResponse idamRolesMappingResponse = caseWorkerServiceImpl - .buildIdamRoleMappings(serviceRoleMappingList); + .buildIdamRoleMappings(serviceRoleMappingList); Set serviceCode = new HashSet<>(); serviceCode.add(serviceRoleMapping.getServiceId()); assertThat(idamRolesMappingResponse.getStatusCode()).isEqualTo(201); assertThat(idamRolesMappingResponse.getMessage()) - .isEqualTo(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCode.toString()); + .isEqualTo(CaseWorkerConstants.IDAM_ROLE_MAPPINGS_SUCCESS + serviceCode.toString()); } @Test(expected = IdamRolesMappingException.class) public void test_buildIdamRoleMappings_exception() { ServiceRoleMapping serviceRoleMapping = ServiceRoleMapping.builder().roleId(1).build(); doThrow(new RuntimeException("Exception message")) - .when(idamRoleMappingService).buildIdamRoleAssociation(any()); + .when(idamRoleMappingService).buildIdamRoleAssociation(any()); caseWorkerServiceImpl.buildIdamRoleMappings(singletonList(serviceRoleMapping)); } @@ -309,17 +326,17 @@ public void test_publishCaseWorkerDataToTopic() { @Test(expected = ResourceNotFoundException.class) public void test_shouldThrow404WhenCaseworker_profile_not_found() { doReturn(emptyList()) - .when(caseWorkerProfileRepository).findByCaseWorkerIdIn(any()); + .when(caseWorkerProfileRepository).findByCaseWorkerIdIn(any()); caseWorkerServiceImpl.fetchCaseworkersById(singletonList("")); } @Test public void test_should_return_caseworker_profile() { doReturn(singletonList(buildCaseWorkerProfile())) - .when(caseWorkerProfileRepository).findByCaseWorkerIdIn(singletonList( - "27fbd198-552e-4c32-9caf-37be1545caaf")); + .when(caseWorkerProfileRepository).findByCaseWorkerIdIn(singletonList( + "27fbd198-552e-4c32-9caf-37be1545caaf")); caseWorkerServiceImpl.fetchCaseworkersById( - singletonList("27fbd198-552e-4c32-9caf-37be1545caaf")); + singletonList("27fbd198-552e-4c32-9caf-37be1545caaf")); verify(caseWorkerProfileRepository, times(1)).findByCaseWorkerIdIn(any()); } @@ -366,46 +383,46 @@ public CaseWorkerProfile buildCaseWorkerProfile() { public uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile buildCaseWorkerProfileForDto() { Role - role = Role.builder() - .roleId("1") - .roleName("roleName") - .createdTime(LocalDateTime.now()) - .lastUpdatedTime(LocalDateTime.now()) - .isPrimary(true) - .build(); + role = Role.builder() + .roleId("1") + .roleName("roleName") + .createdTime(LocalDateTime.now()) + .lastUpdatedTime(LocalDateTime.now()) + .isPrimary(true) + .build(); Location location = Location - .builder() - .baseLocationId(11111) - .locationName("LocationName") - .isPrimary(true) - .createdTime(LocalDateTime.now()) - .lastUpdatedTime(LocalDateTime.now()) - .build(); + .builder() + .baseLocationId(11111) + .locationName("LocationName") + .isPrimary(true) + .createdTime(LocalDateTime.now()) + .lastUpdatedTime(LocalDateTime.now()) + .build(); WorkArea workArea = WorkArea.builder() - .areaOfWork("areaOfWork") - .serviceCode("serviceCode") - .createdTime(LocalDateTime.now()) - .lastUpdatedTime(LocalDateTime.now()) - .build(); - - uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile caseWorkerProfile = - uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile.builder() - .id("27fbd198-552e-4c32-9caf-37be1545caaf") - .firstName("firstName") - .lastName("lastName") - .officialEmail("a@b.com") - .regionName("regionName") - .regionId(1) - .userType("userType") - .userId(11111L) - .suspended("false") + .areaOfWork("areaOfWork") + .serviceCode("serviceCode") .createdTime(LocalDateTime.now()) .lastUpdatedTime(LocalDateTime.now()) - .roles(singletonList(role)) - .locations(singletonList(location)) - .workAreas(singletonList(workArea)) .build(); + uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile caseWorkerProfile = + uk.gov.hmcts.reform.cwrdapi.client.domain.CaseWorkerProfile.builder() + .id("27fbd198-552e-4c32-9caf-37be1545caaf") + .firstName("firstName") + .lastName("lastName") + .officialEmail("a@b.com") + .regionName("regionName") + .regionId(1) + .userType("userType") + .userId(11111L) + .suspended("false") + .createdTime(LocalDateTime.now()) + .lastUpdatedTime(LocalDateTime.now()) + .roles(singletonList(role)) + .locations(singletonList(location)) + .workAreas(singletonList(workArea)) + .build(); + return caseWorkerProfile; } @@ -440,16 +457,16 @@ public void testUpdateRole() throws JsonProcessingException { when(caseWorkerStaticValueRepositoryAccessorImpl.getUserTypes()).thenReturn(singletonList(userType)); when(caseWorkerProfileRepository.findByEmailIdIn(any())).thenReturn(profiles); when(userProfileFeignClient.getUserProfileWithRolesById(any())) - .thenReturn(Response.builder() - .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), - null)).body(userProfileResponseBody, defaultCharset()).status(200).build()); + .thenReturn(Response.builder() + .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), + null)).body(userProfileResponseBody, defaultCharset()).status(200).build()); String userProfileRolesResponseBody = mapper.writeValueAsString(userProfileRolesResponse); when(userProfileFeignClient.modifyUserRoles(any(), any(), any())) - .thenReturn(Response.builder() - .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), - null)).body(userProfileRolesResponseBody, defaultCharset()) - .status(200).build()); + .thenReturn(Response.builder() + .request(Request.create(Request.HttpMethod.POST, "", new HashMap<>(), Request.Body.empty(), + null)).body(userProfileRolesResponseBody, defaultCharset()) + .status(200).build()); List requests = new ArrayList<>(); requests.add(cwProfileCreationRequest); @@ -534,7 +551,6 @@ public void updateRoleFailsForInvalidResponseFromIdam_Scenario2() throws JsonPro profile.setSuspended(false); - when(caseWorkerStaticValueRepositoryAccessorImpl.getRoleTypes()).thenReturn(singletonList(roleType)); Set emails = new HashSet<>(); emails.add(cwProfileCreationRequest.getEmailId()); @@ -729,7 +745,7 @@ public void testMapCaseWorkerProfileRequest() { UserProfileCreationResponse userProfileCreationResponse = new UserProfileCreationResponse(); userProfileCreationResponse.setIdamId("1"); CaseWorkerProfile caseWorkerProfile = caseWorkerServiceImpl.mapCaseWorkerProfileRequest( - "1", cwProfileCreationRequest, new CaseWorkerProfile()); + "1", cwProfileCreationRequest, new CaseWorkerProfile()); assertThat(caseWorkerProfile.getCaseWorkerId()).isEqualTo("1"); assertThat(caseWorkerProfile.getFirstName()).isEqualTo(cwProfileCreationRequest.getFirstName()); @@ -741,4 +757,182 @@ public void testMapCaseWorkerProfileRequest() { assertThat(caseWorkerProfile.getRegion()).isEqualTo(cwProfileCreationRequest.getRegion()); } + @Test + public void testDeleteUserProfileByUserId() { + Response responseMock = mock(Response.class); + + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + deletionResponse.setMessage("Case Worker Profiles successfully deleted"); + deletionResponse.setStatusCode(NO_CONTENT.value()); + + when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + .thenReturn(responseMock); + when(responseMock.status()).thenReturn(NO_CONTENT.value()); + when(caseWorkerProfileRepository.findByCaseWorkerId(any(String.class))) + .thenReturn(Optional.ofNullable(caseWorkerProfile)); + + CaseWorkerProfilesDeletionResponse deletionResp = + caseWorkerServiceImpl.deleteByUserId(caseWorkerProfile.getCaseWorkerId()); + + assertThat(deletionResp.getStatusCode()).isEqualTo(deletionResponse.getStatusCode()); + assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); + + verify(caseWorkerProfileRepository, times(1)).findByCaseWorkerId(any(String.class)); + verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); + verify(responseMock, times(2)).status(); + verify(userProfileFeignClient, times(1)) + .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + } + + @Test + public void testDeleteUserProfileByUserId_WhenUpReturns404() { + Response responseMock = mock(Response.class); + + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + deletionResponse.setMessage("Case Worker Profiles successfully deleted"); + deletionResponse.setStatusCode(NO_CONTENT.value()); + + when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + .thenReturn(responseMock); + when(responseMock.status()).thenReturn(NOT_FOUND.value()); + when(caseWorkerProfileRepository.findByCaseWorkerId(any(String.class))) + .thenReturn(Optional.ofNullable(caseWorkerProfile)); + + CaseWorkerProfilesDeletionResponse deletionResp = + caseWorkerServiceImpl.deleteByUserId(caseWorkerProfile.getCaseWorkerId()); + + assertThat(deletionResp.getStatusCode()).isEqualTo(deletionResponse.getStatusCode()); + assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); + + verify(caseWorkerProfileRepository, times(1)).findByCaseWorkerId(any(String.class)); + verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); + verify(responseMock, times(3)).status(); + verify(userProfileFeignClient, times(1)) + .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + } + + @Test + public void testDeleteUserProfileByUserId_WhenUpReturnsError() { + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + deletionResponse.setMessage("UP Delete request failed for userId: " + caseWorkerProfile.getCaseWorkerId() + + ". With the following UP message: INTERNAL SERVER ERROR"); + deletionResponse.setStatusCode(BAD_REQUEST.value()); + + Response responseMock = mock(Response.class); + + when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + .thenReturn(responseMock); + when(responseMock.status()).thenReturn(BAD_REQUEST.value()); + + CaseWorkerProfilesDeletionResponse deletionResp = + caseWorkerServiceImpl.deleteByUserId(caseWorkerProfile.getCaseWorkerId()); + + assertThat(deletionResp.getStatusCode()).isEqualTo(deletionResponse.getStatusCode()); + assertThat(deletionResp.getMessage()).contains("UP Delete request failed for userId"); + + verify(responseMock, times(3)).status(); + verify(userProfileFeignClient, times(1)) + .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + verify(userProfileFeignClient, times(1)) + .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + } + + @Test + public void testDeleteUserProfileByEmailPattern() { + List caseWorkerProfiles = new ArrayList<>(); + caseWorkerProfiles.add(caseWorkerProfile); + + Response responseMock = mock(Response.class); + + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + deletionResponse.setMessage("Case Worker Profiles successfully deleted"); + deletionResponse.setStatusCode(NO_CONTENT.value()); + + when(userProfileFeignClient.deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN)) + .thenReturn(responseMock); + when(responseMock.status()).thenReturn(NO_CONTENT.value()); + when(caseWorkerProfileRepository + .findByEmailIdIgnoreCaseContaining(COMMON_EMAIL_PATTERN)).thenReturn(caseWorkerProfiles); + + CaseWorkerProfilesDeletionResponse deletionResp = + caseWorkerServiceImpl.deleteByEmailPattern(COMMON_EMAIL_PATTERN); + + assertThat(deletionResp.getStatusCode()).isEqualTo(deletionResponse.getStatusCode()); + assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); + + verify(userProfileFeignClient, times(1)) + .deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN); + verify(responseMock, times(1)).status(); + verify(caseWorkerProfileRepository, times(1)) + .findByEmailIdIgnoreCaseContaining(any(String.class)); + verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); + } + + @Test + public void testDeleteUserProfileByEmailPattern_WhenUpReturns404() { + List caseWorkerProfiles = new ArrayList<>(); + caseWorkerProfiles.add(caseWorkerProfile); + + Response responseMock = mock(Response.class); + + CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); + deletionResponse.setMessage("Case Worker Profiles successfully deleted"); + deletionResponse.setStatusCode(NO_CONTENT.value()); + + when(userProfileFeignClient.deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN)) + .thenReturn(responseMock); + when(responseMock.status()).thenReturn(NOT_FOUND.value()); + when(caseWorkerProfileRepository + .findByEmailIdIgnoreCaseContaining(COMMON_EMAIL_PATTERN)).thenReturn(caseWorkerProfiles); + + CaseWorkerProfilesDeletionResponse deletionResp = + caseWorkerServiceImpl.deleteByEmailPattern(COMMON_EMAIL_PATTERN); + + assertThat(deletionResp.getStatusCode()).isEqualTo(deletionResponse.getStatusCode()); + assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); + + verify(userProfileFeignClient, times(1)) + .deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN); + verify(responseMock, times(2)).status(); + verify(caseWorkerProfileRepository, times(1)) + .findByEmailIdIgnoreCaseContaining(any(String.class)); + verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); + } + + @Test + @SuppressWarnings("unchecked") + public void testValidateUserAfterUpDeleteWhenStatusIs204() { + Optional userProfile = mock(Optional.class); + String userId = UUID.randomUUID().toString(); + + when(userProfile.isPresent()).thenReturn(false); + + CaseWorkerProfilesDeletionResponse deletionResponse = + caseWorkerServiceImpl.validateUserAfterUpDelete(userProfile, userId, 204); + + assertThat(deletionResponse.getStatusCode()).isEqualTo(204); + assertThat(deletionResponse.getMessage()) + .isEqualTo("User deleted in UP but was not present in CRD with userId: " + userId); + + verify(userProfile, times(1)).isPresent(); + } + + @Test + @SuppressWarnings("unchecked") + public void testValidateUserAfterUpDeleteWhenStatusIsNot204() { + Optional userProfile = mock(Optional.class); + String userId = UUID.randomUUID().toString(); + + when(userProfile.isPresent()).thenReturn(false); + + CaseWorkerProfilesDeletionResponse deletionResponse = + caseWorkerServiceImpl.validateUserAfterUpDelete(userProfile, userId, 404); + + assertThat(deletionResponse.getStatusCode()).isEqualTo(404); + assertThat(deletionResponse.getMessage()) + .isEqualTo("User was not present in UP or CRD with userId: " + userId); + + verify(userProfile, times(1)).isPresent(); + } + } \ No newline at end of file From 8320a441d45804e913e9d3f502d9c32e6ae20154 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 14:29:50 +0100 Subject: [PATCH 12/31] RDCC-2390: adding new API to FeatureToggleServiceImpl --- .../reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java index faed62eb0..111c272f3 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java @@ -43,6 +43,8 @@ public void mapServiceToFlag() { CWD_UPLOAD_FILE_FLAG); launchDarklyMap.put("CaseWorkerRefController.caseWorkerFileUpload", CWD_UPLOAD_FILE_FLAG); + launchDarklyMap.put("CaseWorkerRefUsersController.deleteCaseWorkerProfileByIdOrEmailPattern", + CWD_UPLOAD_FILE_FLAG); } @Override From af761e533a68bb2e190635d31180a5c5403fdfa6 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 15 Apr 2021 14:30:45 +0100 Subject: [PATCH 13/31] RDCC-2390: updating new API flag in CaseWorkerRefFunctionalTest --- .../gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java index 874cc3f72..311d5fb4b 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/CaseWorkerRefFunctionalTest.java @@ -73,7 +73,7 @@ public class CaseWorkerRefFunctionalTest extends AuthorizationFunctionalTest { public static final String FETCH_BY_CASEWORKER_ID = "CaseWorkerRefUsersController.fetchCaseworkersById"; public static final String CASEWORKER_FILE_UPLOAD = "CaseWorkerRefController.caseWorkerFileUpload"; public static final String DELETE_CASEWORKER_BY_ID_OR_EMAILPATTERN = - "CaseWorkerRefController.deleteCaseWorkerProfileByIdOrEmailPattern"; + "CaseWorkerRefUsersController.deleteCaseWorkerProfileByIdOrEmailPattern"; public static List caseWorkerIds = new ArrayList<>(); @Test From c95a2f07f2148b3c8df29a9e4baaee9cb49d3965 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Fri, 16 Apr 2021 11:31:11 +0100 Subject: [PATCH 14/31] RDCC-2390: adding unit tests for CaseWorkerProfileRepository --- .../CaseWorkerProfileRepositoryTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/test/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepositoryTest.java b/src/test/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepositoryTest.java index 9b9f13345..2c36f5b81 100644 --- a/src/test/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepositoryTest.java +++ b/src/test/java/uk/gov/hmcts/reform/cwrdapi/repository/CaseWorkerProfileRepositoryTest.java @@ -1,8 +1,10 @@ package uk.gov.hmcts.reform.cwrdapi.repository; import org.junit.Test; +import uk.gov.hmcts.reform.cwrdapi.domain.CaseWorkerProfile; import java.util.ArrayList; +import java.util.Optional; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; @@ -21,4 +23,18 @@ public void findByServiceCodeTest() { assertNotNull(cwProfileRepository.findByEmailIdIn(any())); verify(cwProfileRepository, times(1)).findByEmailIdIn(any()); } + + @Test + public void findByEmailIdIgnoreCaseContaining() { + when(cwProfileRepository.findByEmailIdIgnoreCaseContaining(any())).thenReturn(new ArrayList<>()); + assertNotNull(cwProfileRepository.findByEmailIdIgnoreCaseContaining(any())); + verify(cwProfileRepository, times(1)).findByEmailIdIgnoreCaseContaining(any()); + } + + @Test + public void findByCaseWorkerId() { + when(cwProfileRepository.findByCaseWorkerId(any())).thenReturn(Optional.of(new CaseWorkerProfile())); + assertNotNull(cwProfileRepository.findByCaseWorkerId(any())); + verify(cwProfileRepository, times(1)).findByCaseWorkerId(any()); + } } From 657c6aa3251688e1e011821ecd6f276a045605cb Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Fri, 16 Apr 2021 11:42:48 +0100 Subject: [PATCH 15/31] RDCC-2390: pointing to UP PR containing new Delete API (to be reverted) --- src/functionalTest/resources/application-functional.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functionalTest/resources/application-functional.yaml b/src/functionalTest/resources/application-functional.yaml index 16c6caa9d..33cfa2356 100644 --- a/src/functionalTest/resources/application-functional.yaml +++ b/src/functionalTest/resources/application-functional.yaml @@ -9,4 +9,4 @@ oauth2.client.secret: ${CA_REF_OAUTH2_CLIENT_SECRET:} idam.auth.clientId: ${CA_REF_OAUTH2_CLIENT_ID:} idam.auth.redirectUrl: ${OAUTH2_REDIRECT_URI:https://rd-caseworker-ref-api-aat.service.core-compute-aat.internal/oauth2redirect} s2s-secret: ${S2S_SECRET:} -userProfUrl: http://rd-user-profile-api-aat.service.core-compute-aat.internal \ No newline at end of file +userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal/ \ No newline at end of file From 7bd8a8962b5110537b9f00104a26d65cb6cdcc45 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Fri, 16 Apr 2021 12:19:11 +0100 Subject: [PATCH 16/31] RDCC-2390: reverting FT application.yaml changes --- src/functionalTest/resources/application-functional.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functionalTest/resources/application-functional.yaml b/src/functionalTest/resources/application-functional.yaml index 33cfa2356..16c6caa9d 100644 --- a/src/functionalTest/resources/application-functional.yaml +++ b/src/functionalTest/resources/application-functional.yaml @@ -9,4 +9,4 @@ oauth2.client.secret: ${CA_REF_OAUTH2_CLIENT_SECRET:} idam.auth.clientId: ${CA_REF_OAUTH2_CLIENT_ID:} idam.auth.redirectUrl: ${OAUTH2_REDIRECT_URI:https://rd-caseworker-ref-api-aat.service.core-compute-aat.internal/oauth2redirect} s2s-secret: ${S2S_SECRET:} -userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal/ \ No newline at end of file +userProfUrl: http://rd-user-profile-api-aat.service.core-compute-aat.internal \ No newline at end of file From 69972b36e64652d469374559d5679940502b069b Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Mon, 19 Apr 2021 12:57:18 +0100 Subject: [PATCH 17/31] RDCC-2390: updating UP URL --- .../gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java | 1 + src/functionalTest/resources/application-functional.yaml | 2 +- src/main/resources/application.yaml | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java index 4c2bb83e1..58193848f 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java @@ -94,6 +94,7 @@ public void beforeTestClass(TestContext testContext) { log.info("Configured S2S secret: " + s2sSecret.substring(0, 2) + "************" + s2sSecret.substring(14)); log.info("Configured S2S microservice: " + s2sName); log.info("Configured S2S URL: " + s2sUrl); + log.info("User Profile URL::::: " + baseUrlUserProfile); idamOpenIdClient = new IdamOpenIdClient(configProperties); diff --git a/src/functionalTest/resources/application-functional.yaml b/src/functionalTest/resources/application-functional.yaml index 16c6caa9d..5a6334517 100644 --- a/src/functionalTest/resources/application-functional.yaml +++ b/src/functionalTest/resources/application-functional.yaml @@ -9,4 +9,4 @@ oauth2.client.secret: ${CA_REF_OAUTH2_CLIENT_SECRET:} idam.auth.clientId: ${CA_REF_OAUTH2_CLIENT_ID:} idam.auth.redirectUrl: ${OAUTH2_REDIRECT_URI:https://rd-caseworker-ref-api-aat.service.core-compute-aat.internal/oauth2redirect} s2s-secret: ${S2S_SECRET:} -userProfUrl: http://rd-user-profile-api-aat.service.core-compute-aat.internal \ No newline at end of file +userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 7c97bd86f..2b971165b 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -112,7 +112,7 @@ feign: allow: headers: - authorization -userProfUrl: ${USER_PROFILE_URL:http://rd-user-profile-api-aat.service.core-compute-aat.internal} +userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal crd: publisher: From 39bd1ddb47947204d4427c142785dfb2036ade12 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Mon, 19 Apr 2021 15:26:50 +0100 Subject: [PATCH 18/31] RDCC-2390: updating UserProfile Delete API in FeignClient --- .../feign/UserProfileFeignClient.java | 14 ++++-------- .../service/impl/CaseWorkerServiceImpl.java | 4 ++-- .../impl/CaseWorkerServiceImplTest.java | 22 +++++++++---------- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java index 5f9dc0ee8..d5edacc1c 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/feign/UserProfileFeignClient.java @@ -37,16 +37,10 @@ Response modifyUserRoles(@RequestBody UserProfileUpdatedData modifyRoles, @PathV "Content-Type: application/json"}) Response getUserProfileWithRolesById(@PathVariable String id); - @DeleteMapping(value = "/v1/userprofile/users?userId={userId}") - @RequestLine("DELETE /v1/userprofile/users?userId={userId}") + @DeleteMapping(value = "/v1/userprofile/users") + @RequestLine("DELETE /v1/userprofile/users") @Headers({"Authorization: {authorization}", "ServiceAuthorization: {serviceAuthorization}", "Content-Type: application/json"}) - Response deleteUserProfileById(@PathVariable String userId); - - @DeleteMapping(value = "/v1/userprofile/users?emailPattern={emailPattern}") - @RequestLine("DELETE /v1/userprofile/users?emailPattern={emailPattern}") - @Headers({"Authorization: {authorization}", "ServiceAuthorization: {serviceAuthorization}", - "Content-Type: application/json"}) - Response deleteUserProfileByEmailPattern(@PathVariable String emailPattern); - + Response deleteUserProfile(@RequestParam(value = "userId", required = false) String userId, + @RequestParam(value = "emailPattern", required = false) String emailPattern); } diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java index 07a5e3869..0f25ae3d9 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImpl.java @@ -627,7 +627,7 @@ private ResponseEntity createUserProfileInIdamUP(CaseWorkersProfileCreat public CaseWorkerProfilesDeletionResponse deleteByUserId(String userId) { CaseWorkerProfilesDeletionResponse deletionResponse = new CaseWorkerProfilesDeletionResponse(); - Response userProfileResponse = userProfileFeignClient.deleteUserProfileById(userId); + Response userProfileResponse = userProfileFeignClient.deleteUserProfile(userId, null); if (userProfileResponse.status() == NO_CONTENT.value() || userProfileResponse.status() == NOT_FOUND.value()) { Optional caseWorkerProfile = caseWorkerProfileRepo.findByCaseWorkerId(userId.trim()); @@ -652,7 +652,7 @@ public CaseWorkerProfilesDeletionResponse deleteByEmailPattern(String emailPatte throw new ResourceNotFoundException("No User Profiles found for email pattern: " + emailPattern); } - Response userProfileResponse = userProfileFeignClient.deleteUserProfileByEmailPattern(emailPattern); + Response userProfileResponse = userProfileFeignClient.deleteUserProfile(null, emailPattern); if (userProfileResponse.status() == NO_CONTENT.value() || userProfileResponse.status() == NOT_FOUND.value()) { return deleteUserProfiles(userProfiles); diff --git a/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java b/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java index 522afaa43..2f55c2fcf 100644 --- a/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/reform/cwrdapi/service/impl/CaseWorkerServiceImplTest.java @@ -765,7 +765,7 @@ public void testDeleteUserProfileByUserId() { deletionResponse.setMessage("Case Worker Profiles successfully deleted"); deletionResponse.setStatusCode(NO_CONTENT.value()); - when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + when(userProfileFeignClient.deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null)) .thenReturn(responseMock); when(responseMock.status()).thenReturn(NO_CONTENT.value()); when(caseWorkerProfileRepository.findByCaseWorkerId(any(String.class))) @@ -781,7 +781,7 @@ public void testDeleteUserProfileByUserId() { verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); verify(responseMock, times(2)).status(); verify(userProfileFeignClient, times(1)) - .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + .deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null); } @Test @@ -792,7 +792,7 @@ public void testDeleteUserProfileByUserId_WhenUpReturns404() { deletionResponse.setMessage("Case Worker Profiles successfully deleted"); deletionResponse.setStatusCode(NO_CONTENT.value()); - when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + when(userProfileFeignClient.deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null)) .thenReturn(responseMock); when(responseMock.status()).thenReturn(NOT_FOUND.value()); when(caseWorkerProfileRepository.findByCaseWorkerId(any(String.class))) @@ -808,7 +808,7 @@ public void testDeleteUserProfileByUserId_WhenUpReturns404() { verify(caseWorkerProfileRepository, times(1)).deleteAll(any()); verify(responseMock, times(3)).status(); verify(userProfileFeignClient, times(1)) - .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + .deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null); } @Test @@ -820,7 +820,7 @@ public void testDeleteUserProfileByUserId_WhenUpReturnsError() { Response responseMock = mock(Response.class); - when(userProfileFeignClient.deleteUserProfileById(caseWorkerProfile.getCaseWorkerId())) + when(userProfileFeignClient.deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null)) .thenReturn(responseMock); when(responseMock.status()).thenReturn(BAD_REQUEST.value()); @@ -832,9 +832,9 @@ public void testDeleteUserProfileByUserId_WhenUpReturnsError() { verify(responseMock, times(3)).status(); verify(userProfileFeignClient, times(1)) - .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + .deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null); verify(userProfileFeignClient, times(1)) - .deleteUserProfileById(caseWorkerProfile.getCaseWorkerId()); + .deleteUserProfile(caseWorkerProfile.getCaseWorkerId(), null); } @Test @@ -848,7 +848,7 @@ public void testDeleteUserProfileByEmailPattern() { deletionResponse.setMessage("Case Worker Profiles successfully deleted"); deletionResponse.setStatusCode(NO_CONTENT.value()); - when(userProfileFeignClient.deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN)) + when(userProfileFeignClient.deleteUserProfile(null, COMMON_EMAIL_PATTERN)) .thenReturn(responseMock); when(responseMock.status()).thenReturn(NO_CONTENT.value()); when(caseWorkerProfileRepository @@ -861,7 +861,7 @@ public void testDeleteUserProfileByEmailPattern() { assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); verify(userProfileFeignClient, times(1)) - .deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN); + .deleteUserProfile(null, COMMON_EMAIL_PATTERN); verify(responseMock, times(1)).status(); verify(caseWorkerProfileRepository, times(1)) .findByEmailIdIgnoreCaseContaining(any(String.class)); @@ -879,7 +879,7 @@ public void testDeleteUserProfileByEmailPattern_WhenUpReturns404() { deletionResponse.setMessage("Case Worker Profiles successfully deleted"); deletionResponse.setStatusCode(NO_CONTENT.value()); - when(userProfileFeignClient.deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN)) + when(userProfileFeignClient.deleteUserProfile(null, COMMON_EMAIL_PATTERN)) .thenReturn(responseMock); when(responseMock.status()).thenReturn(NOT_FOUND.value()); when(caseWorkerProfileRepository @@ -892,7 +892,7 @@ public void testDeleteUserProfileByEmailPattern_WhenUpReturns404() { assertThat(deletionResp.getMessage()).isEqualTo(deletionResponse.getMessage()); verify(userProfileFeignClient, times(1)) - .deleteUserProfileByEmailPattern(COMMON_EMAIL_PATTERN); + .deleteUserProfile(null, COMMON_EMAIL_PATTERN); verify(responseMock, times(2)).status(); verify(caseWorkerProfileRepository, times(1)) .findByEmailIdIgnoreCaseContaining(any(String.class)); From 4d75068b27e5a480f5dab4627536f5263326fa99 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Tue, 20 Apr 2021 09:54:19 +0100 Subject: [PATCH 19/31] RDCC-2390: creating Constant for Error Message --- .../cwrdapi/controllers/CaseWorkerRefUsersController.java | 4 +++- .../reform/cwrdapi/controllers/constants/ErrorConstants.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index 0d49486f0..ff8b66480 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -23,6 +23,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import uk.gov.hmcts.reform.cwrdapi.controllers.advice.InvalidRequestException; +import uk.gov.hmcts.reform.cwrdapi.controllers.constants.ErrorConstants; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfileCreationResponse; @@ -37,6 +38,7 @@ import static org.apache.commons.lang3.ObjectUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; +import static uk.gov.hmcts.reform.cwrdapi.controllers.constants.ErrorConstants.NO_USER_ID_OR_EMAIL_PATTERN_PROVIDED_TO_DELETE; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.BAD_REQUEST; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.FORBIDDEN_ERROR; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.INTERNAL_SERVER_ERROR; @@ -240,7 +242,7 @@ public ResponseEntity deleteCaseWorkerProfil resource = caseWorkerService.deleteByEmailPattern(emailPattern); } else { - throw new InvalidRequestException("No User ID or Email Pattern provided to delete the User(s)"); + throw new InvalidRequestException(NO_USER_ID_OR_EMAIL_PATTERN_PROVIDED_TO_DELETE.getErrorMessage()); } return ResponseEntity.status(resource.getStatusCode()).body(resource); diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/constants/ErrorConstants.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/constants/ErrorConstants.java index 43e21bf5e..35cf8f969 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/constants/ErrorConstants.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/constants/ErrorConstants.java @@ -20,7 +20,9 @@ public enum ErrorConstants { RUNTIME_EXCEPTION("8 : Sorry, there is a problem with the service. Try again later"), FILE_UPLOAD_IN_PROGRESS("9 : File upload is already in progress." - + " Please try again once existing file upload is completed"); + + " Please try again once existing file upload is completed"), + + NO_USER_ID_OR_EMAIL_PATTERN_PROVIDED_TO_DELETE("No User ID or Email Pattern provided to delete the User(s)"); private final String errorMessage; From d30b91e5f330fd7826947f4e04dbcd36bda52eea Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Tue, 20 Apr 2021 09:55:01 +0100 Subject: [PATCH 20/31] RDCC-2390: changing to static import --- .../reform/cwrdapi/controllers/CaseWorkerRefUsersController.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index ff8b66480..90593f354 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -23,7 +23,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import uk.gov.hmcts.reform.cwrdapi.controllers.advice.InvalidRequestException; -import uk.gov.hmcts.reform.cwrdapi.controllers.constants.ErrorConstants; import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserRequest; import uk.gov.hmcts.reform.cwrdapi.controllers.response.CaseWorkerProfileCreationResponse; From a9a4beca0c154eeba3527e9179ab1f849f6b554f Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 21 Apr 2021 11:49:10 +0100 Subject: [PATCH 21/31] RDCC-2390: adding new LD Flag to FeatureToggleService --- .../reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java index 111c272f3..2f1196b20 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/service/impl/FeatureToggleServiceImpl.java @@ -15,6 +15,7 @@ public class FeatureToggleServiceImpl implements FeatureToggleService { public static final String CWD_UPLOAD_FILE_FLAG = "cwd-upload-file-flag"; + public static final String CWD_DELETE_BY_ID_OR_EMAILPATTERN_FLAG = "delete-caseworker-by-id-or-emailpattern"; @Autowired private final LDClient ldClient; @@ -44,7 +45,7 @@ public void mapServiceToFlag() { launchDarklyMap.put("CaseWorkerRefController.caseWorkerFileUpload", CWD_UPLOAD_FILE_FLAG); launchDarklyMap.put("CaseWorkerRefUsersController.deleteCaseWorkerProfileByIdOrEmailPattern", - CWD_UPLOAD_FILE_FLAG); + CWD_DELETE_BY_ID_OR_EMAILPATTERN_FLAG); } @Override From 4bb544acc98cfb00c33feef9c26e24ce06db4437 Mon Sep 17 00:00:00 2001 From: Adil Cassam Oozeerally <49557838+AdilOoze@users.noreply.github.com> Date: Wed, 21 Apr 2021 16:13:38 +0100 Subject: [PATCH 22/31] RDCC-2390: removing UP URL Logger used for debugging --- .../gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java index 58193848f..5b96f9e2a 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/cwrdapi/AuthorizationFunctionalTest.java @@ -94,7 +94,6 @@ public void beforeTestClass(TestContext testContext) { log.info("Configured S2S secret: " + s2sSecret.substring(0, 2) + "************" + s2sSecret.substring(14)); log.info("Configured S2S microservice: " + s2sName); log.info("Configured S2S URL: " + s2sUrl); - log.info("User Profile URL::::: " + baseUrlUserProfile); idamOpenIdClient = new IdamOpenIdClient(configProperties); @@ -161,4 +160,4 @@ public UserProfileResponse getUserProfileFromUp(String email) { "/v1/userprofile/roles?email=" + email, UserProfileResponse.class, baseUrlUserProfile); } -} \ No newline at end of file +} From a9f6e09846c7ca30fa8784535fc1387afa2a99b3 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 22 Apr 2021 11:44:34 +0100 Subject: [PATCH 23/31] RDCC-2390: adding note to Delete API --- .../reform/cwrdapi/controllers/CaseWorkerRefUsersController.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index 90593f354..eda581dc8 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -191,6 +191,7 @@ public ResponseEntity fetchCaseworkersById(@RequestBody UserRequest user } @ApiOperation(value = "Delete Case Worker Profiles by User ID or Email Pattern", + notes = "This API is only for use in non Prod environments", authorizations = { @Authorization(value = "ServiceAuthorization"), @Authorization(value = "Authorization") From d8709928dd87ee983bec4efa5e2158eec3916280 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 28 Apr 2021 15:58:27 +0100 Subject: [PATCH 24/31] RDCC-2390: adding additional security check to API & related changes --- .../values.preview.template.yaml | 1 + charts/rd-caseworker-ref-api/values.yaml | 3 ++- .../cwrdapi/FetchCaseworkersByIdProviderTest.java | 2 +- src/integrationTest/resources/application-test.yml | 2 ++ .../controllers/CaseWorkerRefUsersController.java | 13 ++++++++++++- .../reform/cwrdapi/util/CaseWorkerConstants.java | 2 ++ src/main/resources/application.yaml | 2 ++ 7 files changed, 22 insertions(+), 3 deletions(-) diff --git a/charts/rd-caseworker-ref-api/values.preview.template.yaml b/charts/rd-caseworker-ref-api/values.preview.template.yaml index 435b146c9..b0910f429 100644 --- a/charts/rd-caseworker-ref-api/values.preview.template.yaml +++ b/charts/rd-caseworker-ref-api/values.preview.template.yaml @@ -13,6 +13,7 @@ java: CWRD_MQ_TRUST_ALL_CERTS: false CWRD_DATA_PER_MESSAGE: 50 LAUNCH_DARKLY_ENV: "preview" + ENVIRONMENT_NAME: "preview" postgresql: enabled: true postgresqlUsername: dbrdcaseworker diff --git a/charts/rd-caseworker-ref-api/values.yaml b/charts/rd-caseworker-ref-api/values.yaml index c3fa55b1a..43b395c85 100644 --- a/charts/rd-caseworker-ref-api/values.yaml +++ b/charts/rd-caseworker-ref-api/values.yaml @@ -14,7 +14,8 @@ java: CWRD_MQ_TOPIC_NAME: rd-caseworker-topic-{{ .Values.global.environment }} CWRD_MQ_TRUST_ALL_CERTS: false CWRD_DATA_PER_MESSAGE: 50 - LAUNCH_DARKLY_ENV: "{{ .Values.global.environment }}" + LAUNCH_DARKLY_ENV: {{ .Values.global.environment }} + ENVIRONMENT_NAME: {{ .Values.global.environment }} IDAM_URL: https://idam-api.{{ .Values.global.environment }}.platform.hmcts.net USER_PROFILE_URL: http://rd-user-profile-api-{{ .Values.global.environment }}.service.core-compute-{{ .Values.global.environment }}.internal OIDC_ISSUER_URL: https://forgerock-am.service.core-compute-idam-{{ .Values.global.environment }}.internal:8443/openam/oauth2/hmcts diff --git a/src/contractTest/java/uk/gov/hmcts/reform/cwrdapi/FetchCaseworkersByIdProviderTest.java b/src/contractTest/java/uk/gov/hmcts/reform/cwrdapi/FetchCaseworkersByIdProviderTest.java index 39f629b46..41854f6da 100644 --- a/src/contractTest/java/uk/gov/hmcts/reform/cwrdapi/FetchCaseworkersByIdProviderTest.java +++ b/src/contractTest/java/uk/gov/hmcts/reform/cwrdapi/FetchCaseworkersByIdProviderTest.java @@ -75,7 +75,7 @@ void beforeCreate(PactVerificationContext context) { MockMvcTestTarget testTarget = new MockMvcTestTarget(); testTarget.setControllers( new CaseWorkerRefUsersController( - "RD-Caseworker-Ref-Api", caseWorkerServiceImpl)); + "RD-Caseworker-Ref-Api", "preview", caseWorkerServiceImpl)); if (context != null) { context.setTarget(testTarget); } diff --git a/src/integrationTest/resources/application-test.yml b/src/integrationTest/resources/application-test.yml index b05a33564..53aa9889e 100644 --- a/src/integrationTest/resources/application-test.yml +++ b/src/integrationTest/resources/application-test.yml @@ -100,6 +100,8 @@ oidc: issuer: ${OIDC_ISSUER:http://127.0.0.1:5000/openam/oauth2/hmcts} expiration: 14400000 # milliseconds 4 hours +environment_name: ${ENVIRONMENT_NAME:prod} + ## user profile feign connection userProfUrl: ${USER_PROFILE_URL:http://127.0.0.1:8091} loggingComponentName: RD-Caseworker-Ref-Api diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index eda581dc8..a6fcef30b 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -12,6 +12,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.annotation.Secured; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.DeleteMapping; @@ -38,6 +39,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static uk.gov.hmcts.reform.cwrdapi.controllers.constants.ErrorConstants.NO_USER_ID_OR_EMAIL_PATTERN_PROVIDED_TO_DELETE; +import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.API_IS_NOT_AVAILABLE_IN_PROD_ENV; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.BAD_REQUEST; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.FORBIDDEN_ERROR; import static uk.gov.hmcts.reform.cwrdapi.util.CaseWorkerConstants.INTERNAL_SERVER_ERROR; @@ -52,13 +54,16 @@ ) @RestController @Slf4j -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor public class CaseWorkerRefUsersController { @Value("${loggingComponentName}") private String loggingComponentName; + @Value("${environment_name}") + private String environmentName; + @Autowired CaseWorkerService caseWorkerService; @@ -233,6 +238,12 @@ public ResponseEntity deleteCaseWorkerProfil * This API will need to be revisited if it is to be used for business functionality. */ + log.info("ENVIRONMENT NAME:::::: " + environmentName); + + if (environmentName.equalsIgnoreCase("PROD")) { + throw new AccessDeniedException(API_IS_NOT_AVAILABLE_IN_PROD_ENV); + } + CaseWorkerProfilesDeletionResponse resource; if (isNotBlank(userId)) { diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerConstants.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerConstants.java index 27538bd22..161a9a659 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerConstants.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/util/CaseWorkerConstants.java @@ -136,4 +136,6 @@ private CaseWorkerConstants() { public static final String RESPONSE_BODY_MISSING_FROM_UP = "Response Body is missing from User Profile"; public static final String DUPLICATE_EMAIL_PROFILES = "User record in row ID %s is duplicate to another row. " + "Please ensure that the record is not duplicate and try again"; + + public static final String API_IS_NOT_AVAILABLE_IN_PROD_ENV = "This API is not available in Production Environment"; } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 2b971165b..17c6ed193 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -107,6 +107,8 @@ idam: oidc.issuer: ${OIDC_ISSUER_URL:https://forgerock-am.service.core-compute-idam-aat.internal:8443/openam/oauth2/hmcts} +environment_name: ${ENVIRONMENT_NAME:prod} + loggingComponentName: RD-Caseworker-Ref-Api feign: allow: From f2c64c0451c9d5a1c5b55deb78b9a97a7b0c7d30 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 28 Apr 2021 16:02:44 +0100 Subject: [PATCH 25/31] RDCC-2390: surrounding values.yaml entry in quotes --- charts/rd-caseworker-ref-api/values.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/charts/rd-caseworker-ref-api/values.yaml b/charts/rd-caseworker-ref-api/values.yaml index 43b395c85..8dc8af58f 100644 --- a/charts/rd-caseworker-ref-api/values.yaml +++ b/charts/rd-caseworker-ref-api/values.yaml @@ -14,8 +14,8 @@ java: CWRD_MQ_TOPIC_NAME: rd-caseworker-topic-{{ .Values.global.environment }} CWRD_MQ_TRUST_ALL_CERTS: false CWRD_DATA_PER_MESSAGE: 50 - LAUNCH_DARKLY_ENV: {{ .Values.global.environment }} - ENVIRONMENT_NAME: {{ .Values.global.environment }} + LAUNCH_DARKLY_ENV: "{{ .Values.global.environment }}" + ENVIRONMENT_NAME: "{{ .Values.global.environment }}" IDAM_URL: https://idam-api.{{ .Values.global.environment }}.platform.hmcts.net USER_PROFILE_URL: http://rd-user-profile-api-{{ .Values.global.environment }}.service.core-compute-{{ .Values.global.environment }}.internal OIDC_ISSUER_URL: https://forgerock-am.service.core-compute-idam-{{ .Values.global.environment }}.internal:8443/openam/oauth2/hmcts From 7557237cde4eed7721f49d68946a716085546282 Mon Sep 17 00:00:00 2001 From: hmcts-jenkins-rd <62425331+hmcts-jenkins-rd[bot]@users.noreply.github.com> Date: Wed, 28 Apr 2021 15:03:33 +0000 Subject: [PATCH 26/31] Bumping chart version --- charts/rd-caseworker-ref-api/Chart.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/charts/rd-caseworker-ref-api/Chart.yaml b/charts/rd-caseworker-ref-api/Chart.yaml index 85d12dca3..b3e8349a7 100644 --- a/charts/rd-caseworker-ref-api/Chart.yaml +++ b/charts/rd-caseworker-ref-api/Chart.yaml @@ -3,7 +3,7 @@ appVersion: "1.0" description: A Helm chart for rd-caseworker-ref-api name: rd-caseworker-ref-api home: https://github.com/hmcts/rd-caseworker-ref-api -version: 0.0.15 +version: 0.0.16 maintainers: - name: Reference Data Team dependencies: From ee9e8b739362ca0bb1e5a10af5233ca1f72d61d4 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 28 Apr 2021 16:20:15 +0100 Subject: [PATCH 27/31] RDCC-2390: changing environment_name value to 'preview' for integration tests --- src/integrationTest/resources/application-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/integrationTest/resources/application-test.yml b/src/integrationTest/resources/application-test.yml index 53aa9889e..f7c38090e 100644 --- a/src/integrationTest/resources/application-test.yml +++ b/src/integrationTest/resources/application-test.yml @@ -100,7 +100,7 @@ oidc: issuer: ${OIDC_ISSUER:http://127.0.0.1:5000/openam/oauth2/hmcts} expiration: 14400000 # milliseconds 4 hours -environment_name: ${ENVIRONMENT_NAME:prod} +environment_name: ${ENVIRONMENT_NAME:preview} ## user profile feign connection userProfUrl: ${USER_PROFILE_URL:http://127.0.0.1:8091} From f6d389a2124d37bc2f29eb85fb6fbc2fb1bdf972 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Wed, 28 Apr 2021 16:25:03 +0100 Subject: [PATCH 28/31] RDCC-2390: flipping if statement --- .../cwrdapi/controllers/CaseWorkerRefUsersController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java index a6fcef30b..bdede511d 100644 --- a/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java +++ b/src/main/java/uk/gov/hmcts/reform/cwrdapi/controllers/CaseWorkerRefUsersController.java @@ -240,7 +240,7 @@ public ResponseEntity deleteCaseWorkerProfil log.info("ENVIRONMENT NAME:::::: " + environmentName); - if (environmentName.equalsIgnoreCase("PROD")) { + if ("PROD".equalsIgnoreCase(environmentName)) { throw new AccessDeniedException(API_IS_NOT_AVAILABLE_IN_PROD_ENV); } From cc1408bee2538fe5d6f497d48d44024825ce4cb5 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 29 Apr 2021 10:07:00 +0100 Subject: [PATCH 29/31] RDCC-2390: changing value from 'preview' to 'prod' for testing --- charts/rd-caseworker-ref-api/values.preview.template.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/charts/rd-caseworker-ref-api/values.preview.template.yaml b/charts/rd-caseworker-ref-api/values.preview.template.yaml index b0910f429..23c598e17 100644 --- a/charts/rd-caseworker-ref-api/values.preview.template.yaml +++ b/charts/rd-caseworker-ref-api/values.preview.template.yaml @@ -13,7 +13,7 @@ java: CWRD_MQ_TRUST_ALL_CERTS: false CWRD_DATA_PER_MESSAGE: 50 LAUNCH_DARKLY_ENV: "preview" - ENVIRONMENT_NAME: "preview" + ENVIRONMENT_NAME: "prod" postgresql: enabled: true postgresqlUsername: dbrdcaseworker From 0fd1ca48e79b393b92a1461c14b2f1e0082ee4b2 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 29 Apr 2021 10:43:11 +0100 Subject: [PATCH 30/31] RDCC-2390: reverting 'prod' value to 'preview' after successful testing --- charts/rd-caseworker-ref-api/values.preview.template.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/charts/rd-caseworker-ref-api/values.preview.template.yaml b/charts/rd-caseworker-ref-api/values.preview.template.yaml index 23c598e17..b0910f429 100644 --- a/charts/rd-caseworker-ref-api/values.preview.template.yaml +++ b/charts/rd-caseworker-ref-api/values.preview.template.yaml @@ -13,7 +13,7 @@ java: CWRD_MQ_TRUST_ALL_CERTS: false CWRD_DATA_PER_MESSAGE: 50 LAUNCH_DARKLY_ENV: "preview" - ENVIRONMENT_NAME: "prod" + ENVIRONMENT_NAME: "preview" postgresql: enabled: true postgresqlUsername: dbrdcaseworker From a7946e2fc84d69cefdf576170b18ab77b433bba4 Mon Sep 17 00:00:00 2001 From: AdilOoze Date: Thu, 29 Apr 2021 12:51:34 +0100 Subject: [PATCH 31/31] RDCC-2390: changing userProfileUrl from PR to AAT --- src/functionalTest/resources/application-functional.yaml | 2 +- src/main/resources/application.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functionalTest/resources/application-functional.yaml b/src/functionalTest/resources/application-functional.yaml index 5a6334517..16c6caa9d 100644 --- a/src/functionalTest/resources/application-functional.yaml +++ b/src/functionalTest/resources/application-functional.yaml @@ -9,4 +9,4 @@ oauth2.client.secret: ${CA_REF_OAUTH2_CLIENT_SECRET:} idam.auth.clientId: ${CA_REF_OAUTH2_CLIENT_ID:} idam.auth.redirectUrl: ${OAUTH2_REDIRECT_URI:https://rd-caseworker-ref-api-aat.service.core-compute-aat.internal/oauth2redirect} s2s-secret: ${S2S_SECRET:} -userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal \ No newline at end of file +userProfUrl: http://rd-user-profile-api-aat.service.core-compute-aat.internal \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 17c6ed193..ad96086db 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -114,7 +114,7 @@ feign: allow: headers: - authorization -userProfUrl: http://rd-user-profile-api-pr-664.service.core-compute-preview.internal +userProfUrl: ${USER_PROFILE_URL:http://rd-user-profile-api-aat.service.core-compute-aat.internal} crd: publisher: