> crestCourtSitesCache = new ConcurrentHashMap<>();
private final XhibitReferenceDataValidator xhibitReferenceDataValidator = new XhibitReferenceDataValidator();
private static final String COURT_DETAILS_NOT_FOUND = "Cannot find court details with courtCentre %s";
- private static final String COURT_MAPPING_NOT_FOUND_FOR_TYPE =
- "Cannot find court mapping for courtCentre %s with court type %s";
private static final Logger LOGGER = LoggerFactory.getLogger(CommonXhibitReferenceDataService.class);
@@ -92,48 +90,17 @@ public CourtLocation getCrownCourtDetails(final UUID courtCentreId) {
return createCrownCourtLocation(court);
}
- /**
- * Xhibit court location for a committing court (magistrates or crown). Resolution uses
- * {@link ReferenceDataCache#getCpXhibitCourtMappingsMapCache(UUID)}: mags
- * ({@code referencedata.query.cp-xhibit-mags-court-mapping}, including empty {@code {}}), else
- * {@code referencedata.query.cp-xhibit-court-mappings}.
- *
- * When {@code courtHouseType} is set (e.g. from offence committing court), the mapping with that
- * {@link CourtMapping#getCourtType()} is used; otherwise the first mapping from the cache is used.
- */
- public CourtLocation getCriminalCourtDetails(final UUID courtCentreId, final String courtHouseType) {
-
- final List mappings = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId)
- .orElseThrow(() -> new InvalidReferenceDataException(format(COURT_DETAILS_NOT_FOUND, courtCentreId)));
- if (mappings.isEmpty()) {
- throw new InvalidReferenceDataException(format(COURT_DETAILS_NOT_FOUND, courtCentreId));
- }
-
- final CourtMapping court;
- if (courtHouseType != null && !courtHouseType.isBlank()) {
- court = mappings.stream()
- .filter(m -> courtHouseType.equals(m.getCourtType()))
- .findFirst()
- .orElseThrow(() -> new InvalidReferenceDataException(
- format(COURT_MAPPING_NOT_FOUND_FOR_TYPE, courtCentreId, courtHouseType)));
- } else {
- court = mappings.stream()
- .findFirst()
- .orElseThrow(() -> new InvalidReferenceDataException(format(COURT_DETAILS_NOT_FOUND, courtCentreId)));
- }
+ public CourtLocation getMagsCourtDetails(final UUID courtCentreId) {
- return createCourtLocationFromCourtMapping(court);
- }
+ final CourtMapping court = referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId)
+ .orElseThrow(() -> new InvalidReferenceDataException(format(COURT_DETAILS_NOT_FOUND, courtCentreId)))
+ .stream()
+ .findFirst()
+ .orElseThrow(() -> new InvalidReferenceDataException(format(COURT_DETAILS_NOT_FOUND, courtCentreId)));
- /**
- * Same as {@link #getCriminalCourtDetails(UUID, String)} with no {@code courtHouseType} (first combined mapping).
- */
- public CourtLocation getCriminalCourtDetails(final UUID courtCentreId) {
- return getCriminalCourtDetails(courtCentreId, null);
+ return createMagsCourtLocation(court);
}
-
-
public List getCrestCourtSitesForCrownCourtCentre(UUID courtCentreId) {
return crestCourtSitesCache.computeIfAbsent(courtCentreId.toString(), id -> fetchCrestCourtSitesFromDatabase(courtCentreId));
}
@@ -247,11 +214,4 @@ private CourtLocation createMagsCourtLocation(final CourtMapping courtMapping) {
courtMapping.getCrestCourtSiteCode(),
courtMapping.getCourtType());
}
-
- private CourtLocation createCourtLocationFromCourtMapping(final CourtMapping courtMapping) {
- if (MAGISTRATES_COURT_TYPE.equals(courtMapping.getCourtType())) {
- return createMagsCourtLocation(courtMapping);
- }
- return createCrownCourtLocation(courtMapping);
- }
}
diff --git a/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCache.java b/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCache.java
index af16020b6..6bf506192 100644
--- a/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCache.java
+++ b/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCache.java
@@ -3,7 +3,6 @@
import uk.gov.moj.cpp.listing.common.xhibit.exception.InvalidReferenceDataException;
import uk.gov.moj.cpp.listing.common.xhibit.model.CourtCentreRoomKey;
import uk.gov.moj.cpp.listing.domain.referencedata.CourtMapping;
-import uk.gov.moj.cpp.listing.domain.referencedata.CourtMappingsList;
import uk.gov.moj.cpp.listing.domain.referencedata.CourtRoomMapping;
import uk.gov.moj.cpp.listing.domain.referencedata.CourtRoomMappingsList;
import uk.gov.moj.cpp.listing.domain.referencedata.HearingType;
@@ -13,8 +12,6 @@
import uk.gov.moj.cpp.listing.domain.referencedata.OrganisationUnitList;
import uk.gov.moj.cpp.listing.domain.xhibit.CourtLocation;
-import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -22,7 +19,6 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
@@ -41,15 +37,6 @@ public class ReferenceDataCache {
private final Map> magsCourtMappingListMapCache = new ConcurrentHashMap<>();
- private static final String MAGISTRATES_COURT_TYPE = "MAGISTRATES_COURT";
-
- /**
- * CP Xhibit court mappings for committing court (lazy per court centre): mags from
- * {@code referencedata.query.cp-xhibit-mags-court-mapping}, else
- * {@code referencedata.query.cp-xhibit-court-mappings} by court centre id.
- */
- private final Map> lazyCpXhibitCourtMappingsByCourtCentreId = new ConcurrentHashMap<>();
-
private final Map hearingTypesMapCache = new ConcurrentHashMap<>();
private final Map> cpCourtRoomCache = new ConcurrentHashMap<>();
@@ -80,23 +67,9 @@ public void initReferenceData() {
public Optional> getCrownCourtMappingsMapCache(final UUID courtCentreId) {
OrganisationUnit organisationUnit = organisationUnitMapByIdCache.get(courtCentreId);
- if (organisationUnit == null) {
- return Optional.empty();
- }
-
- final String oucode = organisationUnit.getOucode();
- final List cachedMappings = crownCourtMappingListMapCache.get(oucode);
- if (cachedMappings != null && !cachedMappings.isEmpty()) {
- return Optional.of(cachedMappings);
- }
-
- return referenceDataLoader.getXhibitCrownCourtMappings(courtCentreId)
- .map(CourtMappingsList::getCpXhibitCourtMappings)
- .filter(mappings -> !mappings.isEmpty())
- .map(mappings -> {
- cacheCrownCourtMappings(mappings);
- return crownCourtMappingListMapCache.get(oucode);
- });
+ return organisationUnit == null
+ ? Optional.empty()
+ : Optional.ofNullable(crownCourtMappingListMapCache.get(organisationUnit.getOucode()));
}
public Optional> getMagsCourtMappingsMapCache(final UUID courtCentreId) {
@@ -116,56 +89,6 @@ public Optional> getMagsCourtMappingsMapCache(final UUID cour
);
}
- /**
- * Xhibit court mappings for committing court: magistrates via
- * {@code referencedata.query.cp-xhibit-mags-court-mapping} (including HTTP 200 with empty {@code {}}),
- * then if absent or empty — {@code referencedata.query.cp-xhibit-court-mappings} by court centre id.
- */
- public Optional> getCpXhibitCourtMappingsMapCache(final UUID courtCentreId) {
- if (organisationUnitMapByIdCache.get(courtCentreId) == null) {
- return Optional.empty();
- }
- return Optional.of(
- lazyCpXhibitCourtMappingsByCourtCentreId.computeIfAbsent(courtCentreId, this::resolveCpXhibitCourtMappingsWithMagsFirst)
- );
- }
-
- private List resolveCpXhibitCourtMappingsWithMagsFirst(final UUID courtCentreId) {
- final OrganisationUnit organisationUnit = organisationUnitMapByIdCache.get(courtCentreId);
- if (organisationUnit == null) {
- return Collections.emptyList();
- }
- final String oucode = organisationUnit.getOucode();
-
- final List magsMappings = referenceDataLoader.getXhibitMagsCourtMappings(oucode)
- .map(CourtMappingsList::getCpXhibitCourtMappings)
- .filter(list -> list != null && !list.isEmpty())
- .orElse(Collections.emptyList());
-
- if (!magsMappings.isEmpty()) {
- List updatedMappings = magsMappings.stream()
- .map(mapping -> new CourtMapping.Builder()
- .withId(mapping.getId())
- .withOucode(mapping.getOucode())
- .withCrestCourtId(mapping.getCrestCourtId())
- .withCrestCourtSiteId(mapping.getCrestCourtSiteId())
- .withCrestCourtName(mapping.getCrestCourtName())
- .withCrestCourtShortName(mapping.getCrestCourtShortName())
- .withCrestCourtSiteName(mapping.getCrestCourtSiteName())
- .withCrestCourtSiteCode(mapping.getCrestCourtSiteCode())
- .withCourtType(MAGISTRATES_COURT_TYPE)
- .build())
- .collect(Collectors.toList());
- return new ArrayList<>(updatedMappings);
- }
-
-
- return referenceDataLoader.getXhibitCrownCourtMappings(courtCentreId)
- .map(CourtMappingsList::getCpXhibitCourtMappings)
- .filter(list -> list != null && !list.isEmpty())
- .orElse(Collections.emptyList());
- }
-
public Optional getJudiciariesMapCache(final UUID judiciaryId) {
return Optional.ofNullable(
judiciariesMapCache.computeIfAbsent(judiciaryId,
@@ -242,20 +165,16 @@ private synchronized void ensureCrownCourtMappingsInitialized() {
}
private void initCrownCourtMappingsList() {
- referenceDataLoader.getXhibitCrownCourtMappings()
- .map(CourtMappingsList::getCpXhibitCourtMappings)
- .ifPresent(this::cacheCrownCourtMappings);
- }
-
- private void cacheCrownCourtMappings(final List courtMappings) {
- courtMappings.forEach(courtMapping -> {
- crownCourtLocationListMapCache
- .computeIfAbsent(courtMapping.getCrestCourtId(), k -> new java.util.concurrent.CopyOnWriteArrayList<>())
- .add(createCourtLocation(courtMapping));
-
- crownCourtMappingListMapCache
- .computeIfAbsent(courtMapping.getOucode(), k -> new java.util.concurrent.CopyOnWriteArrayList<>())
- .add(courtMapping);
+ referenceDataLoader.getXhibitCrownCourtMappings().ifPresent(courtMappingsList -> {
+ courtMappingsList.getCpXhibitCourtMappings().forEach(courtMapping -> {
+ crownCourtLocationListMapCache
+ .computeIfAbsent(courtMapping.getCrestCourtId(), k -> new java.util.concurrent.CopyOnWriteArrayList<>())
+ .add(createCourtLocation(courtMapping));
+
+ crownCourtMappingListMapCache
+ .computeIfAbsent(courtMapping.getOucode(), k -> new java.util.concurrent.CopyOnWriteArrayList<>())
+ .add(courtMapping);
+ });
});
}
diff --git a/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoader.java b/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoader.java
index ad28422a8..07c1021bf 100644
--- a/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoader.java
+++ b/listing-common/src/main/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoader.java
@@ -145,22 +145,7 @@ public Optional getXhibitMagsCourtMappings(final String oucod
final Envelope response = requester.requestAsAdmin(requestEnvelope, CourtMapping.class);
- if (Objects.isNull(response) || Objects.isNull(response.payload())) {
- return empty();
- }
- final CourtMapping payload = response.payload();
- if (isEmptyMagsCourtMappingPayload(payload)) {
- return empty();
- }
- return of(new CourtMappingsList(asList(payload)));
- }
-
- /**
- * Referencedata returns HTTP 200 with {@code {}} when no mags mapping exists; that deserialises to a
- * {@link CourtMapping} with no id/oucode.
- */
- private static boolean isEmptyMagsCourtMappingPayload(final CourtMapping payload) {
- return payload.getId() == null && payload.getOucode() == null;
+ return Objects.isNull(response) ? empty() : of((new CourtMappingsList(asList(response.payload()))));
}
public Optional getCourtRoomMappingsList(UUID courtCentreId) {
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerSearchServiceTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerSearchServiceTest.java
new file mode 100644
index 000000000..b3e37ba77
--- /dev/null
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerSearchServiceTest.java
@@ -0,0 +1,89 @@
+package uk.gov.moj.cpp.listing.common.service;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import uk.gov.justice.services.common.converter.StringToJsonObjectConverter;
+import uk.gov.justice.services.core.dispatcher.SystemUserProvider;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+
+import javax.ws.rs.core.Response;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+@ExtendWith(MockitoExtension.class)
+class CourtSchedulerSearchServiceTest {
+
+ private static final String BASE_URI = "http://test-uri";
+ private static final UUID TEST_USER_ID = UUID.randomUUID();
+
+ @Mock
+ private SystemUserProvider systemUserProvider;
+ @Mock
+ private StringToJsonObjectConverter stringToJsonObjectConverter;
+ @Mock
+ private HttpClientBuilder httpClientBuilder;
+ @Mock
+ private CloseableHttpClient httpClient;
+ @Mock
+ private CloseableHttpResponse httpResponse;
+ @Mock
+ private StatusLine statusLine;
+ @Captor
+ private ArgumentCaptor httpGetCaptor;
+
+ @InjectMocks
+ private CourtSchedulerSearchService courtSchedulerSearchService;
+
+ @BeforeEach
+ void setUp() {
+ courtSchedulerSearchService.baseUri = BASE_URI;
+ }
+
+ @Test
+ void searchAvailableJudiciaries_shouldCallCourtSchedulerEndpoint() throws Exception {
+ final Map params = new HashMap<>();
+ params.put("search", "ai");
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpGet.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.OK.getStatusCode());
+ when(httpResponse.getEntity()).thenReturn(mock(HttpEntity.class));
+ when(stringToJsonObjectConverter.convert(any())).thenReturn(mock(javax.json.JsonObject.class));
+
+ final Response response = courtSchedulerSearchService.searchAvailableJudiciaries(params);
+
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ verify(httpClient).execute(httpGetCaptor.capture());
+ assertThat(httpGetCaptor.getValue().getURI().toString(),
+ is(BASE_URI + "/judiciaries/search-available?search=ai"));
+ }
+ }
+}
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerServiceAdapterTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerServiceAdapterTest.java
index 1d884edb2..525096a0c 100644
--- a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerServiceAdapterTest.java
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/CourtSchedulerServiceAdapterTest.java
@@ -6,6 +6,7 @@
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.when;
import static uk.gov.moj.cpp.listing.common.utils.FileUtil.givenPayload;
@@ -36,7 +37,7 @@
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
-public class CourtSchedulerServiceAdapterTest {
+class CourtSchedulerServiceAdapterTest {
@InjectMocks
private CourtSchedulerServiceAdapter courtSchedulerServiceAdapter;
@@ -54,7 +55,7 @@ public class CourtSchedulerServiceAdapterTest {
private JsonObjectToObjectConverter jsonObjectConverter;
@Test
- public void shouldGetJudicialRoles() {
+ void shouldGetJudicialRoles() {
final String startDate = LocalDate.now().toString();
final String ouCode = "B01LY00";
final Optional courtSessionOptional = Optional.of("AM");
@@ -75,16 +76,16 @@ public void shouldGetJudicialRoles() {
final JsonObject judiciaryJsonObject = (JsonObject) ((JsonObject) hearingSlotsResponse.getJsonArray("hearingSlots").get(0)).getJsonArray("judiciaries").get(index);
- assertThat(judicialRole.getJudicialId().toString(), is(judiciaryJsonObject.getString("judiciaryId")));
- assertThat(judicialRole.getIsBenchChairman(), is(Optional.of(judiciaryJsonObject.getBoolean("benchChairman"))));
- assertThat(judicialRole.getIsDeputy(), is(Optional.of(judiciaryJsonObject.getBoolean("deputy"))));
+ assertThat(judicialRole.getJudicialId().toString(), is(judiciaryJsonObject.getString("id")));
+ assertThat(judicialRole.getIsBenchChairman(), is(Optional.of(judiciaryJsonObject.getBoolean("isBenchChairman"))));
+ assertThat(judicialRole.getIsDeputy(), is(Optional.of(judiciaryJsonObject.getBoolean("isDeputy"))));
assertThat(judicialRole.getJudicialRoleType().getJudiciaryType(), is(judiciaryJsonObject.getString("judiciaryType")));
});
}
@Test
- public void shouldGetEmptyListIfThereIsNoMatchingJudicialRolesInRotaSL() {
+ void shouldGetEmptyListIfThereIsNoMatchingJudicialRolesInRotaSL() {
final String startDate = LocalDate.now().toString();
final String ouCode = "B01LY00";
final Optional courtSessionOptional = Optional.of("AM");
@@ -101,7 +102,7 @@ public void shouldGetEmptyListIfThereIsNoMatchingJudicialRolesInRotaSL() {
}
@Test
- public void shouldGetHearingSlotResponse() {
+ void shouldGetHearingSlotResponse() {
final String startDate = LocalDate.now().toString();
final String ouCode = "B01LY00";
final String courtRoomId = "a91a93e6-d704-3cf1-9f20-e267b5a7eeeb";
@@ -112,9 +113,9 @@ public void shouldGetHearingSlotResponse() {
when(response.getEntity()).thenReturn(hearingSlotsResponse);
when(hearingSlotsService.search(anyMap())).thenReturn(response);
- final Response response = courtSchedulerServiceAdapter.getHearingSlotResponse(startDate, startDate, ouCode, courtRoomId);
+ final Response slotResponse = courtSchedulerServiceAdapter.getHearingSlotResponse(startDate, startDate, ouCode, courtRoomId);
- final JsonObject responseJson = objectToJsonObjectConverter.convert(response.getEntity());
+ final JsonObject responseJson = objectToJsonObjectConverter.convert(slotResponse.getEntity());
final JsonObject object = responseJson.getJsonArray("hearingSlots").getValuesAs(JsonObject.class).get(0);
assertThat(object.getString("panel"), is("YOUTH"));
@@ -122,7 +123,7 @@ public void shouldGetHearingSlotResponse() {
}
@Test
- public void shouldGetPanelInfoIfNotPresentInPayload() {
+ void shouldGetPanelInfoIfNotPresentInPayload() {
final Optional panelInfoFromPayload = empty();
final LocalDate startDate = LocalDate.of(2021, 6, 21);
@@ -144,7 +145,7 @@ public void shouldGetPanelInfoIfNotPresentInPayload() {
}
@Test
- public void shouldGetPanelInfoIfPresentInPayload() {
+ void shouldGetPanelInfoIfPresentInPayload() {
final Optional panelInfoFromPayload = of("ADULT");
final LocalDate startDate = LocalDate.of(2021, 6, 21);
@@ -160,7 +161,7 @@ public void shouldGetPanelInfoIfPresentInPayload() {
}
@Test
- public void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingErrorFromRotaApi() {
+ void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingErrorFromRotaApi() {
final Optional panelInfoFromPayload = empty();
final LocalDate startDate = LocalDate.of(2021, 6, 21);
@@ -178,7 +179,7 @@ public void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingErrorFromRo
}
@Test
- public void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingEmptyPayloadFromRotaApi() {
+ void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingEmptyPayloadFromRotaApi() {
final Optional panelInfoFromPayload = empty();
final LocalDate startDate = LocalDate.of(2021, 6, 21);
@@ -199,7 +200,7 @@ public void shouldReturnEmptyPanelInfoIfNotPresentInPayloadAndGettingEmptyPayloa
}
@Test
- public void shouldGetHearingIds() {
+ void shouldGetHearingIds() {
final String courtCentreId = UUID.randomUUID().toString();
final Optional courtSessionOptional = Optional.of("AD");
final String courtRoomId = UUID.randomUUID().toString();
@@ -221,4 +222,43 @@ public void shouldGetHearingIds() {
assertThat(finalResp.getPageCount(), is(1L));
assertThat(finalResp.getResults(), is(4L));
}
+
+ @Test
+ void shouldValidateSessionAvailability() {
+ final JsonObject validateResponse = givenPayload("/mock-data/azure.rotasl.getHearingSlots.stub-data.json");
+ final JsonObject params = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+
+ when(hearingSlotsService.validateSessionAvailability(any(JsonObject.class))).thenReturn(response);
+ when(response.getStatus()).thenReturn(HttpStatus.SC_OK);
+ when(response.getEntity()).thenReturn(validateResponse);
+
+ final Response result = courtSchedulerServiceAdapter.validateSessionAvailability(params);
+
+ assertThat(result.getStatus(), is(HttpStatus.SC_OK));
+ assertThat(result.getEntity(), is(validateResponse));
+ }
+
+ @Test
+ void shouldReturnErrorResponseWhenValidateSessionAvailabilityFails() {
+ final JsonObject params = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+
+ when(hearingSlotsService.validateSessionAvailability(any(JsonObject.class))).thenReturn(response);
+ when(response.getStatus()).thenReturn(HttpStatus.SC_BAD_REQUEST);
+ when(response.hasEntity()).thenReturn(true);
+ when(response.getEntity()).thenReturn("Validation failed");
+
+ final Response result = courtSchedulerServiceAdapter.validateSessionAvailability(params);
+
+ assertThat(result.getStatus(), is(HttpStatus.SC_BAD_REQUEST));
+ }
}
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/HearingSlotsServiceTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/HearingSlotsServiceTest.java
index b38cebb37..1b45c285c 100644
--- a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/HearingSlotsServiceTest.java
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/service/HearingSlotsServiceTest.java
@@ -23,6 +23,7 @@
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
@@ -65,6 +66,8 @@ class HearingSlotsServiceTest {
private ArgumentCaptor httpPutCaptor;
@Captor
private ArgumentCaptor httpDeleteCaptor;
+ @Captor
+ private ArgumentCaptor httpPostCaptor;
@InjectMocks
private HearingSlotsService hearingSlotsService;
@@ -75,7 +78,7 @@ void setUp() {
}
@Test
- public void shouldSearchSuccessfully() throws Exception {
+ void shouldSearchSuccessfully() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -102,7 +105,7 @@ public void shouldSearchSuccessfully() throws Exception {
}
@Test
- public void shouldDeleteSuccessfully() throws Exception {
+ void shouldDeleteSuccessfully() throws Exception {
// Given
when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
@@ -124,7 +127,7 @@ public void shouldDeleteSuccessfully() throws Exception {
}
@Test
- public void shouldGetCourtSchedulerHearingIdsSuccessfully() throws Exception {
+ void shouldGetCourtSchedulerHearingIdsSuccessfully() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -151,7 +154,7 @@ public void shouldGetCourtSchedulerHearingIdsSuccessfully() throws Exception {
}
@Test
- public void shouldThrowExceptionWhenSearchParamsAreNull() {
+ void shouldThrowExceptionWhenSearchParamsAreNull() {
// Given
Map params = null;
@@ -164,7 +167,7 @@ public void shouldThrowExceptionWhenSearchParamsAreNull() {
}
@Test
- public void shouldHandleHttpErrorResponse() throws Exception {
+ void shouldHandleHttpErrorResponse() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -190,7 +193,7 @@ public void shouldHandleHttpErrorResponse() throws Exception {
}
@Test
- public void shouldHandleIOException() throws Exception {
+ void shouldHandleIOException() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -210,7 +213,7 @@ public void shouldHandleIOException() throws Exception {
}
@Test
- public void shouldGetCourtSchedulesByIdSuccessfully() throws Exception {
+ void shouldGetCourtSchedulesByIdSuccessfully() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -237,7 +240,7 @@ public void shouldGetCourtSchedulesByIdSuccessfully() throws Exception {
}
@Test
- public void shouldThrowExceptionWhenGetCourtSchedulesByIdParamsAreNull() {
+ void shouldThrowExceptionWhenGetCourtSchedulesByIdParamsAreNull() {
// Given
Map params = null;
@@ -245,12 +248,12 @@ public void shouldThrowExceptionWhenGetCourtSchedulesByIdParamsAreNull() {
try {
hearingSlotsService.getCourtSchedulesById(params);
} catch (DataValidationException e) {
- assertThat(e.getMessage(), is("Params for search application/vnd.courtscheduler.search.courtschedules.by.id+json is null ...."));
+ assertThat(e.getMessage(), is("Params for search application/vnd.courtscheduler.search.court-schedules-by-id+json is null ...."));
}
}
@Test
- public void shouldHandleGetCourtSchedulesByIdError() throws Exception {
+ void shouldHandleGetCourtSchedulesByIdError() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -273,7 +276,7 @@ public void shouldHandleGetCourtSchedulesByIdError() throws Exception {
}
@Test
- public void shouldHandleDeleteError() throws Exception {
+ void shouldHandleDeleteError() throws Exception {
// Given
when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
@@ -295,7 +298,7 @@ public void shouldHandleDeleteError() throws Exception {
}
@Test
- public void shouldHandleDeleteIOException() throws Exception {
+ void shouldHandleDeleteIOException() throws Exception {
// Given
when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
@@ -315,7 +318,7 @@ public void shouldHandleDeleteIOException() throws Exception {
}
@Test
- public void shouldHandleResponseEntityConversionError() throws Exception {
+ void shouldHandleResponseEntityConversionError() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -343,7 +346,7 @@ public void shouldHandleResponseEntityConversionError() throws Exception {
}
@Test
- public void shouldHandleMultipleQueryParameters() throws Exception {
+ void shouldHandleMultipleQueryParameters() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key1", "value1");
@@ -371,7 +374,7 @@ public void shouldHandleMultipleQueryParameters() throws Exception {
}
@Test
- public void shouldHandleSystemUserProviderError() {
+ void shouldHandleSystemUserProviderError() {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -387,7 +390,7 @@ public void shouldHandleSystemUserProviderError() {
@Test
- public void shouldSearchAndBookSlotsSuccessfully() throws Exception {
+ void shouldSearchAndBookSlotsSuccessfully() throws Exception {
// Given
Map params = new HashMap<>();
params.put("key", "value");
@@ -414,7 +417,7 @@ public void shouldSearchAndBookSlotsSuccessfully() throws Exception {
}
@Test
- public void shouldThrowExceptionWhenSearchAndBookParamsAreNull() {
+ void shouldThrowExceptionWhenSearchAndBookParamsAreNull() {
// Given
Map params = null;
@@ -425,4 +428,256 @@ public void shouldThrowExceptionWhenSearchAndBookParamsAreNull() {
assertThat(e.getMessage(), is("Params for search application/vnd.courtscheduler.search.book.hearing.slots+json is null ...."));
}
}
+
+ // ─── validateSessionAvailability tests ──────────────────────────────
+
+ @Test
+ void shouldValidateSessionAvailabilitySuccessfully() throws Exception {
+ // Given
+ javax.json.JsonObject params = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.OK.getStatusCode());
+ when(httpResponse.getEntity()).thenReturn(mock(org.apache.http.HttpEntity.class));
+
+ // When
+ Response response = hearingSlotsService.validateSessionAvailability(params);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ verify(httpClient).execute(httpPostCaptor.capture());
+ HttpPost capturedPost = httpPostCaptor.getValue();
+ assertThat(capturedPost.getURI().toString(), is(BASE_URI + "/validate-session-availability"));
+ }
+ }
+
+ @Test
+ void shouldThrowExceptionWhenValidateSessionAvailabilityParamsAreNull() {
+ // Given
+ javax.json.JsonObject params = null;
+
+ // When/Then
+ try {
+ hearingSlotsService.validateSessionAvailability(params);
+ } catch (DataValidationException e) {
+ assertThat(e.getMessage(), is("Payload for application/vnd.courtscheduler.validate.session.availability+json is null or empty ...."));
+ }
+ }
+
+ @Test
+ void shouldThrowExceptionWhenValidateSessionAvailabilityPayloadIsEmpty() {
+ // Given
+ javax.json.JsonObject emptyPayload = javax.json.Json.createObjectBuilder().build();
+
+ // When/Then
+ try {
+ hearingSlotsService.validateSessionAvailability(emptyPayload);
+ } catch (DataValidationException e) {
+ assertThat(e.getMessage(), is("Payload for application/vnd.courtscheduler.validate.session.availability+json is null or empty ...."));
+ }
+ }
+
+ @Test
+ void shouldHandlePostErrorResponse() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
+ when(httpResponse.getEntity()).thenReturn(mock(org.apache.http.HttpEntity.class));
+
+ // When
+ Response response = hearingSlotsService.validateSessionAvailability(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
+ }
+ }
+
+ @Test
+ void shouldHandleIOExceptionWhenValidatingSessionAvailability() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPost.class))).thenThrow(new IOException("Connection refused"));
+
+ // When
+ Response response = hearingSlotsService.validateSessionAvailability(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ }
+ }
+
+ @Test
+ void shouldHandleNullEntityInPostResponse() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.OK.getStatusCode());
+ when(httpResponse.getEntity()).thenReturn(null);
+
+ // When
+ Response response = hearingSlotsService.validateSessionAvailability(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ }
+ }
+
+ @Test
+ void shouldConvertNonBlankPostResponseBody() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("courtScheduleIdList", javax.json.Json.createArrayBuilder()
+ .add(javax.json.Json.createObjectBuilder()
+ .add("courtScheduleId", "f8254db1-1683-483e-afb3-b87fde5a0a26")))
+ .add("duration", 30)
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class);
+ MockedStatic entityUtilsMockedStatic = Mockito.mockStatic(EntityUtils.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.OK.getStatusCode());
+ org.apache.http.HttpEntity entity = mock(org.apache.http.HttpEntity.class);
+ when(httpResponse.getEntity()).thenReturn(entity);
+ entityUtilsMockedStatic.when(() -> EntityUtils.toString(entity)).thenReturn("{\"available\":true}");
+ when(stringToJsonObjectConverter.convert("{\"available\":true}")).thenReturn(mock(javax.json.JsonObject.class));
+
+ // When
+ Response response = hearingSlotsService.validateSessionAvailability(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ verify(stringToJsonObjectConverter).convert("{\"available\":true}");
+ }
+ }
+
+ // ─── listHearingInCourtSessions tests ────────────────────────────────
+
+ @Test
+ void shouldListHearingInCourtSessionsSuccessfully() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("hearingSlots", javax.json.Json.createArrayBuilder().build())
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class);
+ MockedStatic entityUtilsMockedStatic = Mockito.mockStatic(EntityUtils.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPut.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.OK.getStatusCode());
+ org.apache.http.HttpEntity entity = mock(org.apache.http.HttpEntity.class);
+ when(httpResponse.getEntity()).thenReturn(entity);
+ entityUtilsMockedStatic.when(() -> EntityUtils.toString(entity)).thenReturn("{\"result\":\"success\"}");
+ when(stringToJsonObjectConverter.convert("{\"result\":\"success\"}")).thenReturn(mock(javax.json.JsonObject.class));
+
+ // When
+ Response response = hearingSlotsService.listHearingInCourtSessions(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
+ verify(httpClient).execute(httpPutCaptor.capture());
+ HttpPut capturedPut = httpPutCaptor.getValue();
+ assertThat(capturedPut.getURI().toString(), is(BASE_URI + "/list/hearingslots"));
+ // Verify the body is produced by JsonObject.toString(), not objectMapper
+ byte[] requestBody = capturedPut.getEntity().getContent().readAllBytes();
+ assertThat(new String(requestBody, java.nio.charset.StandardCharsets.UTF_8), is(payload.toString()));
+ }
+ }
+
+ @Test
+ void shouldHandleListHearingInCourtSessionsErrorResponse() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("hearingSlots", javax.json.Json.createArrayBuilder().build())
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class);
+ MockedStatic entityUtilsMockedStatic = Mockito.mockStatic(EntityUtils.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPut.class))).thenReturn(httpResponse);
+ when(httpResponse.getStatusLine()).thenReturn(statusLine);
+ when(statusLine.getStatusCode()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
+ org.apache.http.HttpEntity entity = mock(org.apache.http.HttpEntity.class);
+ when(httpResponse.getEntity()).thenReturn(entity);
+ entityUtilsMockedStatic.when(() -> EntityUtils.toString(entity)).thenReturn("error message");
+
+ // When
+ Response response = hearingSlotsService.listHearingInCourtSessions(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
+ }
+ }
+
+ @Test
+ void shouldHandleListHearingInCourtSessionsIOException() throws Exception {
+ // Given
+ javax.json.JsonObject payload = javax.json.Json.createObjectBuilder()
+ .add("hearingSlots", javax.json.Json.createArrayBuilder().build())
+ .build();
+ when(systemUserProvider.getContextSystemUserId()).thenReturn(java.util.Optional.of(TEST_USER_ID));
+
+ try (MockedStatic mockedStatic = Mockito.mockStatic(HttpClientBuilder.class)) {
+ mockedStatic.when(HttpClientBuilder::create).thenReturn(httpClientBuilder);
+ when(httpClientBuilder.build()).thenReturn(httpClient);
+ when(httpClient.execute(any(HttpPut.class))).thenThrow(new IOException("Connection refused"));
+
+ // When
+ Response response = hearingSlotsService.listHearingInCourtSessions(payload);
+
+ // Then
+ assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ }
+ }
}
\ No newline at end of file
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/CommonXhibitReferenceDataServiceTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/CommonXhibitReferenceDataServiceTest.java
index 694e1538f..c5faaf5e3 100644
--- a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/CommonXhibitReferenceDataServiceTest.java
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/CommonXhibitReferenceDataServiceTest.java
@@ -111,7 +111,7 @@ public void shouldGetCrownCourtDetails() {
}
@Test
- public void shouldGetCriminalCourtDetailsForMagistratesCommittingCourt() {
+ public void shouldGetMagsCourtDetails() {
final UUID courtCentreId = randomUUID();
final String ouCode = "OUCODE";
@@ -134,9 +134,9 @@ public void shouldGetCriminalCourtDetailsForMagistratesCommittingCourt() {
.withCourtType(courtType)
.build();
- when(referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId)).thenReturn(Optional.of(Arrays.asList(courtMapping)));
+ when(referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId)).thenReturn(Optional.of(Arrays.asList(courtMapping)));
- final CourtLocation courtDetails = commonXhibitReferenceDataService.getCriminalCourtDetails(courtCentreId);
+ final CourtLocation courtDetails = commonXhibitReferenceDataService.getMagsCourtDetails(courtCentreId);
assertEquals(courtDetails.getOuCode(), ouCode);
assertEquals(courtDetails.getCrestCourtId(), courtId);
@@ -147,40 +147,6 @@ public void shouldGetCriminalCourtDetailsForMagistratesCommittingCourt() {
assertEquals(courtDetails.getCourtType(), courtType);
}
- @Test
- public void shouldGetCriminalCourtDetailsByCourtHouseTypeWhenCrownAndMagsMappingsPresent() {
-
- final UUID courtCentreId = randomUUID();
-
- final CourtMapping crownMapping = new CourtMapping.Builder()
- .withOucode("OUCROWN")
- .withCrestCourtId("100")
- .withCrestCourtSiteId("101")
- .withCrestCourtName("CROWN")
- .withCrestCourtSiteName("CROWN")
- .withCrestCourtShortName("CR")
- .withCrestCourtSiteCode("C")
- .withCourtType("CROWN_COURT")
- .build();
-
- final CourtMapping magsMapping = new CourtMapping.Builder()
- .withOucode("OUMAGS")
- .withCrestCourtId("200")
- .withCrestCourtSiteId("201")
- .withCrestCourtName("MAGS")
- .withCrestCourtSiteName("MAGS")
- .withCrestCourtShortName("MG")
- .withCrestCourtSiteCode("M")
- .withCourtType("MAGISTRATES_COURT")
- .build();
-
- when(referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId))
- .thenReturn(Optional.of(Arrays.asList(crownMapping, magsMapping)));
-
- assertEquals("C", commonXhibitReferenceDataService.getCriminalCourtDetails(courtCentreId, "CROWN_COURT").getCourtSiteCode());
- assertEquals("M", commonXhibitReferenceDataService.getCriminalCourtDetails(courtCentreId, "MAGISTRATES_COURT").getCourtSiteCode());
- }
-
@Test
public void shouldGetJudiciary() {
final String titleSuffix = "judge";
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCacheTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCacheTest.java
index d2d0848e5..eade46b7c 100644
--- a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCacheTest.java
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataCacheTest.java
@@ -1,10 +1,8 @@
package uk.gov.moj.cpp.listing.common.xhibit;
import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
import static java.util.UUID.fromString;
import static java.util.UUID.randomUUID;
-import static org.mockito.Mockito.*;
import static uk.gov.justice.services.messaging.JsonObjects.createArrayBuilder;
import static uk.gov.justice.services.messaging.JsonObjects.createObjectBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -13,7 +11,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
import static uk.gov.justice.services.test.utils.core.reflection.ReflectionUtil.getValueOfField;
import static uk.gov.moj.cpp.listing.common.utils.FileUtil.givenPayload;
@@ -44,7 +42,6 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
@@ -226,35 +223,6 @@ public void shouldPopulateCrownCourtMappingsMapCache() {
assertThat(actualCourtMappingList.get().get(0).getOucode(), is(expectedCourtMappingList.get(0).getOucode()));
}
- @Test
- public void shouldLazyLoadCrownCourtMappingsWhenNotInStartupCache() {
- final UUID manchesterCourtCentreId = fromString("e3e762ed-8271-3454-b59b-8a13f7cc8870");
- final String manchesterOuCode = "C06MC00";
- final CourtMapping manchesterCourtMapping = getManchesterCourtMapping();
-
- organisationUnitList = Optional.of(new OrganisationUnitList(asList(
- new OrganisationUnit.Builder()
- .withId(manchesterCourtCentreId)
- .withOucode(manchesterOuCode)
- .build())));
-
- hearingTypesListTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- when(referenceDataLoader.getXhibitCrownCourtMappings(manchesterCourtCentreId))
- .thenReturn(Optional.of(new CourtMappingsList(asList(manchesterCourtMapping))));
-
- referenceDataCache.initReferenceData();
-
- final Optional> actualCourtMappingList =
- referenceDataCache.getCrownCourtMappingsMapCache(manchesterCourtCentreId);
-
- assertThat(actualCourtMappingList.isPresent(), is(true));
- assertThat(actualCourtMappingList.get().get(0).getOucode(), is(manchesterOuCode));
- assertThat(actualCourtMappingList.get().get(0).getCrestCourtId(), is("435"));
- }
-
@Test
public void shouldPopulateMagsCourtMappingsMapCache() {
@@ -277,401 +245,6 @@ public void shouldPopulateMagsCourtMappingsMapCache() {
assertThat(actualCourtMappingList.get().get(0).getOucode(), is(expectedCourtMappingList.get(0).getOucode()));
}
- @Test
- public void shouldPopulateCpXhibitCourtMappingsMapCacheFromMagsQueryWhenMagsSucceeds() {
-
- initializeTestData();
-
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(magsCourtMappingsList);
-
- referenceDataCache.initReferenceData();
-
- final CourtMapping magsMapping = getCourtMapping("MAGISTRATES_COURT");
-
- final Optional> actualCourtMappingList = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(actualCourtMappingList.isPresent(), is(true));
- assertThat(actualCourtMappingList.get().size(), is(1));
- assertThat(actualCourtMappingList.get().get(0).getCourtType(), is(magsMapping.getCourtType()));
- assertThat(actualCourtMappingList.get().get(0).getOucode(), is(magsMapping.getOucode()));
- }
-
- @Test
- public void shouldFallbackToCrownCourtMappingsWhenMagsReturnsEmpty() {
-
- initializeTestData();
-
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.empty());
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId))).thenReturn(crownCourtMappingsList);
-
- referenceDataCache.initReferenceData();
-
- final CourtMapping crownMapping = getCourtMapping("CROWN_COURT");
-
- final Optional> actualCourtMappingList = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(actualCourtMappingList.isPresent(), is(true));
- assertThat(actualCourtMappingList.get().size(), is(1));
- assertThat(actualCourtMappingList.get().get(0).getCourtType(), is(crownMapping.getCourtType()));
- }
-
- @Test
- public void shouldReturnEmptyForGetCrownCourtMappingsWhenCourtCentreIdUnknown() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getCrownCourtMappingsMapCache(randomUUID()).isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyForGetCrownCourtMappingsWhenOucodeNotInCrownCache() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getCrownCourtMappingsMapCache(courtCentreId).isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyForGetMagsCourtMappingsWhenCourtCentreIdUnknown() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getMagsCourtMappingsMapCache(randomUUID()).isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyForGetMagsCourtMappingsWhenLoaderReturnsEmptyOptional() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.empty());
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId).isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyForGetMagsCourtMappingsWhenCpMappingListIsNull() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(new CourtMappingsList(null)));
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId).isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnPresentWithEmptyListForGetMagsWhenMagsReturnsEmptyCpList() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- referenceDataCache.initReferenceData();
-
- final Optional> actual = referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId);
- assertThat(actual.isPresent(), is(true));
- assertThat(actual.get().isEmpty(), is(true));
- }
-
- @Test
- public void shouldHitMagsLoaderOnlyOncePerOucodeWhenGetMagsCalledTwice() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(magsCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId);
- referenceDataCache.getMagsCourtMappingsMapCache(courtCentreId);
-
- verify(referenceDataLoader, times(1)).getXhibitMagsCourtMappings(eq(ouCode));
- }
-
- @Test
- public void shouldReturnEmptyForCpXhibitCourtMappingsWhenCourtCentreIdUnknown() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- referenceDataCache.initReferenceData();
-
- assertThat(referenceDataCache.getCpXhibitCourtMappingsMapCache(randomUUID()).isPresent(), is(false));
- }
-
- @Test
- public void shouldFallbackCpXhibitToCrownWhenMagsReturnsEmptyCpMappingList() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId))).thenReturn(crownCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- final CourtMapping crownMapping = getCourtMapping("CROWN_COURT");
- final Optional> actual = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(actual.isPresent(), is(true));
- assertThat(actual.get().size(), is(1));
- assertThat(actual.get().get(0).getCourtType(), is(crownMapping.getCourtType()));
- verify(referenceDataLoader, times(1)).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
- @Test
- public void shouldReturnPresentEmptyListForCpXhibitWhenMagsAndCrownBothYieldNoMappings() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId))).thenReturn(Optional.of(new CourtMappingsList(emptyList())));
- referenceDataCache.initReferenceData();
-
- final Optional> actual = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(actual.isPresent(), is(true));
- assertThat(actual.get().isEmpty(), is(true));
- }
-
- @Test
- public void shouldLazyCacheCpXhibitPerCourtCentreId() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(magsCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- verify(referenceDataLoader, times(1)).getXhibitMagsCourtMappings(eq(ouCode));
- verify(referenceDataLoader, never()).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
-
-
- /**
- * When the mags endpoint returns a non-empty list, every CourtMapping field
- * from the source must be carried over to the rebuilt mapping AND the
- * courtType must be forced to "MAGISTRATES_COURT" regardless of whatever
- * value the source had.
- */
- @Test
- public void shouldCopyAllFieldsFromMagsMappingAndOverrideCourtTypeToMagistratesCourt() {
- final UUID mappingId = randomUUID();
- final String oucode = "C01BL00";
- final String courtIdVal = "432";
- final String courtSiteId = "433";
- final String courtName = "BLACKFRIARS CROWN";
- final String courtShortName = "BLF";
- final String courtSiteName = "BLACKFRIARS SITE";
- final String courtSiteCode = "B";
-
- final CourtMapping sourceMapping = new CourtMapping.Builder()
- .withId(mappingId)
- .withOucode(oucode)
- .withCrestCourtId(courtIdVal)
- .withCrestCourtSiteId(courtSiteId)
- .withCrestCourtName(courtName)
- .withCrestCourtShortName(courtShortName)
- .withCrestCourtSiteName(courtSiteName)
- .withCrestCourtSiteCode(courtSiteCode)
- .withCourtType("CROWN_COURT") // original type – must be overridden
- .build();
-
- final CourtMappingsList magsList = new CourtMappingsList(asList(sourceMapping));
-
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(magsList));
- referenceDataCache.initReferenceData();
-
- final Optional> result = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(result.isPresent(), is(true));
- assertThat(result.get(), hasSize(1));
-
- final CourtMapping rebuilt = result.get().get(0);
- assertThat(rebuilt.getId(), is(mappingId));
- assertThat(rebuilt.getOucode(), is(oucode));
- assertThat(rebuilt.getCrestCourtId(), is(courtIdVal));
- assertThat(rebuilt.getCrestCourtSiteId(), is(courtSiteId));
- assertThat(rebuilt.getCrestCourtName(), is(courtName));
- assertThat(rebuilt.getCrestCourtShortName(), is(courtShortName));
- assertThat(rebuilt.getCrestCourtSiteName(), is(courtSiteName));
- assertThat(rebuilt.getCrestCourtSiteCode(), is(courtSiteCode));
- // *** The key assertion: courtType must ALWAYS be MAGISTRATES_COURT ***
- assertThat(rebuilt.getCourtType(), is("MAGISTRATES_COURT"));
- }
-
- /**
- * When mags returns multiple mappings, every entry must be rebuilt with
- * MAGISTRATES_COURT courtType and the list size must match.
- */
- @Test
- public void shouldRebuildAllMagsMappingsWithMagistratesCourtType() {
- final CourtMapping mapping1 = new CourtMapping.Builder()
- .withId(randomUUID())
- .withOucode(ouCode)
- .withCrestCourtId("111")
- .withCourtType("CROWN_COURT")
- .build();
- final CourtMapping mapping2 = new CourtMapping.Builder()
- .withId(randomUUID())
- .withOucode(ouCode)
- .withCrestCourtId("222")
- .withCourtType("CROWN_COURT")
- .build();
-
- final CourtMappingsList magsList = new CourtMappingsList(asList(mapping1, mapping2));
-
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.of(magsList));
- referenceDataCache.initReferenceData();
-
- final Optional> result = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(result.isPresent(), is(true));
- assertThat(result.get(), hasSize(2));
- result.get().forEach(m -> assertThat(m.getCourtType(), is("MAGISTRATES_COURT")));
- // Crown endpoint must never have been consulted
- verify(referenceDataLoader, never()).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
- /**
- * When mags returns a CourtMappingsList whose inner list is null
- * the filter step treats it as empty → fallback to crown.
- */
- @Test
- public void shouldFallbackToCrownWhenMagsReturnsNullInnerList() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- // null inner list – getCpXhibitCourtMappings() returns null
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode)))
- .thenReturn(Optional.of(new CourtMappingsList(null)));
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId)))
- .thenReturn(crownCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- final Optional> result = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(result.isPresent(), is(true));
- assertThat(result.get(), hasSize(1));
- assertThat(result.get().get(0).getCourtType(), is("CROWN_COURT"));
- verify(referenceDataLoader, times(1)).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
- /**
- * When mags is absent (Optional.empty()) AND crown returns Optional.empty(),
- * the result must be present with an empty list (not Optional.empty()).
- */
- @Test
- public void shouldReturnPresentEmptyListWhenMagsAbsentAndCrownReturnsEmptyOptional() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.empty());
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId))).thenReturn(Optional.empty());
- referenceDataCache.initReferenceData();
-
- final Optional> result = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(result.isPresent(), is(true));
- assertThat(result.get().isEmpty(), is(true));
- }
-
- /**
- * When mags is absent AND crown returns a CourtMappingsList with a null
- * inner list, the filter drops it and the result must be an empty list.
- */
- @Test
- public void shouldReturnPresentEmptyListWhenMagsAbsentAndCrownReturnsNullInnerList() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(Optional.empty());
- when(referenceDataLoader.getXhibitCrownCourtMappings(eq(courtCentreId)))
- .thenReturn(Optional.of(new CourtMappingsList(null)));
- referenceDataCache.initReferenceData();
-
- final Optional> result = referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- assertThat(result.isPresent(), is(true));
- assertThat(result.get().isEmpty(), is(true));
- }
-
- /**
- * The resolved list is stored in the lazy cache: regardless of how many
- * times getCpXhibitCourtMappingsMapCache is called, the mags loader must
- * only be consulted once per court-centre.
- */
- @Test
- public void shouldCallMagsLoaderOnlyOncePerCourtCentreIdOnRepeatedLookups() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(magsCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- // Call three times
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- verify(referenceDataLoader, times(1)).getXhibitMagsCourtMappings(eq(ouCode));
- verify(referenceDataLoader, never()).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
- /**
- * When mags succeeds (non-empty list) the crown-by-courtCentreId endpoint
- * must never be invoked at all.
- */
- @Test
- public void shouldNeverCallCrownLoaderWhenMagsSucceeds() {
- initializeTestData();
- when(referenceDataLoader.getAllHearingTypesList()).thenReturn(hearingTypesList);
- when(referenceDataLoader.getXhibitCrownCourtMappings()).thenReturn(crownCourtMappingsList);
- when(referenceDataLoader.getOrganisationUnitList()).thenReturn(organisationUnitList);
- when(referenceDataLoader.getXhibitMagsCourtMappings(eq(ouCode))).thenReturn(magsCourtMappingsList);
- referenceDataCache.initReferenceData();
-
- referenceDataCache.getCpXhibitCourtMappingsMapCache(courtCentreId);
-
- verify(referenceDataLoader, never()).getXhibitCrownCourtMappings(eq(courtCentreId));
- }
-
-
@Test
public void shouldPopulateJudiciariesCache() {
final UUID judiciaryId = randomUUID();
@@ -788,19 +361,6 @@ private void courtMappingsListTestData() {
magsCourtMappingsList = Optional.of(new CourtMappingsList(asList(getCourtMapping("MAGISTRATES_COURT"))));
}
- private CourtMapping getManchesterCourtMapping() {
- return new CourtMapping.Builder()
- .withOucode("C06MC00")
- .withCrestCourtId("435")
- .withCrestCourtSiteId("435")
- .withCrestCourtName("MANCHESTER")
- .withCrestCourtSiteName("MANCHESTER")
- .withCrestCourtShortName("MANCH")
- .withCrestCourtSiteCode("A")
- .withCourtType("CROWN_COURT")
- .build();
- }
-
private CourtMapping getCourtMapping(final String courtType) {
final String courtSiteId = "433";
final String crestCourtName = "BLACKFRIARS";
diff --git a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoaderTest.java b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoaderTest.java
index 6dbb4b1b8..09057ba03 100644
--- a/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoaderTest.java
+++ b/listing-common/src/test/java/uk/gov/moj/cpp/listing/common/xhibit/ReferenceDataLoaderTest.java
@@ -4,13 +4,13 @@
import static uk.gov.justice.services.messaging.JsonObjects.createArrayBuilder;
import static uk.gov.justice.services.messaging.JsonObjects.createObjectBuilder;
import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static uk.gov.justice.services.test.utils.core.reflection.ReflectionUtil.setField;
import static uk.gov.moj.cpp.listing.common.utils.FileUtil.givenPayload;
@@ -18,6 +18,7 @@
import uk.gov.justice.services.common.converter.JsonObjectToObjectConverter;
import uk.gov.justice.services.common.converter.jackson.ObjectMapperProducer;
import uk.gov.justice.services.core.requester.Requester;
+import uk.gov.justice.services.messaging.Envelope;
import uk.gov.moj.cpp.listing.common.xhibit.exception.InvalidReferenceDataException;
import uk.gov.moj.cpp.listing.domain.referencedata.CourtMapping;
import uk.gov.moj.cpp.listing.domain.referencedata.CourtMappingsList;
@@ -236,24 +237,6 @@ public void shouldGetXhibitCourtMappingsWithCourtCenter() {
assertThat(courtId, is(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getCrestCourtId()));
}
- @Test
- public void shouldReturnEmptyWhenGetXhibitCrownCourtMappingsNoParamsAndResponseEnvelopeIsNull() {
- when(requester.requestAsAdmin(any(), eq(CourtMappingsList.class))).thenReturn(null);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitCrownCourtMappings();
-
- assertThat(courtMappingsList.isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyWhenGetXhibitCrownCourtMappingsByCourtCentreIdAndResponseEnvelopeIsNull() {
- when(requester.requestAsAdmin(any(), eq(CourtMappingsList.class))).thenReturn(null);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitCrownCourtMappings(UUID.randomUUID());
-
- assertThat(courtMappingsList.isPresent(), is(false));
- }
-
@Test
public void shouldGetXhibitMagsCourtMappings() {
final String ouCode = "OUCODE";
@@ -286,67 +269,6 @@ public void shouldGetXhibitMagsCourtMappings() {
assertThat(courtId, is(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getCrestCourtId()));
}
- @Test
- public void shouldReturnEmptyWhenMagsPayloadIsEmptyRecordFromReferencedata() {
- when(requester.requestAsAdmin(any(), eq(CourtMapping.class)).payload()).thenReturn(new CourtMapping.Builder().build());
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitMagsCourtMappings("OUCODE");
-
- assertThat(courtMappingsList.isPresent(), equalTo(false));
- }
-
- @Test
- public void shouldReturnEmptyWhenGetXhibitMagsCourtMappingsAndResponseEnvelopeIsNull() {
- when(requester.requestAsAdmin(any(), eq(CourtMapping.class))).thenReturn(null);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitMagsCourtMappings("OUCODE");
-
- assertThat(courtMappingsList.isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnEmptyWhenGetXhibitMagsCourtMappingsAndPayloadIsNull() {
- when(requester.requestAsAdmin(any(), eq(CourtMapping.class)).payload()).thenReturn(null);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitMagsCourtMappings("OUCODE");
-
- assertThat(courtMappingsList.isPresent(), is(false));
- }
-
- @Test
- public void shouldReturnMagsMappingsWhenPayloadHasOucodeOnlyAndIdNull() {
- final String ouCode = "ONLY_OU";
- final CourtMapping courtMapping = new CourtMapping.Builder()
- .withOucode(ouCode)
- .withCrestCourtId("432")
- .build();
-
- when(requester.requestAsAdmin(any(), eq(CourtMapping.class)).payload()).thenReturn(courtMapping);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitMagsCourtMappings(ouCode);
-
- assertThat(courtMappingsList.isPresent(), is(true));
- assertThat(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getOucode(), is(ouCode));
- assertThat(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getId(), is(nullValue()));
- }
-
- @Test
- public void shouldReturnMagsMappingsWhenPayloadHasIdOnlyAndOucodeNull() {
- final UUID mappingId = randomUUID();
- final CourtMapping courtMapping = new CourtMapping.Builder()
- .withId(mappingId)
- .withCrestCourtId("432")
- .build();
-
- when(requester.requestAsAdmin(any(), eq(CourtMapping.class)).payload()).thenReturn(courtMapping);
-
- final Optional courtMappingsList = referenceDataLoader.getXhibitMagsCourtMappings("ANY");
-
- assertThat(courtMappingsList.isPresent(), is(true));
- assertThat(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getId(), is(mappingId));
- assertThat(courtMappingsList.get().getCpXhibitCourtMappings().get(0).getOucode(), is(nullValue()));
- }
-
@Test
public void shouldGetCourtRoomMappingsList() {
final UUID courtCentreId = randomUUID();
diff --git a/listing-common/src/test/resources/mock-data/azure.rotasl.getHearingSlots.stub-data.json b/listing-common/src/test/resources/mock-data/azure.rotasl.getHearingSlots.stub-data.json
index 286712f7b..2405666ac 100644
--- a/listing-common/src/test/resources/mock-data/azure.rotasl.getHearingSlots.stub-data.json
+++ b/listing-common/src/test/resources/mock-data/azure.rotasl.getHearingSlots.stub-data.json
@@ -23,28 +23,28 @@
"availableDuration": 0,
"judiciaries": [
{
- "judiciaryId": "0fd0233e-a8f9-3dc8-8bef-4f6b1d4799f3",
+ "id": "0fd0233e-a8f9-3dc8-8bef-4f6b1d4799f3",
"courtScheduleId": "0d9c4454-46db-305d-bb48-dcf423a6d2a5",
"courtListingProfileId": "CS2339681",
"judiciaryType": "MAGISTRATE",
- "deputy": true,
- "benchChairman": false
+ "isDeputy": true,
+ "isBenchChairman": false
},
{
- "judiciaryId": "d424f73e-4a19-396d-a00c-f4c38d1c864e",
+ "id": "d424f73e-4a19-396d-a00c-f4c38d1c864e",
"courtScheduleId": "0d9c4454-46db-305d-bb48-dcf423a6d2a5",
"courtListingProfileId": "CS2339681",
"judiciaryType": "MAGISTRATE",
- "deputy": false,
- "benchChairman": true
+ "isDeputy": false,
+ "isBenchChairman": true
},
{
- "judiciaryId": "f0cd595c-be23-3539-9aed-7f1aab1d1e19",
+ "id": "f0cd595c-be23-3539-9aed-7f1aab1d1e19",
"courtScheduleId": "0d9c4454-46db-305d-bb48-dcf423a6d2a5",
"courtListingProfileId": "CS2339681",
"judiciaryType": "MAGISTRATE",
- "deputy": true,
- "benchChairman": false
+ "isDeputy": true,
+ "isBenchChairman": false
}
],
"slotStartTimes": []
diff --git a/listing-domain/listing-domain-aggregate/pom.xml b/listing-domain/listing-domain-aggregate/pom.xml
index 900fd4872..d0f4e700e 100644
--- a/listing-domain/listing-domain-aggregate/pom.xml
+++ b/listing-domain/listing-domain-aggregate/pom.xml
@@ -3,7 +3,7 @@
listing-domain
uk.gov.moj.cpp.listing
- 17.103.176-SNAPSHOT
+ 17.103.163-JA-SNAPSHOT
4.0.0
diff --git a/listing-domain/listing-domain-aggregate/src/main/java/uk/gov/moj/cpp/listing/domain/aggregate/Case.java b/listing-domain/listing-domain-aggregate/src/main/java/uk/gov/moj/cpp/listing/domain/aggregate/Case.java
index 2c2621450..7e6112d1a 100644
--- a/listing-domain/listing-domain-aggregate/src/main/java/uk/gov/moj/cpp/listing/domain/aggregate/Case.java
+++ b/listing-domain/listing-domain-aggregate/src/main/java/uk/gov/moj/cpp/listing/domain/aggregate/Case.java
@@ -38,20 +38,16 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
-import java.util.Map;
-import java.util.HashMap;
import java.util.UUID;
import java.util.stream.Stream;
@SuppressWarnings({"pmd:BeanMembersShouldSerialize", "squid:S1068"})
public class Case implements Aggregate {
- private static final long serialVersionUID = 204L;
+ private static final long serialVersionUID = 203L;
private final Set hearingIds = new HashSet<>();
- private final Map currentDefendants = new HashMap<>();
-
private final Set defendantsToBeUpdated = new HashSet<>();
public List getHearingIds() {
@@ -63,7 +59,7 @@ public Object apply(final Object event) {
return match(event).with(
when(HearingAddedToCase.class).apply(this::onHearingAddedToCase),
when(HearingUpdatedToCase.class).apply(this::onHearingUpdatedToCase),
- when(DefendantsToBeUpdated.class).apply(this::onDefendantsToBeUpdated),
+ when(DefendantsToBeUpdated.class).apply(e -> onDefendantsToBeUpdated()),
when(DefendantsToBeUpdatedLater.class).apply(this::onDefendantsToBeUpdatedLater),
when(OffencesToBeAdded.class).apply(e -> onOffencesToBeAdded()),
when(OffencesToBeDeleted.class).apply(e -> onOffencesToBeDeleted()),
@@ -96,37 +92,20 @@ public Stream