|
| 1 | +package com.johnlpage.memex.cucumber.steps; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.johnlpage.memex.cucumber.service.VehicleInspectionIdRangeValidator; |
| 6 | +import com.johnlpage.memex.model.VehicleInspection; |
| 7 | +import io.cucumber.datatable.DataTable; |
| 8 | +import io.cucumber.java.en.Given; |
| 9 | +import lombok.extern.slf4j.Slf4j; |
| 10 | +import org.springframework.beans.factory.annotation.Autowired; |
| 11 | +import org.springframework.beans.factory.annotation.Value; |
| 12 | +import org.springframework.core.ParameterizedTypeReference; |
| 13 | +import org.springframework.http.MediaType; |
| 14 | +import org.springframework.http.ResponseEntity; |
| 15 | +import org.springframework.web.client.RestClient; |
| 16 | + |
| 17 | +import java.util.ArrayList; |
| 18 | +import java.util.Collections; |
| 19 | +import java.util.List; |
| 20 | +import java.util.Map; |
| 21 | +import java.util.stream.Collectors; |
| 22 | +import java.util.stream.LongStream; |
| 23 | + |
| 24 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 25 | + |
| 26 | +@Slf4j |
| 27 | +public class InspectionsPreConditionSteps { |
| 28 | + |
| 29 | + @Value("${memex.base-url}") |
| 30 | + private String apiBaseUrl; |
| 31 | + |
| 32 | + private final RestClient restClient; |
| 33 | + private final ObjectMapper objectMapper; |
| 34 | + private final VehicleInspectionIdRangeValidator idRangeValidator; |
| 35 | + |
| 36 | + @Autowired |
| 37 | + public InspectionsPreConditionSteps(RestClient.Builder restClientBuilder, ObjectMapper objectMapper, |
| 38 | + VehicleInspectionIdRangeValidator idRangeValidator) { |
| 39 | + this.restClient = restClientBuilder.baseUrl(apiBaseUrl).build(); |
| 40 | + this.objectMapper = objectMapper; |
| 41 | + this.idRangeValidator = idRangeValidator; |
| 42 | + } |
| 43 | + |
| 44 | + @Given("the following vehicle inspections exist:") |
| 45 | + public void givenVehicleInspectionsExist(DataTable dataTable) throws JsonProcessingException { |
| 46 | + List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class); |
| 47 | + List<VehicleInspection> inspections = new ArrayList<>(); |
| 48 | + |
| 49 | + for (Map<String, String> row : rows) { |
| 50 | + String json = row.get("vehicleinspection"); |
| 51 | + VehicleInspection inspection = objectMapper.readValue(json, VehicleInspection.class); |
| 52 | + inspections.add(inspection); |
| 53 | + Long testId = inspection.getTestid(); |
| 54 | + assertNotNull(testId, "testid is expected to be part of the data input"); |
| 55 | + idRangeValidator.validate(testId); |
| 56 | + } |
| 57 | + |
| 58 | + upsertInspectionsViaApi(inspections); |
| 59 | + } |
| 60 | + |
| 61 | + @Given("the vehicle inspection with id {long} does not exist") |
| 62 | + public void theFollowingVehicleInspectionDoesNotExist(long testId) throws JsonProcessingException { |
| 63 | + idRangeValidator.validate(testId); |
| 64 | + deleteInspectionsViaApi(Collections.singletonList(testId)); |
| 65 | + } |
| 66 | + |
| 67 | + @Given("the vehicle inspections in range {long}-{long} do not exist") |
| 68 | + public void theFollowingVehicleInspectionsInRangeDoesNotExist(long startId, long endId) throws JsonProcessingException { |
| 69 | + idRangeValidator.validateRange(startId, endId); |
| 70 | + List<Long> idsForDeletion = LongStream.rangeClosed(startId, endId) |
| 71 | + .boxed() |
| 72 | + .collect(Collectors.toList()); |
| 73 | + |
| 74 | + deleteInspectionsViaApi(idsForDeletion); |
| 75 | + } |
| 76 | + |
| 77 | + @Given("the following vehicle inspections do not exist:") |
| 78 | + public void givenTheFollowingVehicleInspectionsDoNotExist(DataTable dataTable) throws JsonProcessingException { |
| 79 | + List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class); |
| 80 | + List<Long> idsToDelete = new ArrayList<>(); |
| 81 | + |
| 82 | + for (Map<String, String> row : rows) { |
| 83 | + if (row.size() != 1) { |
| 84 | + throw new IllegalArgumentException("Only one column per row is supported in this step for deletion criteria."); |
| 85 | + } |
| 86 | + Map.Entry<String, String> entry = row.entrySet().iterator().next(); |
| 87 | + String key = entry.getKey(); |
| 88 | + String inputQuery = entry.getValue(); |
| 89 | + |
| 90 | + String rangeCheck = "\"_id\": {\"$gte\": " + idRangeValidator.getRangeStart() + ", \"$lte\": " + idRangeValidator.getRangeEnd() + "}"; |
| 91 | + String mongoQueryJson = String.format("{\"filter\": {%s, %s}}", rangeCheck, inputQuery.substring(inputQuery.indexOf('{') + 1, inputQuery.lastIndexOf('}'))); // Basic example, might need more robust query building |
| 92 | + |
| 93 | + try { |
| 94 | + ResponseEntity<List<VehicleInspection>> responseEntity = restClient.post() |
| 95 | + .uri(apiBaseUrl + "/api/inspections/query") |
| 96 | + .contentType(MediaType.APPLICATION_JSON) |
| 97 | + .body(mongoQueryJson) |
| 98 | + .retrieve() |
| 99 | + .toEntity(new ParameterizedTypeReference<List<VehicleInspection>>() { |
| 100 | + }); |
| 101 | + |
| 102 | + if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { |
| 103 | + List<VehicleInspection> inspections = responseEntity.getBody(); |
| 104 | + inspections.forEach(insp -> idsToDelete.add(insp.getTestid())); |
| 105 | + } else { |
| 106 | + log.warn("Query {} returned status {} or empty body. No IDs added for deletion.", |
| 107 | + mongoQueryJson, responseEntity.getStatusCode()); |
| 108 | + } |
| 109 | + } catch (Exception e) { |
| 110 | + log.error("Error querying API for a query {}", mongoQueryJson, e); |
| 111 | + throw new RuntimeException("Error querying API for a query: " + mongoQueryJson, e); |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + deleteInspectionsViaApi(idsToDelete); |
| 116 | + } |
| 117 | + |
| 118 | + private void deleteInspectionsViaApi(List<Long> idsToDelete) throws JsonProcessingException { |
| 119 | + if (idsToDelete.isEmpty()) { |
| 120 | + log.info("Delete IDs list is empty, skipping API call."); |
| 121 | + return; |
| 122 | + } |
| 123 | + |
| 124 | + List<Map<String, Object>> payload = idsToDelete.stream() |
| 125 | + .map(id -> Map.<String, Object>of("testid", id, "deleted", true)) |
| 126 | + .collect(Collectors.toList()); |
| 127 | + |
| 128 | + String jsonPayload = objectMapper.writeValueAsString(payload); |
| 129 | + |
| 130 | + try { |
| 131 | + log.info("apiBaseUrl: {}", apiBaseUrl); |
| 132 | + ResponseEntity<String> response = restClient.post() |
| 133 | + .uri(apiBaseUrl + "/api/inspections?updateStrategy=UPDATEWITHHISTORY&futz=true") |
| 134 | + .contentType(MediaType.APPLICATION_JSON) |
| 135 | + .body(jsonPayload) |
| 136 | + .retrieve() |
| 137 | + .toEntity(String.class); |
| 138 | + |
| 139 | + if (response.getStatusCode().is2xxSuccessful()) { |
| 140 | + log.info("Successfully marked inspections for deletion. IDs count: {}", idsToDelete.size()); |
| 141 | + } else { |
| 142 | + log.error("Failed to mark inspections for deletion. Status: {}, Body: {}", |
| 143 | + response.getStatusCode(), response.getBody()); |
| 144 | + throw new RuntimeException("Failed to mark inspections for deletion: " + response.getStatusCode()); |
| 145 | + } |
| 146 | + } catch (Exception e) { |
| 147 | + log.error("Error calling API to mark inspections for deletion. IDs count: {}", idsToDelete.size(), e); |
| 148 | + throw new RuntimeException("Error calling API to mark inspections for deletion: " + e.getMessage()); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + private void upsertInspectionsViaApi(List<VehicleInspection> inspections) throws JsonProcessingException { |
| 153 | + if (inspections.isEmpty()) { |
| 154 | + log.info("No inspections to upsert, skipping API call."); |
| 155 | + return; |
| 156 | + } |
| 157 | + |
| 158 | + String jsonPayload = objectMapper.writeValueAsString(inspections); |
| 159 | + |
| 160 | + try { |
| 161 | + ResponseEntity<String> response = restClient.post() |
| 162 | + .uri(apiBaseUrl + "/api/inspections?updateStrategy=UPDATEWITHHISTORY&futz=true") |
| 163 | + .contentType(MediaType.APPLICATION_JSON) |
| 164 | + .body(jsonPayload) |
| 165 | + .retrieve() |
| 166 | + .toEntity(String.class); |
| 167 | + |
| 168 | + if (response.getStatusCode().is2xxSuccessful()) { |
| 169 | + log.info("Successfully upserted {} inspections.", inspections.size()); |
| 170 | + } else { |
| 171 | + log.error("Failed to upsert inspections. Status: {}, Body: {}", |
| 172 | + response.getStatusCode(), response.getBody()); |
| 173 | + throw new RuntimeException("Failed to upsert inspections: " + response.getStatusCode()); |
| 174 | + } |
| 175 | + } catch (Exception e) { |
| 176 | + log.error("Error calling API to upsert inspections. Count: {}", inspections.size(), e); |
| 177 | + throw new RuntimeException("Error calling API to upsert inspections: " + e.getMessage()); |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments