From b0c875e166f5db788f752f57d3ba4150abfef4d6 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 1 Jul 2024 12:30:05 -0700 Subject: [PATCH 01/39] Implemented Water Supply DTO and Tests --- .../cda/data/dto/watersupply/WaterSupply.java | 147 +++++++++++ .../dto/watersupply/WaterUserContractRef.java | 48 ++++ .../data/dto/watersupply/WaterSupplyTest.java | 242 ++++++++++++++++++ .../cda/data/dto/watersupply/watersupply.json | 116 +++++++++ 4 files changed, 553 insertions(+) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java create mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java new file mode 100644 index 000000000..a1f7d9368 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java @@ -0,0 +1,147 @@ +/* + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) +@JsonDeserialize(builder = WaterSupply.Builder.class) +public class WaterSupply implements CwmsDTOBase { + private final String contractName; + private final Integer contractNumber; + private final String waterUser; + private final WaterUser user; + private final WaterUserContract contract; + + private WaterSupply(Builder builder) { + contractName = builder.contractName; + contractNumber = builder.contractNumber; + waterUser = builder.waterUser; + user = builder.user; + contract = builder.contract; + } + + public String getContractName() { + return contractName; + } + + public Integer getContractNumber() { + return contractNumber; + } + + public String getWaterUser() { + return waterUser; + } + + public WaterUser getUser() { + return user; + } + + public WaterUserContract getContract() { + return contract; + } + + public static class Builder { + private String contractName; + private Integer contractNumber; + private String waterUser; + private WaterUser user; + private WaterUserContract contract; + + public Builder withContractName(String contractName) { + this.contractName = contractName; + return this; + } + + public Builder withContractNumber(Integer contractNumber) { + this.contractNumber = contractNumber; + return this; + } + + public Builder withWaterUser(String waterUser) { + this.waterUser = waterUser; + return this; + } + + public Builder withUser(WaterUser user) { + this.user = user; + return this; + } + + public Builder withContract(WaterUserContract contract) { + this.contract = contract; + return this; + } + + public WaterSupply build() { + return new WaterSupply(this); + } + } + + @Override + public void validate() throws FieldException { + if (contractName == null || contractName.isEmpty()) { + throw new FieldException("Contract Name cannot be null or empty"); + } + if (contractNumber == null) { + throw new FieldException("Contract Number cannot be null"); + } + if (waterUser == null || waterUser.isEmpty()) { + throw new FieldException("Water User cannot be null or empty"); + } + if (user == null) { + throw new FieldException("User Type cannot be null"); + } + if (user.getEntityName() == null) { + throw new FieldException("User Type Entity Name cannot be null"); + } + if (user.getWaterRight() == null) { + throw new FieldException("User Type Water Right cannot be null"); + } + if (contract == null) { + throw new FieldException("Contract Type cannot be null"); + } + if (contract.getWaterUserContractRef() == null) { + throw new FieldException("Water User Contract Ref Type cannot be null"); + } + if (contract.getWaterSupplyContract() == null) { + throw new FieldException("Water Supply Contract Type cannot be null"); + } + if (contract.getContractEffectiveDate() == null) { + throw new FieldException("Contract Effective Date cannot be null"); + } + if (contract.getInitialUseAllocation() == null) { + throw new FieldException("Contract Initial Use Allocation cannot be null"); + } + if (contract.getContractedStorage() == null) { + throw new FieldException("Contracted Storage cannot be null"); + } + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java new file mode 100644 index 000000000..b16c02be4 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java @@ -0,0 +1,48 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +public class WaterUserContractRef { + private WaterUser waterUser; + private String contractName; + + private WaterUserContractRef() { + } + + public WaterUserContractRef(WaterUser waterUser, String contractName) { + this.waterUser = waterUser; + this.contractName = contractName; + } + + public String getContractName() { + return this.contractName; + } + + public WaterUser getWaterUser() { + return this.waterUser; + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java new file mode 100644 index 000000000..af85fb9da --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java @@ -0,0 +1,242 @@ +/* + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import cwms.cda.api.enums.Nation; +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.CwmsIdTest; +import cwms.cda.formatters.Formats; +import cwms.cda.data.dto.LookupType; +import cwms.cda.data.dto.Location; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.ZoneId; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +class WaterSupplyTest { + + private static final String OFFICE_ID = "SPK"; + + @Test + void testWaterSupplySerializationRoundTrip() { + WaterSupply waterSupply = buildTestWaterSupply(); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), waterSupply); + WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); + assertSame(waterSupply, deserialized); + } + + @Test + void testWaterSupplySerializationRoundTripFromFile() throws Exception + { + WaterSupply waterSupply = buildTestWaterSupply(); + InputStream resource = this.getClass().getResourceAsStream("/cwms/cda/data/dto/watersupply/watersupply.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); + assertSame(waterSupply, deserialized); + } + + @Test + void testValidate() + { + assertAll(() -> { + WaterSupply waterSupply = buildTestWaterSupply(); + assertDoesNotThrow(waterSupply::validate); + }, () -> { + WaterSupply waterSupply = new WaterSupply.Builder() + .withContractName("Test Contract") + .build(); + assertThrows(FieldException.class, waterSupply::validate, + "Expected validate() to throw FieldException for missing fields, but it didn't"); + } + ); + } + + private WaterSupply buildTestWaterSupply () + { + return new WaterSupply.Builder() + .withContractName("Test Contract") + .withContractNumber(1234) + .withWaterUser("Test User") + .withUser(new WaterUser("Test Entity", + new CwmsId.Builder() + .withName("Base Location") + .withOfficeId(OFFICE_ID) + .build(), + "Water Right test")) + .withContract(new WaterUserContract.Builder() + .withWaterUserContractRef(new WaterUserContractRef(new WaterUser("Entity Test", + new CwmsId.Builder() + .withName("Base Location") + .withOfficeId(OFFICE_ID) + .build(), + "Water Right Test"), + "Contract Name Test")) + .withWaterSupplyContract(new LookupType.Builder() + .withActive(true) + .withDisplayValue("Display Value Test") + .withOfficeId(OFFICE_ID) + .withTooltip("Example Tooltip") + .build()) + .withContractEffectiveDate(new Date(1719854376)) + .withContractExpirationDate(new Date(1719854376)) + .withContractedStorage(1000.0) + .withInitialUseAllocation(20.5) + .withFutureUseAllocation(79.5) + .withStorageUnitsId("Test Storage Unit") + .withFutureUsePercentActivated(25.5) + .withTotalAllocPercentActivated(15.2) + .withPumpOutLocation(buildLocationType("Pump Out Location")) + .withPumpOutBelowLocation(buildLocationType("Pump Out Below Location")) + .withPumpInLocation(buildLocationType("Pump In Location")) + .build()) + .build(); + } + + private Location buildLocationType(String pumpLocation) + { + return new Location.Builder(OFFICE_ID, pumpLocation) + .withStateInitial("CA") + .withBoundingOfficeId(OFFICE_ID) + .withDescription("Place for testing") + .withElevation(120.0) + .withCountyName("Sacramento") + .withHorizontalDatum("WGS84") + .withLatitude(0.0) + .withLongitude(0.0) + .withLongName("Full Location Name") + .withMapLabel("Map location") + .withNearestCity("Davis") + .withPublishedLatitude(0.0) + .withPublishedLongitude(0.0) + .withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("WGS84") + .withPublicName(pumpLocation) + .withLocationType("PUMP") + .withActive(true) + .withNation(Nation.US) + .withBoundingOfficeId(OFFICE_ID) + .withElevationUnits("m") + .withLocationKind("PUMP") + .build(); + } + + + private static void assertSame(WaterSupply first, WaterSupply second) + { + assertAll( + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertEquals(first.getContractNumber(), second.getContractNumber()), + () -> assertEquals(first.getWaterUser(), second.getWaterUser()), + () -> assertWaterUserType(first.getUser(), second.getUser()), + () -> assertWaterUserContractType(first.getContract(), second.getContract()) + ); + } + + private static void assertLocationType(Location first, Location second) + { + assertAll( + () -> assertEquals(first.getNearestCity(), second.getNearestCity()), + () -> assertEquals(first.getNation(), second.getNation()), + () -> assertEquals(first.getBoundingOfficeId(), second.getBoundingOfficeId()), + () -> assertEquals(first.getPublishedLongitude(), second.getPublishedLongitude()), + () -> assertEquals(first.getPublishedLatitude(), second.getPublishedLatitude()), + () -> assertEquals(first.getMapLabel(), second.getMapLabel()), + () -> assertEquals(first.getLocationKind(), second.getLocationKind()), + () -> assertEquals(first.getActive(), second.getActive()), + () -> assertEquals(first.getDescription(), second.getDescription()), + () -> assertEquals(first.getLongName(), second.getLongName()), + () -> assertEquals(first.getPublicName(), second.getPublicName()), + () -> assertEquals(first.getVerticalDatum(), second.getVerticalDatum()), + () -> assertEquals(first.getElevationUnits(), second.getElevationUnits()), + () -> assertEquals(first.getElevation(), second.getElevation()), + () -> assertEquals(first.getHorizontalDatum(), second.getHorizontalDatum()), + () -> assertEquals(first.getLongitude(), second.getLongitude()), + () -> assertEquals(first.getLatitude(), second.getLatitude()), + () -> assertEquals(first.getLocationType(), second.getLocationType()), + () -> assertEquals(first.getTimezoneName(), second.getTimezoneName()), + () -> assertEquals(first.getCountyName(), second.getCountyName()), + () -> assertEquals(first.getStateInitial(), second.getStateInitial()), + () -> assertEquals(first.getName(), second.getName()) + ); + } + + private static void assertLookupType(LookupType first, LookupType second) + { + assertAll( + () -> assertEquals(first.getOfficeId(), second.getOfficeId()), + () -> assertEquals(first.getActive(), second.getActive()), + () -> assertEquals(first.getDisplayValue(), second.getDisplayValue()), + () -> assertEquals(first.getTooltip(), second.getTooltip()) + ); + } + + private static void assertWaterUserType(WaterUser first, WaterUser second) + { + assertAll( + () -> assertEquals(first.getEntityName(), second.getEntityName()), + () -> CwmsIdTest.assertSame(first.getParentLocationRef(), second.getParentLocationRef()), + () -> assertEquals(first.getWaterRight(), second.getWaterRight()) + ); + } + + private static void assertWaterUserContractType(WaterUserContract first, WaterUserContract second) + { + assertAll( + () -> assertWaterUserContractRefType(first.getWaterUserContractRef(), second.getWaterUserContractRef()), + () -> assertLookupType(first.getWaterSupplyContract(), second.getWaterSupplyContract()), + () -> assertEquals(first.getContractEffectiveDate(), second.getContractEffectiveDate()), + () -> assertEquals(first.getContractExpirationDate(), second.getContractExpirationDate()), + () -> assertEquals(first.getContractedStorage(), second.getContractedStorage()), + () -> assertEquals(first.getInitialUseAllocation(), second.getInitialUseAllocation()), + () -> assertEquals(first.getFutureUseAllocation(), second.getFutureUseAllocation()), + () -> assertEquals(first.getStorageUnitsId(), second.getStorageUnitsId()), + () -> assertEquals(first.getFutureUsePercentActivated(), second.getFutureUsePercentActivated()), + () -> assertEquals(first.getTotalAllocPercentActivated(), second.getTotalAllocPercentActivated()), + () -> assertLocationType(first.getPumpOutLocation(), second.getPumpOutLocation()), + () -> assertLocationType(first.getPumpOutBelowLocation(), second.getPumpOutBelowLocation()), + () -> assertLocationType(first.getPumpInLocation(), second.getPumpInLocation()) + ); + } + + private static void assertWaterUserContractRefType(WaterUserContractRef first, WaterUserContractRef second) + { + assertAll( + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertWaterUserType(first.getWaterUser(), second.getWaterUser()) + ); + } +} + diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json new file mode 100644 index 000000000..1244e0401 --- /dev/null +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json @@ -0,0 +1,116 @@ +{ + "contract-name": "Test Contract", + "contract-number": 1234, + "water-user": "Test User", + "user": { + "entity-name": "Test Entity", + "parent-location-ref": { + "name": "Base Location", + "office-id": "SPK" + }, + "water-right": "Water Right test" + }, + "contract": { + "water-user-contract-ref": { + "water-user": { + "entity-name": "Entity Test", + "parent-location-ref": { + "name": "Base Location", + "office-id": "SPK" + }, + "water-right": "Water Right Test" + }, + "contract-name": "Contract Name Test" + }, + "water-supply-contract": { + "active": true, + "office-id": "SPK", + "tooltip": "Example Tooltip", + "display-value": "Display Value Test" + }, + "contract-effective-date": 1719854376, + "contract-expiration-date": 1719854376, + "contracted-storage": 1000, + "initial-use-allocation": 20.5, + "future-use-allocation": 79.5, + "storage-units-id": "Test Storage Unit", + "future-use-percent-activated": 25.5, + "total-alloc-percent-activated": 15.2, + "pump-out-location": { + "nearest-city": "Davis", + "nation": "US", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind": "PUMP", + "active": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump Out Location", + "vertical-datum": "WGS84", + "elevation-units": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "location-type": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "name": "Pump Out Location", + "office-id": "SPK" + }, + "pump-out-below-location": { + "nearest-city": "Davis", + "nation": "US", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind": "PUMP", + "active": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump Out Below Location", + "vertical-datum": "WGS84", + "elevation-units": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "location-type": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "name": "Pump Out Below Location", + "office-id": "SPK" + }, + "pump-in-location": { + "nearest-city": "Davis", + "nation": "US", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind": "PUMP", + "active": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump In Location", + "vertical-datum": "WGS84", + "elevation-units": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "location-type": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "name": "Pump In Location", + "office-id": "SPK" + + } + } +} \ No newline at end of file From f4130b5c373816f63ebb6359dbc9aa01b59a2ca5 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 3 Jul 2024 13:29:10 -0700 Subject: [PATCH 02/39] Implemented Water Supply DTO and Tests with updated design --- .../cda/data/dto/watersupply/WaterSupply.java | 147 ----------- .../dto/watersupply/WaterUserContractRef.java | 12 +- .../data/dto/watersupply/WaterSupplyTest.java | 242 ------------------ .../cda/data/dto/watersupply/watersupply.json | 116 --------- 4 files changed, 11 insertions(+), 506 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java delete mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java deleted file mode 100644 index a1f7d9368..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import cwms.cda.api.errors.FieldException; -import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.annotations.FormattableWith; -import cwms.cda.formatters.json.JsonV1; - -@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) -@JsonDeserialize(builder = WaterSupply.Builder.class) -public class WaterSupply implements CwmsDTOBase { - private final String contractName; - private final Integer contractNumber; - private final String waterUser; - private final WaterUser user; - private final WaterUserContract contract; - - private WaterSupply(Builder builder) { - contractName = builder.contractName; - contractNumber = builder.contractNumber; - waterUser = builder.waterUser; - user = builder.user; - contract = builder.contract; - } - - public String getContractName() { - return contractName; - } - - public Integer getContractNumber() { - return contractNumber; - } - - public String getWaterUser() { - return waterUser; - } - - public WaterUser getUser() { - return user; - } - - public WaterUserContract getContract() { - return contract; - } - - public static class Builder { - private String contractName; - private Integer contractNumber; - private String waterUser; - private WaterUser user; - private WaterUserContract contract; - - public Builder withContractName(String contractName) { - this.contractName = contractName; - return this; - } - - public Builder withContractNumber(Integer contractNumber) { - this.contractNumber = contractNumber; - return this; - } - - public Builder withWaterUser(String waterUser) { - this.waterUser = waterUser; - return this; - } - - public Builder withUser(WaterUser user) { - this.user = user; - return this; - } - - public Builder withContract(WaterUserContract contract) { - this.contract = contract; - return this; - } - - public WaterSupply build() { - return new WaterSupply(this); - } - } - - @Override - public void validate() throws FieldException { - if (contractName == null || contractName.isEmpty()) { - throw new FieldException("Contract Name cannot be null or empty"); - } - if (contractNumber == null) { - throw new FieldException("Contract Number cannot be null"); - } - if (waterUser == null || waterUser.isEmpty()) { - throw new FieldException("Water User cannot be null or empty"); - } - if (user == null) { - throw new FieldException("User Type cannot be null"); - } - if (user.getEntityName() == null) { - throw new FieldException("User Type Entity Name cannot be null"); - } - if (user.getWaterRight() == null) { - throw new FieldException("User Type Water Right cannot be null"); - } - if (contract == null) { - throw new FieldException("Contract Type cannot be null"); - } - if (contract.getWaterUserContractRef() == null) { - throw new FieldException("Water User Contract Ref Type cannot be null"); - } - if (contract.getWaterSupplyContract() == null) { - throw new FieldException("Water Supply Contract Type cannot be null"); - } - if (contract.getContractEffectiveDate() == null) { - throw new FieldException("Contract Effective Date cannot be null"); - } - if (contract.getInitialUseAllocation() == null) { - throw new FieldException("Contract Initial Use Allocation cannot be null"); - } - if (contract.getContractedStorage() == null) { - throw new FieldException("Contracted Storage cannot be null"); - } - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java index b16c02be4..ba36c7fce 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java @@ -26,7 +26,9 @@ package cwms.cda.data.dto.watersupply; -public class WaterUserContractRef { +import cwms.cda.data.dto.CwmsDTOBase; + +public class WaterUserContractRef implements CwmsDTOBase { private WaterUser waterUser; private String contractName; @@ -45,4 +47,12 @@ public String getContractName() { public WaterUser getWaterUser() { return this.waterUser; } + + @Override + public void validate() { + if (this.contractName == null) { + throw new IllegalArgumentException("ContractName cannot be null"); + } + this.waterUser.validate(); + } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java deleted file mode 100644 index af85fb9da..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import cwms.cda.api.enums.Nation; -import cwms.cda.api.errors.FieldException; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.CwmsIdTest; -import cwms.cda.formatters.Formats; -import cwms.cda.data.dto.LookupType; -import cwms.cda.data.dto.Location; -import org.apache.commons.io.IOUtils; -import org.junit.jupiter.api.Test; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.ZoneId; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -class WaterSupplyTest { - - private static final String OFFICE_ID = "SPK"; - - @Test - void testWaterSupplySerializationRoundTrip() { - WaterSupply waterSupply = buildTestWaterSupply(); - String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), waterSupply); - WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); - assertSame(waterSupply, deserialized); - } - - @Test - void testWaterSupplySerializationRoundTripFromFile() throws Exception - { - WaterSupply waterSupply = buildTestWaterSupply(); - InputStream resource = this.getClass().getResourceAsStream("/cwms/cda/data/dto/watersupply/watersupply.json"); - assertNotNull(resource); - String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); - WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); - assertSame(waterSupply, deserialized); - } - - @Test - void testValidate() - { - assertAll(() -> { - WaterSupply waterSupply = buildTestWaterSupply(); - assertDoesNotThrow(waterSupply::validate); - }, () -> { - WaterSupply waterSupply = new WaterSupply.Builder() - .withContractName("Test Contract") - .build(); - assertThrows(FieldException.class, waterSupply::validate, - "Expected validate() to throw FieldException for missing fields, but it didn't"); - } - ); - } - - private WaterSupply buildTestWaterSupply () - { - return new WaterSupply.Builder() - .withContractName("Test Contract") - .withContractNumber(1234) - .withWaterUser("Test User") - .withUser(new WaterUser("Test Entity", - new CwmsId.Builder() - .withName("Base Location") - .withOfficeId(OFFICE_ID) - .build(), - "Water Right test")) - .withContract(new WaterUserContract.Builder() - .withWaterUserContractRef(new WaterUserContractRef(new WaterUser("Entity Test", - new CwmsId.Builder() - .withName("Base Location") - .withOfficeId(OFFICE_ID) - .build(), - "Water Right Test"), - "Contract Name Test")) - .withWaterSupplyContract(new LookupType.Builder() - .withActive(true) - .withDisplayValue("Display Value Test") - .withOfficeId(OFFICE_ID) - .withTooltip("Example Tooltip") - .build()) - .withContractEffectiveDate(new Date(1719854376)) - .withContractExpirationDate(new Date(1719854376)) - .withContractedStorage(1000.0) - .withInitialUseAllocation(20.5) - .withFutureUseAllocation(79.5) - .withStorageUnitsId("Test Storage Unit") - .withFutureUsePercentActivated(25.5) - .withTotalAllocPercentActivated(15.2) - .withPumpOutLocation(buildLocationType("Pump Out Location")) - .withPumpOutBelowLocation(buildLocationType("Pump Out Below Location")) - .withPumpInLocation(buildLocationType("Pump In Location")) - .build()) - .build(); - } - - private Location buildLocationType(String pumpLocation) - { - return new Location.Builder(OFFICE_ID, pumpLocation) - .withStateInitial("CA") - .withBoundingOfficeId(OFFICE_ID) - .withDescription("Place for testing") - .withElevation(120.0) - .withCountyName("Sacramento") - .withHorizontalDatum("WGS84") - .withLatitude(0.0) - .withLongitude(0.0) - .withLongName("Full Location Name") - .withMapLabel("Map location") - .withNearestCity("Davis") - .withPublishedLatitude(0.0) - .withPublishedLongitude(0.0) - .withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("WGS84") - .withPublicName(pumpLocation) - .withLocationType("PUMP") - .withActive(true) - .withNation(Nation.US) - .withBoundingOfficeId(OFFICE_ID) - .withElevationUnits("m") - .withLocationKind("PUMP") - .build(); - } - - - private static void assertSame(WaterSupply first, WaterSupply second) - { - assertAll( - () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertEquals(first.getContractNumber(), second.getContractNumber()), - () -> assertEquals(first.getWaterUser(), second.getWaterUser()), - () -> assertWaterUserType(first.getUser(), second.getUser()), - () -> assertWaterUserContractType(first.getContract(), second.getContract()) - ); - } - - private static void assertLocationType(Location first, Location second) - { - assertAll( - () -> assertEquals(first.getNearestCity(), second.getNearestCity()), - () -> assertEquals(first.getNation(), second.getNation()), - () -> assertEquals(first.getBoundingOfficeId(), second.getBoundingOfficeId()), - () -> assertEquals(first.getPublishedLongitude(), second.getPublishedLongitude()), - () -> assertEquals(first.getPublishedLatitude(), second.getPublishedLatitude()), - () -> assertEquals(first.getMapLabel(), second.getMapLabel()), - () -> assertEquals(first.getLocationKind(), second.getLocationKind()), - () -> assertEquals(first.getActive(), second.getActive()), - () -> assertEquals(first.getDescription(), second.getDescription()), - () -> assertEquals(first.getLongName(), second.getLongName()), - () -> assertEquals(first.getPublicName(), second.getPublicName()), - () -> assertEquals(first.getVerticalDatum(), second.getVerticalDatum()), - () -> assertEquals(first.getElevationUnits(), second.getElevationUnits()), - () -> assertEquals(first.getElevation(), second.getElevation()), - () -> assertEquals(first.getHorizontalDatum(), second.getHorizontalDatum()), - () -> assertEquals(first.getLongitude(), second.getLongitude()), - () -> assertEquals(first.getLatitude(), second.getLatitude()), - () -> assertEquals(first.getLocationType(), second.getLocationType()), - () -> assertEquals(first.getTimezoneName(), second.getTimezoneName()), - () -> assertEquals(first.getCountyName(), second.getCountyName()), - () -> assertEquals(first.getStateInitial(), second.getStateInitial()), - () -> assertEquals(first.getName(), second.getName()) - ); - } - - private static void assertLookupType(LookupType first, LookupType second) - { - assertAll( - () -> assertEquals(first.getOfficeId(), second.getOfficeId()), - () -> assertEquals(first.getActive(), second.getActive()), - () -> assertEquals(first.getDisplayValue(), second.getDisplayValue()), - () -> assertEquals(first.getTooltip(), second.getTooltip()) - ); - } - - private static void assertWaterUserType(WaterUser first, WaterUser second) - { - assertAll( - () -> assertEquals(first.getEntityName(), second.getEntityName()), - () -> CwmsIdTest.assertSame(first.getParentLocationRef(), second.getParentLocationRef()), - () -> assertEquals(first.getWaterRight(), second.getWaterRight()) - ); - } - - private static void assertWaterUserContractType(WaterUserContract first, WaterUserContract second) - { - assertAll( - () -> assertWaterUserContractRefType(first.getWaterUserContractRef(), second.getWaterUserContractRef()), - () -> assertLookupType(first.getWaterSupplyContract(), second.getWaterSupplyContract()), - () -> assertEquals(first.getContractEffectiveDate(), second.getContractEffectiveDate()), - () -> assertEquals(first.getContractExpirationDate(), second.getContractExpirationDate()), - () -> assertEquals(first.getContractedStorage(), second.getContractedStorage()), - () -> assertEquals(first.getInitialUseAllocation(), second.getInitialUseAllocation()), - () -> assertEquals(first.getFutureUseAllocation(), second.getFutureUseAllocation()), - () -> assertEquals(first.getStorageUnitsId(), second.getStorageUnitsId()), - () -> assertEquals(first.getFutureUsePercentActivated(), second.getFutureUsePercentActivated()), - () -> assertEquals(first.getTotalAllocPercentActivated(), second.getTotalAllocPercentActivated()), - () -> assertLocationType(first.getPumpOutLocation(), second.getPumpOutLocation()), - () -> assertLocationType(first.getPumpOutBelowLocation(), second.getPumpOutBelowLocation()), - () -> assertLocationType(first.getPumpInLocation(), second.getPumpInLocation()) - ); - } - - private static void assertWaterUserContractRefType(WaterUserContractRef first, WaterUserContractRef second) - { - assertAll( - () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertWaterUserType(first.getWaterUser(), second.getWaterUser()) - ); - } -} - diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json deleted file mode 100644 index 1244e0401..000000000 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "contract-name": "Test Contract", - "contract-number": 1234, - "water-user": "Test User", - "user": { - "entity-name": "Test Entity", - "parent-location-ref": { - "name": "Base Location", - "office-id": "SPK" - }, - "water-right": "Water Right test" - }, - "contract": { - "water-user-contract-ref": { - "water-user": { - "entity-name": "Entity Test", - "parent-location-ref": { - "name": "Base Location", - "office-id": "SPK" - }, - "water-right": "Water Right Test" - }, - "contract-name": "Contract Name Test" - }, - "water-supply-contract": { - "active": true, - "office-id": "SPK", - "tooltip": "Example Tooltip", - "display-value": "Display Value Test" - }, - "contract-effective-date": 1719854376, - "contract-expiration-date": 1719854376, - "contracted-storage": 1000, - "initial-use-allocation": 20.5, - "future-use-allocation": 79.5, - "storage-units-id": "Test Storage Unit", - "future-use-percent-activated": 25.5, - "total-alloc-percent-activated": 15.2, - "pump-out-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump Out Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump Out Location", - "office-id": "SPK" - }, - "pump-out-below-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump Out Below Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump Out Below Location", - "office-id": "SPK" - }, - "pump-in-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump In Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump In Location", - "office-id": "SPK" - - } - } -} \ No newline at end of file From d6708f8d3a41fb29838d24bfe7f36515765957ea Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 16 Jul 2024 14:53:35 -0700 Subject: [PATCH 03/39] Updated Water Supply DTO validators --- .../data/dto/watersupply/WaterUserContractRef.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java index ba36c7fce..835170f5f 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java @@ -27,8 +27,9 @@ package cwms.cda.data.dto.watersupply; import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.data.dto.CwmsDTOValidator; -public class WaterUserContractRef implements CwmsDTOBase { +public class WaterUserContractRef extends CwmsDTOBase { private WaterUser waterUser; private String contractName; @@ -49,10 +50,9 @@ public WaterUser getWaterUser() { } @Override - public void validate() { - if (this.contractName == null) { - throw new IllegalArgumentException("ContractName cannot be null"); - } - this.waterUser.validate(); + protected void validateInternal(CwmsDTOValidator validator) { + super.validateInternal(validator); + validator.required(getContractName(), "contract-name"); + validator.required(getWaterUser(), "water-user"); } } From d396307d479cacc9529bb0d3f75af80ba550bb15 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 16 Jul 2024 15:45:25 -0700 Subject: [PATCH 04/39] Removed internal validation, replaced with JSON require; Added formattable tags to water user --- .../data/dto/watersupply/WaterUserContractRef.java | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java index 835170f5f..5768942a8 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java @@ -26,11 +26,13 @@ package cwms.cda.data.dto.watersupply; +import com.fasterxml.jackson.annotation.JsonProperty; import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.data.dto.CwmsDTOValidator; public class WaterUserContractRef extends CwmsDTOBase { + @JsonProperty(required = true) private WaterUser waterUser; + @JsonProperty(required = true) private String contractName; private WaterUserContractRef() { @@ -48,11 +50,4 @@ public String getContractName() { public WaterUser getWaterUser() { return this.waterUser; } - - @Override - protected void validateInternal(CwmsDTOValidator validator) { - super.validateInternal(validator); - validator.required(getContractName(), "contract-name"); - validator.required(getWaterUser(), "water-user"); - } } From df3d00784e80bd021923a8a454a376ec5d9abbae Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 17 Jul 2024 16:33:05 -0700 Subject: [PATCH 05/39] Renamed PUMP enum and some other variables, Removed WaterUserContractRef.java --- .../dto/watersupply/WaterUserContractRef.java | 53 ------------------- 1 file changed, 53 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java deleted file mode 100644 index 5768942a8..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRef.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import com.fasterxml.jackson.annotation.JsonProperty; -import cwms.cda.data.dto.CwmsDTOBase; - -public class WaterUserContractRef extends CwmsDTOBase { - @JsonProperty(required = true) - private WaterUser waterUser; - @JsonProperty(required = true) - private String contractName; - - private WaterUserContractRef() { - } - - public WaterUserContractRef(WaterUser waterUser, String contractName) { - this.waterUser = waterUser; - this.contractName = contractName; - } - - public String getContractName() { - return this.contractName; - } - - public WaterUser getWaterUser() { - return this.waterUser; - } -} From a202cc82d56441bffe4a41db0e62805b89768f61 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 1 Jul 2024 12:30:05 -0700 Subject: [PATCH 06/39] Implemented Water Supply DTO and Tests --- .../data/dto/watersupply/LocationRefType.java | 54 +++ .../data/dto/watersupply/LocationType.java | 343 ++++++++++++++++++ .../cda/data/dto/watersupply/LookupType.java | 60 +++ .../cda/data/dto/watersupply/WaterSupply.java | 126 +++++++ .../watersupply/WaterUserContractRefType.java | 48 +++ .../watersupply/WaterUserContractType.java | 206 +++++++++++ .../data/dto/watersupply/WaterUserType.java | 55 +++ .../data/dto/watersupply/WaterSupplyTest.java | 235 ++++++++++++ .../cda/data/dto/watersupply/watersupply.json | 129 +++++++ 9 files changed, 1256 insertions(+) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java create mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java new file mode 100644 index 000000000..3abd428f1 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java @@ -0,0 +1,54 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +public class LocationRefType { + private String baseLocationId; + private String officeId; + private String subLocationId; + + private LocationRefType() { + } + + public LocationRefType(String baseLocationId, String subLocationId, String officeId) { + this.baseLocationId = baseLocationId; + this.subLocationId = subLocationId; + this.officeId = officeId; + } + + public String getBaseLocationId() { + return this.baseLocationId; + } + + public String getSubLocationId() { + return this.subLocationId; + } + + public String getOfficeId() { + return this.officeId; + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java new file mode 100644 index 000000000..9961e6685 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java @@ -0,0 +1,343 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +public class LocationType { + private final String nearestCity; + private final String nationId; + private final String boundingOfficeName; + private final String boundingOfficeId; + private final Double publishedLongitude; + private final Double publishedLatitude; + private final String mapLabel; + private final String locationKindId; + private final boolean activeFlag; + private final String description; + private final String longName; + private final String publicName; + private final String verticalDatum; + private final String elevUnitId; + private final Double elevation; + private final String horizontalDatum; + private final Double longitude; + private final Double latitude; + private final String typeOfLocation; + private final String timeZoneName; + private final String countyName; + private final String stateInitial; + private final LocationRefType locationRefType; + + private LocationType() { + this.nearestCity = null; + this.nationId = null; + this.boundingOfficeName = null; + this.boundingOfficeId = null; + this.publishedLongitude = null; + this.publishedLatitude = null; + this.mapLabel = null; + this.locationKindId = null; + this.activeFlag = false; + this.description = null; + this.longName = null; + this.publicName = null; + this.verticalDatum = null; + this.elevUnitId = null; + this.elevation = null; + this.horizontalDatum = null; + this.longitude = null; + this.latitude = null; + this.typeOfLocation = null; + this.timeZoneName = null; + this.countyName = null; + this.stateInitial = null; + this.locationRefType = null; + } + + + public LocationType(Builder builder) { + this.locationRefType = builder.locationRefType; + this.stateInitial = builder.stateInitial; + this.countyName = builder.countyName; + this.timeZoneName = builder.timeZoneName; + this.typeOfLocation = builder.typeOfLocation; + this.latitude = builder.latitude; + this.longitude = builder.longitude; + this.horizontalDatum = builder.horizontalDatum; + this.elevation = builder.elevation; + this.elevUnitId = builder.elevUnitId; + this.verticalDatum = builder.verticalDatum; + this.publicName = builder.publicName; + this.longName = builder.longName; + this.description = builder.description; + this.activeFlag = builder.activeFlag; + this.locationKindId = builder.locationKindId; + this.mapLabel = builder.mapLabel; + this.publishedLatitude = builder.publishedLatitude; + this.publishedLongitude = builder.publishedLongitude; + this.boundingOfficeId = builder.boundingOfficeId; + this.boundingOfficeName = builder.boundingOfficeName; + this.nationId = builder.nationId; + this.nearestCity = builder.nearestCity; + } + + public String getNearestCity() { + return this.nearestCity; + } + + public String getNationId() { + return this.nationId; + } + + public String getBoundingOfficeName() { + return this.boundingOfficeName; + } + + public String getBoundingOfficeId() { + return this.boundingOfficeId; + } + + public Double getPublishedLongitude() { + return this.publishedLongitude; + } + + public Double getPublishedLatitude() { + return this.publishedLatitude; + } + + public String getMapLabel() { + return this.mapLabel; + } + + public String getLocationKindId() { + return this.locationKindId; + } + + public boolean getActiveFlag() { + return this.activeFlag; + } + + public String getDescription() { + return this.description; + } + + public String getLongName() { + return this.longName; + } + + public String getPublicName() { + return this.publicName; + } + + public String getVerticalDatum() { + return this.verticalDatum; + } + + public String getElevUnitId() { + return this.elevUnitId; + } + + public Double getElevation() { + return this.elevation; + } + + public String getHorizontalDatum() { + return this.horizontalDatum; + } + + public Double getLongitude() { + return this.longitude; + } + + public Double getLatitude() { + return this.latitude; + } + + public String getTypeOfLocation() { + return this.typeOfLocation; + } + + public String getTimeZoneName() { + return this.timeZoneName; + } + + public String getCountyName() { + return this.countyName; + } + + public String getStateInitial() { + return this.stateInitial; + } + + public LocationRefType getLocationRefType() { + return this.locationRefType; + } + + public static class Builder { + private String nearestCity; + private String nationId; + private String boundingOfficeName; + private String boundingOfficeId; + private Double publishedLongitude; + private Double publishedLatitude; + private String mapLabel; + private String locationKindId; + private boolean activeFlag; + private String description; + private String longName; + private String publicName; + private String verticalDatum; + private String elevUnitId; + private Double elevation; + private String horizontalDatum; + private Double longitude; + private Double latitude; + private String typeOfLocation; + private String timeZoneName; + private String countyName; + private String stateInitial; + private LocationRefType locationRefType; + + public Builder withNearestCity(String nearestCity) { + this.nearestCity = nearestCity; + return this; + } + + public Builder withNationId(String nationId) { + this.nationId = nationId; + return this; + } + + public Builder withBoundingOfficeName(String boundingOfficeName) { + this.boundingOfficeName = boundingOfficeName; + return this; + } + + public Builder withBoundingOfficeId(String boundingOfficeId) { + this.boundingOfficeId = boundingOfficeId; + return this; + } + + public Builder withPublishedLongitude(Double publishedLongitude) { + this.publishedLongitude = publishedLongitude; + return this; + } + + public Builder withPublishedLatitude(Double publishedLatitude) { + this.publishedLatitude = publishedLatitude; + return this; + } + + public Builder withMapLabel(String mapLabel) { + this.mapLabel = mapLabel; + return this; + } + + public Builder withLocationKindId(String locationKindId) { + this.locationKindId = locationKindId; + return this; + } + + public Builder withActiveFlag(boolean activeFlag) { + this.activeFlag = activeFlag; + return this; + } + + public Builder withDescription(String description) { + this.description = description; + return this; + } + + public Builder withLongName(String longName) { + this.longName = longName; + return this; + } + + public Builder withPublicName(String publicName) { + this.publicName = publicName; + return this; + } + + public Builder withVerticalDatum(String verticalDatum) { + this.verticalDatum = verticalDatum; + return this; + } + + public Builder withElevUnitId(String elevUnitId) { + this.elevUnitId = elevUnitId; + return this; + } + + public Builder withElevation(Double elevation) { + this.elevation = elevation; + return this; + } + + public Builder withHorizontalDatum(String horizontalDatum) { + this.horizontalDatum = horizontalDatum; + return this; + } + + public Builder withLongitude(Double longitude) { + this.longitude = longitude; + return this; + } + + public Builder withLatitude(Double latitude) { + this.latitude = latitude; + return this; + } + + public Builder withTypeOfLocation(String typeOfLocation) { + this.typeOfLocation = typeOfLocation; + return this; + } + + public Builder withTimeZoneName(String timeZoneName) { + this.timeZoneName = timeZoneName; + return this; + } + + public Builder withCountyName(String countyName) { + this.countyName = countyName; + return this; + } + + public Builder withStateInitial(String stateInitial) { + this.stateInitial = stateInitial; + return this; + } + + public Builder withLocationRefType(LocationRefType locationRefType) { + this.locationRefType = locationRefType; + return this; + } + + public LocationType build() { + return new LocationType(this); + } + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java new file mode 100644 index 000000000..39f8bf572 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java @@ -0,0 +1,60 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +public class LookupType { + private boolean active; + private String officeId; + private String tooltip; + private String displayValue; + + public LookupType() { + } + + public LookupType(String officeId, String displayValue, String tooltip, boolean active) { + this.officeId = officeId; + this.displayValue = displayValue; + this.tooltip = tooltip; + this.active = active; + } + + public String getOfficeId() { + return this.officeId; + } + + public String getDisplayValue() { + return this.displayValue; + } + + public String getTooltip() { + return this.tooltip; + } + + public boolean getActive() { + return this.active; + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java new file mode 100644 index 000000000..4c64199ca --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java @@ -0,0 +1,126 @@ +/* + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) +@JsonDeserialize(builder = WaterSupply.Builder.class) +public class WaterSupply implements CwmsDTOBase { + private final String contractName; + private final Integer contractNumber; + private final String waterUser; + private final WaterUserType userType; + private final WaterUserContractType contractType; + + private WaterSupply(Builder builder) { + contractName = builder.contractName; + contractNumber = builder.contractNumber; + waterUser = builder.waterUser; + userType = builder.userType; + contractType = builder.contractType; + } + + public String getContractName() { + return contractName; + } + + public Integer getContractNumber() { + return contractNumber; + } + + public String getWaterUser() { + return waterUser; + } + + public WaterUserType getUserType() { + return userType; + } + + public WaterUserContractType getContractType() { + return contractType; + } + + public static class Builder { + private String contractName; + private Integer contractNumber; + private String waterUser; + private WaterUserType userType; + private WaterUserContractType contractType; + + public Builder withContractName(String contractName) { + this.contractName = contractName; + return this; + } + + public Builder withContractNumber(Integer contractNumber) { + this.contractNumber = contractNumber; + return this; + } + + public Builder withWaterUser(String waterUser) { + this.waterUser = waterUser; + return this; + } + + public Builder withUserType(WaterUserType userType) { + this.userType = userType; + return this; + } + + public Builder withContractType(WaterUserContractType contractType) { + this.contractType = contractType; + return this; + } + + public WaterSupply build() { + return new WaterSupply(this); + } + } + + @Override + public void validate() throws FieldException { + if (contractName == null || contractName.isEmpty()) { + throw new FieldException("Contract Name cannot be null or empty"); + } + if (contractNumber == null) { + throw new FieldException("Contract Number cannot be null"); + } + if (waterUser == null || waterUser.isEmpty()) { + throw new FieldException("Water User cannot be null or empty"); + } + if (userType == null) { + throw new FieldException("User Type cannot be null"); + } + if (contractType == null) { + throw new FieldException("Contract Type cannot be null"); + } + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java new file mode 100644 index 000000000..effc7dfcf --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java @@ -0,0 +1,48 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +public class WaterUserContractRefType { + private WaterUserType waterUserType; + private String contractName; + + private WaterUserContractRefType() { + } + + public WaterUserContractRefType(WaterUserType waterUserType, String contractName) { + this.waterUserType = waterUserType; + this.contractName = contractName; + } + + public String getContractName() { + return this.contractName; + } + + public WaterUserType getWaterUserType() { + return this.waterUserType; + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java new file mode 100644 index 000000000..d4b6289a2 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java @@ -0,0 +1,206 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; +import java.util.Date; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) +@JsonDeserialize(builder = WaterUserContractType.Builder.class) +public class WaterUserContractType { + + private final WaterUserContractRefType waterUserContractRefType; + private final LookupType waterSupplyContractType; + private final Date contractEffectiveDate; + private final Date contractExpirationDate; + private final Double contractedStorage; + private final Double initialUseAllocation; + private final Double futureUseAllocation; + private final String storageUnitsId; + private final Double futureUsePercentActivated; + private final Double totalAllocPercentActivated; + private final LocationType pumpOutLocation; + private final LocationType pumpOutBelowLocation; + private final LocationType pumpInLocation; + + private WaterUserContractType(Builder builder) { + this.waterUserContractRefType = builder.waterUserContractRefType; + this.waterSupplyContractType = builder.waterSupplyContractType; + this.contractEffectiveDate = builder.contractEffectiveDate; + this.contractExpirationDate = builder.contractExpirationDate; + this.contractedStorage = builder.contractedStorage; + this.initialUseAllocation = builder.initialUseAllocation; + this.futureUseAllocation = builder.futureUseAllocation; + this.storageUnitsId = builder.storageUnitsId; + this.futureUsePercentActivated = builder.futureUsePercentActivated; + this.totalAllocPercentActivated = builder.totalAllocPercentActivated; + this.pumpOutLocation = builder.pumpOutLocation; + this.pumpOutBelowLocation = builder.pumpOutBelowLocation; + this.pumpInLocation = builder.pumpInLocation; + } + + public WaterUserContractRefType getWaterUserContractRefType() { + return this.waterUserContractRefType; + } + + public LookupType getWaterSupplyContractType() { + return this.waterSupplyContractType; + } + + public Date getContractEffectiveDate() { + return this.contractEffectiveDate; + } + + public Date getContractExpirationDate() { + return this.contractExpirationDate; + } + + public Double getContractedStorage() { + return this.contractedStorage; + } + + public Double getInitialUseAllocation() { + return this.initialUseAllocation; + } + + public Double getFutureUseAllocation() { + return this.futureUseAllocation; + } + + public String getStorageUnitsId() { + return this.storageUnitsId; + } + + public Double getFutureUsePercentActivated() { + return this.futureUsePercentActivated; + } + + public Double getTotalAllocPercentActivated() { + return this.totalAllocPercentActivated; + } + + public LocationType getPumpOutLocation() { + return this.pumpOutLocation; + } + + public LocationType getPumpOutBelowLocation() { + return this.pumpOutBelowLocation; + } + + public LocationType getPumpInLocation() { + return this.pumpInLocation; + } + + public static class Builder { + private WaterUserContractRefType waterUserContractRefType; + private LookupType waterSupplyContractType; + private Date contractEffectiveDate; + private Date contractExpirationDate; + private Double contractedStorage; + private Double initialUseAllocation; + private Double futureUseAllocation; + private String storageUnitsId; + private Double futureUsePercentActivated; + private Double totalAllocPercentActivated; + private LocationType pumpOutLocation; + private LocationType pumpOutBelowLocation; + private LocationType pumpInLocation; + + public Builder withWaterUserContractRefType(WaterUserContractRefType waterUserContractRefType) { + this.waterUserContractRefType = waterUserContractRefType; + return this; + } + + public Builder withWaterSupplyContractType(LookupType waterSupplyContractType) { + this.waterSupplyContractType = waterSupplyContractType; + return this; + } + + public Builder withContractEffectiveDate(Date contractEffectiveDate) { + this.contractEffectiveDate = contractEffectiveDate; + return this; + } + + public Builder withContractExpirationDate(Date contractExpirationDate) { + this.contractExpirationDate = contractExpirationDate; + return this; + } + + public Builder withContractedStorage(Double contractedStorage) { + this.contractedStorage = contractedStorage; + return this; + } + + public Builder withInitialUseAllocation(Double initialUseAllocation) { + this.initialUseAllocation = initialUseAllocation; + return this; + } + + public Builder withFutureUseAllocation(Double futureUseAllocation) { + this.futureUseAllocation = futureUseAllocation; + return this; + } + + public Builder withStorageUnitsId(String storageUnitsId) { + this.storageUnitsId = storageUnitsId; + return this; + } + + public Builder withFutureUsePercentActivated(Double futureUsePercentActivated) { + this.futureUsePercentActivated = futureUsePercentActivated; + return this; + } + + public Builder withTotalAllocPercentActivated(Double totalAllocPercentActivated) { + this.totalAllocPercentActivated = totalAllocPercentActivated; + return this; + } + + public Builder withPumpOutLocation(LocationType pumpOutLocation) { + this.pumpOutLocation = pumpOutLocation; + return this; + } + + public Builder withPumpOutBelowLocation(LocationType pumpOutBelowLocation) { + this.pumpOutBelowLocation = pumpOutBelowLocation; + return this; + } + + public Builder withPumpInLocation(LocationType pumpInLocation) { + this.pumpInLocation = pumpInLocation; + return this; + } + + public WaterUserContractType build() { + return new WaterUserContractType(this); + } + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java new file mode 100644 index 000000000..90093fc48 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java @@ -0,0 +1,55 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package cwms.cda.data.dto.watersupply; + +public class WaterUserType { + + private String entityName; + private LocationRefType parentLocationRefType; + private String waterRight; + + private WaterUserType() { + } + + public WaterUserType(String entityName, LocationRefType locationRefType, String waterRight) { + this.entityName = entityName; + this.parentLocationRefType = locationRefType; + this.waterRight = waterRight; + } + + public LocationRefType getParentLocationRefType() { + return this.parentLocationRefType; + } + + public String getEntityName() { + return this.entityName; + } + + public String getWaterRight() { + return this.waterRight; + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java new file mode 100644 index 000000000..27468612b --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java @@ -0,0 +1,235 @@ +/* + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import cwms.cda.api.errors.FieldException; +import cwms.cda.formatters.Formats; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertAll; + +class WaterSupplyTest { + + private static final String OFFICE_ID = "SPK"; + + @Test + void testWaterSupplySerializationRoundTrip() { + WaterSupply waterSupply = buildTestWaterSupply(); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), waterSupply); + WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); + assertSame(waterSupply, deserialized); + } + + @Test + void testWaterSupplySerializationRoundTripFromFile() throws Exception + { + WaterSupply waterSupply = buildTestWaterSupply(); + InputStream resource = this.getClass().getResourceAsStream("/cwms/cda/data/dto/watersupply/watersupply.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); + assertSame(waterSupply, deserialized); + } + + @Test + void testValidate() + { + assertAll(() -> { + WaterSupply waterSupply = buildTestWaterSupply(); + assertThrows(FieldException.class, waterSupply::validate); + }, () -> { + WaterSupply waterSupply = new WaterSupply.Builder() + .withContractName("Test Contract") + .build(); + assertThrows(FieldException.class, waterSupply::validate, + "Expected validate() to throw FieldException for missing fields, but it didn't"); + } + ); + } + + private WaterSupply buildTestWaterSupply () + { + return new WaterSupply.Builder() + .withContractName("Test Contract") + .withContractNumber(1234) + .withWaterUser("Test User") + .withUserType(new WaterUserType("Test Entity", + new LocationRefType("Base Location", "Sub location", OFFICE_ID), + "Water Right test")) + .withContractType(new WaterUserContractType.Builder() + .withWaterUserContractRefType(new WaterUserContractRefType(new WaterUserType("Entity Test", + new LocationRefType("Base Location", "Sub Location", OFFICE_ID), + "Water Right Test"), + "Contract Name Test")) + .withWaterSupplyContractType(new LookupType(OFFICE_ID, "Display Value Test", "Example Tooltip", true)) + .withContractEffectiveDate(new Date()) + .withContractExpirationDate(new Date()) + .withContractedStorage(1000.0) + .withInitialUseAllocation(20.5) + .withFutureUseAllocation(79.5) + .withStorageUnitsId("Test Storage Unit") + .withFutureUsePercentActivated(25.5) + .withTotalAllocPercentActivated(15.2) + .withPumpOutLocation(buildLocationType("Pump Out Location")) + .withPumpOutBelowLocation(buildLocationType("Pump Out Below Location")) + .withPumpInLocation(buildLocationType("Pump In Location")) + .build()) + .build(); + } + + private LocationType buildLocationType(String pumpLocation) + { + return new LocationType.Builder() + .withLocationRefType( new LocationRefType("Base Location", "Sub location", OFFICE_ID)) + .withStateInitial("CA") + .withActiveFlag(true) + .withBoundingOfficeId(OFFICE_ID) + .withDescription("Place for testing") + .withElevation(120.0) + .withCountyName("Sacramento") + .withElevUnitId("m") + .withHorizontalDatum("WGS84") + .withLatitude(0.0) + .withLongitude(0.0) + .withLocationKindId("PUMP") + .withLongName(pumpLocation) + .withMapLabel("Map location") + .withNationId("US") + .withNearestCity("Davis") + .withPublishedLatitude(0.0) + .withPublishedLongitude(0.0) + .withTimeZoneName("UTC") + .withTypeOfLocation("WGS84") + .withBoundingOfficeName("Sacramento") + .withVerticalDatum("WGS84") + .withPublicName(pumpLocation) + .build(); + } + + + private static void assertSame(WaterSupply first, WaterSupply second) + { + assertAll( + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertEquals(first.getContractNumber(), second.getContractNumber()), + () -> assertEquals(first.getWaterUser(), second.getWaterUser()), + () -> assertWaterUserType(first.getUserType(), second.getUserType()), + () -> assertWaterUserContractType(first.getContractType(), second.getContractType()) + ); + } + + private static void assertLocationRefType(LocationRefType first, LocationRefType second) + { + assertAll( + () -> assertEquals(first.getBaseLocationId(), second.getBaseLocationId()), + () -> assertEquals(first.getOfficeId(), second.getOfficeId()), + () -> assertEquals(first.getSubLocationId(), second.getSubLocationId()) + ); + } + + private static void assertLocationType(LocationType first, LocationType second) + { + assertAll( + () -> assertEquals(first.getNearestCity(), second.getNearestCity()), + () -> assertEquals(first.getNationId(), second.getNationId()), + () -> assertEquals(first.getBoundingOfficeName(), second.getBoundingOfficeName()), + () -> assertEquals(first.getBoundingOfficeId(), second.getBoundingOfficeId()), + () -> assertEquals(first.getPublishedLongitude(), second.getPublishedLongitude()), + () -> assertEquals(first.getPublishedLatitude(), second.getPublishedLatitude()), + () -> assertEquals(first.getMapLabel(), second.getMapLabel()), + () -> assertEquals(first.getLocationKindId(), second.getLocationKindId()), + () -> assertEquals(first.getActiveFlag(), second.getActiveFlag()), + () -> assertEquals(first.getDescription(), second.getDescription()), + () -> assertEquals(first.getLongName(), second.getLongName()), + () -> assertEquals(first.getPublicName(), second.getPublicName()), + () -> assertEquals(first.getVerticalDatum(), second.getVerticalDatum()), + () -> assertEquals(first.getElevUnitId(), second.getElevUnitId()), + () -> assertEquals(first.getElevation(), second.getElevation()), + () -> assertEquals(first.getHorizontalDatum(), second.getHorizontalDatum()), + () -> assertEquals(first.getLongitude(), second.getLongitude()), + () -> assertEquals(first.getLatitude(), second.getLatitude()), + () -> assertEquals(first.getTypeOfLocation(), second.getTypeOfLocation()), + () -> assertEquals(first.getTimeZoneName(), second.getTimeZoneName()), + () -> assertEquals(first.getCountyName(), second.getCountyName()), + () -> assertEquals(first.getStateInitial(), second.getStateInitial()), + () -> assertLocationRefType(first.getLocationRefType(), second.getLocationRefType()) + ); + } + + private static void assertLookupType(LookupType first, LookupType second) + { + assertAll( + () -> assertEquals(first.getOfficeId(), second.getOfficeId()), + () -> assertEquals(first.getActive(), second.getActive()), + () -> assertEquals(first.getDisplayValue(), second.getDisplayValue()), + () -> assertEquals(first.getTooltip(), second.getTooltip()) + ); + } + + private static void assertWaterUserType(WaterUserType first, WaterUserType second) + { + assertAll( + () -> assertEquals(first.getEntityName(), second.getEntityName()), + () -> assertLocationRefType(first.getParentLocationRefType(), second.getParentLocationRefType()), + () -> assertEquals(first.getWaterRight(), second.getWaterRight()) + ); + } + + private static void assertWaterUserContractType(WaterUserContractType first, WaterUserContractType second) + { + assertAll( + () -> assertWaterUserContractRefType(first.getWaterUserContractRefType(), second.getWaterUserContractRefType()), + () -> assertLookupType(first.getWaterSupplyContractType(), second.getWaterSupplyContractType()), + () -> assertEquals(first.getContractEffectiveDate(), second.getContractEffectiveDate()), + () -> assertEquals(first.getContractExpirationDate(), second.getContractExpirationDate()), + () -> assertEquals(first.getContractedStorage(), second.getContractedStorage()), + () -> assertEquals(first.getInitialUseAllocation(), second.getInitialUseAllocation()), + () -> assertEquals(first.getFutureUseAllocation(), second.getFutureUseAllocation()), + () -> assertEquals(first.getStorageUnitsId(), second.getStorageUnitsId()), + () -> assertEquals(first.getFutureUsePercentActivated(), second.getFutureUsePercentActivated()), + () -> assertEquals(first.getTotalAllocPercentActivated(), second.getTotalAllocPercentActivated()), + () -> assertLocationType(first.getPumpOutLocation(), second.getPumpOutLocation()), + () -> assertLocationType(first.getPumpOutBelowLocation(), second.getPumpOutBelowLocation()), + () -> assertLocationType(first.getPumpInLocation(), second.getPumpInLocation()) + ); + } + + private static void assertWaterUserContractRefType(WaterUserContractRefType first, WaterUserContractRefType second) + { + assertAll( + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertWaterUserType(first.getWaterUserType(), second.getWaterUserType()) + ); + } +} + diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json new file mode 100644 index 000000000..2fb8cafce --- /dev/null +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json @@ -0,0 +1,129 @@ +{ + "contract-name": "Test Contract", + "contract-number": 1234, + "water-user": "Test User", + "user-type": { + "entity-name": "Test Entity", + "parent-location-ref-type": { + "base-location-id": "Base Location", + "office-id": "SPK", + "sub-location-id": "Sub location" + }, + "water-right": "Water Right test" + }, + "contract-type": { + "water-user-contract-ref-type": { + "water-user-type": { + "entity-name": "Entity Test", + "parent-location-ref-type": { + "base-location-id": "Base Location", + "office-id": "SPK", + "sub-location-id": "Sub Location" + }, + "water-right": "Water Right Test" + }, + "contract-name": "Contract Name Test" + }, + "water-supply-contract-type": { + "active": true, + "office-id": "SPK", + "tooltip": "Example Tooltip", + "display-value": "Display Value Test" + }, + "contract-effective-date": 1719854376876, + "contract-expiration-date": 1719854376876, + "contracted-storage": 1000, + "initial-use-allocation": 20.5, + "future-use-allocation": 79.5, + "storage-units-id": "Test Storage Unit", + "future-use-percent-activated": 25.5, + "total-alloc-percent-activated": 15.2, + "pump-out-location": { + "nearest-city": "Davis", + "nation-id": "US", + "bounding-office-name": "Sacramento Office", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind-id": "Test Locale", + "active-flag": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump Out Location", + "vertical-datum": "WGS84", + "elev-unit-id": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "type-of-location": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "location-ref-type": { + "base-location-id": "Base Location", + "office-id": "SPK", + "sub-location-id": "Sub location" + } + }, + "pump-out-below-location": { + "nearest-city": "Davis", + "nation-id": "US", + "bounding-office-name": "Sacramento Office", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind-id": "Test Locale", + "active-flag": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump Out Below Location", + "vertical-datum": "WGS84", + "elev-unit-id": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "type-of-location": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "location-ref-type": { + "base-location-id": "Base Location", + "office-id": "SPK", + "sub-location-id": "Sub location" + } + }, + "pump-in-location": { + "nearest-city": "Davis", + "nation-id": "US", + "bounding-office-name": "Sacramento Office", + "bounding-office-id": "SPK", + "published-longitude": 0, + "published-latitude": 0, + "map-label": "Map location", + "location-kind-id": "Test Locale", + "active-flag": true, + "description": "Place for testing", + "long-name": "Full Location Name", + "public-name": "Pump In Location", + "vertical-datum": "WGS84", + "elev-unit-id": "m", + "elevation": 120, + "horizontal-datum": "WGS84", + "longitude": 0, + "latitude": 0, + "type-of-location": "PUMP", + "time-zone-name": "UTC", + "county-name": "Sacramento", + "state-initial": "CA", + "location-ref-type": { + "base-location-id": "Base Location", + "office-id": "SPK", + "sub-location-id": "Sub location" + } + } + } +} \ No newline at end of file From 8b534c946c744ee8b4400b7728ebc8ef3daffe21 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 1 Jul 2024 13:18:22 -0700 Subject: [PATCH 07/39] Updated validation function --- .../cda/data/dto/watersupply/WaterSupply.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java index 4c64199ca..8036c550c 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java @@ -119,8 +119,30 @@ public void validate() throws FieldException { if (userType == null) { throw new FieldException("User Type cannot be null"); } + if(userType.getEntityName() == null) + { + throw new FieldException("User Type Entity Name cannot be null"); + } + if(userType.getWaterRight() == null) { + throw new FieldException("User Type Water Right cannot be null"); + } if (contractType == null) { throw new FieldException("Contract Type cannot be null"); } + if (contractType.getWaterUserContractRefType() == null) { + throw new FieldException("Water User Contract Ref Type cannot be null"); + } + if (contractType.getWaterSupplyContractType() == null) { + throw new FieldException("Water Supply Contract Type cannot be null"); + } + if (contractType.getContractEffectiveDate() == null) { + throw new FieldException("Contract Effective Date cannot be null"); + } + if (contractType.getInitialUseAllocation() == null) { + throw new FieldException("Contract Initial Use Allocation cannot be null"); + } + if (contractType.getContractedStorage() == null) { + throw new FieldException("Contracted Storage cannot be null"); + } } } From e203dc897bbd487c97b91a43e383db86978ed7c9 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 2 Jul 2024 11:07:46 -0700 Subject: [PATCH 08/39] Renamed Type files, Removed duplicate LookupType and LocationRefType classes --- .../{LocationType.java => Location.java} | 28 +-- .../data/dto/watersupply/LocationRefType.java | 54 ----- .../cda/data/dto/watersupply/WaterSupply.java | 47 ++-- .../watersupply/WaterUserContractRefType.java | 48 ---- .../watersupply/WaterUserContractType.java | 206 ------------------ .../data/dto/watersupply/WaterUserType.java | 55 ----- .../data/dto/watersupply/WaterSupplyTest.java | 81 ++++--- .../cda/data/dto/watersupply/watersupply.json | 49 ++--- 8 files changed, 105 insertions(+), 463 deletions(-) rename cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/{LocationType.java => Location.java} (94%) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java similarity index 94% rename from cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java rename to cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java index 9961e6685..533d9ef8d 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationType.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java @@ -26,7 +26,9 @@ package cwms.cda.data.dto.watersupply; -public class LocationType { +import cwms.cda.data.dto.CwmsId; + +public class Location { private final String nearestCity; private final String nationId; private final String boundingOfficeName; @@ -49,9 +51,9 @@ public class LocationType { private final String timeZoneName; private final String countyName; private final String stateInitial; - private final LocationRefType locationRefType; + private final CwmsId locationRef; - private LocationType() { + private Location() { this.nearestCity = null; this.nationId = null; this.boundingOfficeName = null; @@ -74,12 +76,12 @@ private LocationType() { this.timeZoneName = null; this.countyName = null; this.stateInitial = null; - this.locationRefType = null; + this.locationRef = null; } - public LocationType(Builder builder) { - this.locationRefType = builder.locationRefType; + public Location(Builder builder) { + this.locationRef = builder.locationRef; this.stateInitial = builder.stateInitial; this.countyName = builder.countyName; this.timeZoneName = builder.timeZoneName; @@ -192,8 +194,8 @@ public String getStateInitial() { return this.stateInitial; } - public LocationRefType getLocationRefType() { - return this.locationRefType; + public CwmsId getLocationRef() { + return this.locationRef; } public static class Builder { @@ -219,7 +221,7 @@ public static class Builder { private String timeZoneName; private String countyName; private String stateInitial; - private LocationRefType locationRefType; + private CwmsId locationRef; public Builder withNearestCity(String nearestCity) { this.nearestCity = nearestCity; @@ -331,13 +333,13 @@ public Builder withStateInitial(String stateInitial) { return this; } - public Builder withLocationRefType(LocationRefType locationRefType) { - this.locationRefType = locationRefType; + public Builder withLocationRef(CwmsId locationRef) { + this.locationRef = locationRef; return this; } - public LocationType build() { - return new LocationType(this); + public Location build() { + return new Location(this); } } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java deleted file mode 100644 index 3abd428f1..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LocationRefType.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -public class LocationRefType { - private String baseLocationId; - private String officeId; - private String subLocationId; - - private LocationRefType() { - } - - public LocationRefType(String baseLocationId, String subLocationId, String officeId) { - this.baseLocationId = baseLocationId; - this.subLocationId = subLocationId; - this.officeId = officeId; - } - - public String getBaseLocationId() { - return this.baseLocationId; - } - - public String getSubLocationId() { - return this.subLocationId; - } - - public String getOfficeId() { - return this.officeId; - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java index 8036c550c..a1f7d9368 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java @@ -37,15 +37,15 @@ public class WaterSupply implements CwmsDTOBase { private final String contractName; private final Integer contractNumber; private final String waterUser; - private final WaterUserType userType; - private final WaterUserContractType contractType; + private final WaterUser user; + private final WaterUserContract contract; private WaterSupply(Builder builder) { contractName = builder.contractName; contractNumber = builder.contractNumber; waterUser = builder.waterUser; - userType = builder.userType; - contractType = builder.contractType; + user = builder.user; + contract = builder.contract; } public String getContractName() { @@ -60,20 +60,20 @@ public String getWaterUser() { return waterUser; } - public WaterUserType getUserType() { - return userType; + public WaterUser getUser() { + return user; } - public WaterUserContractType getContractType() { - return contractType; + public WaterUserContract getContract() { + return contract; } public static class Builder { private String contractName; private Integer contractNumber; private String waterUser; - private WaterUserType userType; - private WaterUserContractType contractType; + private WaterUser user; + private WaterUserContract contract; public Builder withContractName(String contractName) { this.contractName = contractName; @@ -90,13 +90,13 @@ public Builder withWaterUser(String waterUser) { return this; } - public Builder withUserType(WaterUserType userType) { - this.userType = userType; + public Builder withUser(WaterUser user) { + this.user = user; return this; } - public Builder withContractType(WaterUserContractType contractType) { - this.contractType = contractType; + public Builder withContract(WaterUserContract contract) { + this.contract = contract; return this; } @@ -116,32 +116,31 @@ public void validate() throws FieldException { if (waterUser == null || waterUser.isEmpty()) { throw new FieldException("Water User cannot be null or empty"); } - if (userType == null) { + if (user == null) { throw new FieldException("User Type cannot be null"); } - if(userType.getEntityName() == null) - { + if (user.getEntityName() == null) { throw new FieldException("User Type Entity Name cannot be null"); } - if(userType.getWaterRight() == null) { + if (user.getWaterRight() == null) { throw new FieldException("User Type Water Right cannot be null"); } - if (contractType == null) { + if (contract == null) { throw new FieldException("Contract Type cannot be null"); } - if (contractType.getWaterUserContractRefType() == null) { + if (contract.getWaterUserContractRef() == null) { throw new FieldException("Water User Contract Ref Type cannot be null"); } - if (contractType.getWaterSupplyContractType() == null) { + if (contract.getWaterSupplyContract() == null) { throw new FieldException("Water Supply Contract Type cannot be null"); } - if (contractType.getContractEffectiveDate() == null) { + if (contract.getContractEffectiveDate() == null) { throw new FieldException("Contract Effective Date cannot be null"); } - if (contractType.getInitialUseAllocation() == null) { + if (contract.getInitialUseAllocation() == null) { throw new FieldException("Contract Initial Use Allocation cannot be null"); } - if (contractType.getContractedStorage() == null) { + if (contract.getContractedStorage() == null) { throw new FieldException("Contracted Storage cannot be null"); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java deleted file mode 100644 index effc7dfcf..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractRefType.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -public class WaterUserContractRefType { - private WaterUserType waterUserType; - private String contractName; - - private WaterUserContractRefType() { - } - - public WaterUserContractRefType(WaterUserType waterUserType, String contractName) { - this.waterUserType = waterUserType; - this.contractName = contractName; - } - - public String getContractName() { - return this.contractName; - } - - public WaterUserType getWaterUserType() { - return this.waterUserType; - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java deleted file mode 100644 index d4b6289a2..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserContractType.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.annotations.FormattableWith; -import cwms.cda.formatters.json.JsonV1; -import java.util.Date; - -@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) -@JsonDeserialize(builder = WaterUserContractType.Builder.class) -public class WaterUserContractType { - - private final WaterUserContractRefType waterUserContractRefType; - private final LookupType waterSupplyContractType; - private final Date contractEffectiveDate; - private final Date contractExpirationDate; - private final Double contractedStorage; - private final Double initialUseAllocation; - private final Double futureUseAllocation; - private final String storageUnitsId; - private final Double futureUsePercentActivated; - private final Double totalAllocPercentActivated; - private final LocationType pumpOutLocation; - private final LocationType pumpOutBelowLocation; - private final LocationType pumpInLocation; - - private WaterUserContractType(Builder builder) { - this.waterUserContractRefType = builder.waterUserContractRefType; - this.waterSupplyContractType = builder.waterSupplyContractType; - this.contractEffectiveDate = builder.contractEffectiveDate; - this.contractExpirationDate = builder.contractExpirationDate; - this.contractedStorage = builder.contractedStorage; - this.initialUseAllocation = builder.initialUseAllocation; - this.futureUseAllocation = builder.futureUseAllocation; - this.storageUnitsId = builder.storageUnitsId; - this.futureUsePercentActivated = builder.futureUsePercentActivated; - this.totalAllocPercentActivated = builder.totalAllocPercentActivated; - this.pumpOutLocation = builder.pumpOutLocation; - this.pumpOutBelowLocation = builder.pumpOutBelowLocation; - this.pumpInLocation = builder.pumpInLocation; - } - - public WaterUserContractRefType getWaterUserContractRefType() { - return this.waterUserContractRefType; - } - - public LookupType getWaterSupplyContractType() { - return this.waterSupplyContractType; - } - - public Date getContractEffectiveDate() { - return this.contractEffectiveDate; - } - - public Date getContractExpirationDate() { - return this.contractExpirationDate; - } - - public Double getContractedStorage() { - return this.contractedStorage; - } - - public Double getInitialUseAllocation() { - return this.initialUseAllocation; - } - - public Double getFutureUseAllocation() { - return this.futureUseAllocation; - } - - public String getStorageUnitsId() { - return this.storageUnitsId; - } - - public Double getFutureUsePercentActivated() { - return this.futureUsePercentActivated; - } - - public Double getTotalAllocPercentActivated() { - return this.totalAllocPercentActivated; - } - - public LocationType getPumpOutLocation() { - return this.pumpOutLocation; - } - - public LocationType getPumpOutBelowLocation() { - return this.pumpOutBelowLocation; - } - - public LocationType getPumpInLocation() { - return this.pumpInLocation; - } - - public static class Builder { - private WaterUserContractRefType waterUserContractRefType; - private LookupType waterSupplyContractType; - private Date contractEffectiveDate; - private Date contractExpirationDate; - private Double contractedStorage; - private Double initialUseAllocation; - private Double futureUseAllocation; - private String storageUnitsId; - private Double futureUsePercentActivated; - private Double totalAllocPercentActivated; - private LocationType pumpOutLocation; - private LocationType pumpOutBelowLocation; - private LocationType pumpInLocation; - - public Builder withWaterUserContractRefType(WaterUserContractRefType waterUserContractRefType) { - this.waterUserContractRefType = waterUserContractRefType; - return this; - } - - public Builder withWaterSupplyContractType(LookupType waterSupplyContractType) { - this.waterSupplyContractType = waterSupplyContractType; - return this; - } - - public Builder withContractEffectiveDate(Date contractEffectiveDate) { - this.contractEffectiveDate = contractEffectiveDate; - return this; - } - - public Builder withContractExpirationDate(Date contractExpirationDate) { - this.contractExpirationDate = contractExpirationDate; - return this; - } - - public Builder withContractedStorage(Double contractedStorage) { - this.contractedStorage = contractedStorage; - return this; - } - - public Builder withInitialUseAllocation(Double initialUseAllocation) { - this.initialUseAllocation = initialUseAllocation; - return this; - } - - public Builder withFutureUseAllocation(Double futureUseAllocation) { - this.futureUseAllocation = futureUseAllocation; - return this; - } - - public Builder withStorageUnitsId(String storageUnitsId) { - this.storageUnitsId = storageUnitsId; - return this; - } - - public Builder withFutureUsePercentActivated(Double futureUsePercentActivated) { - this.futureUsePercentActivated = futureUsePercentActivated; - return this; - } - - public Builder withTotalAllocPercentActivated(Double totalAllocPercentActivated) { - this.totalAllocPercentActivated = totalAllocPercentActivated; - return this; - } - - public Builder withPumpOutLocation(LocationType pumpOutLocation) { - this.pumpOutLocation = pumpOutLocation; - return this; - } - - public Builder withPumpOutBelowLocation(LocationType pumpOutBelowLocation) { - this.pumpOutBelowLocation = pumpOutBelowLocation; - return this; - } - - public Builder withPumpInLocation(LocationType pumpInLocation) { - this.pumpInLocation = pumpInLocation; - return this; - } - - public WaterUserContractType build() { - return new WaterUserContractType(this); - } - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java deleted file mode 100644 index 90093fc48..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterUserType.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ - -package cwms.cda.data.dto.watersupply; - -public class WaterUserType { - - private String entityName; - private LocationRefType parentLocationRefType; - private String waterRight; - - private WaterUserType() { - } - - public WaterUserType(String entityName, LocationRefType locationRefType, String waterRight) { - this.entityName = entityName; - this.parentLocationRefType = locationRefType; - this.waterRight = waterRight; - } - - public LocationRefType getParentLocationRefType() { - return this.parentLocationRefType; - } - - public String getEntityName() { - return this.entityName; - } - - public String getWaterRight() { - return this.waterRight; - } -} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java index 27468612b..f1d866dbd 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java @@ -25,7 +25,10 @@ package cwms.cda.data.dto.watersupply; import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.CwmsIdTest; import cwms.cda.formatters.Formats; +import cwms.cda.data.dto.LookupType; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; @@ -37,6 +40,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; class WaterSupplyTest { @@ -66,7 +70,7 @@ void testValidate() { assertAll(() -> { WaterSupply waterSupply = buildTestWaterSupply(); - assertThrows(FieldException.class, waterSupply::validate); + assertDoesNotThrow(waterSupply::validate); }, () -> { WaterSupply waterSupply = new WaterSupply.Builder() .withContractName("Test Contract") @@ -83,17 +87,28 @@ private WaterSupply buildTestWaterSupply () .withContractName("Test Contract") .withContractNumber(1234) .withWaterUser("Test User") - .withUserType(new WaterUserType("Test Entity", - new LocationRefType("Base Location", "Sub location", OFFICE_ID), + .withUser(new WaterUser("Test Entity", + new CwmsId.Builder() + .withName("Base Location") + .withOfficeId(OFFICE_ID) + .build(), "Water Right test")) - .withContractType(new WaterUserContractType.Builder() - .withWaterUserContractRefType(new WaterUserContractRefType(new WaterUserType("Entity Test", - new LocationRefType("Base Location", "Sub Location", OFFICE_ID), + .withContract(new WaterUserContract.Builder() + .withWaterUserContractRef(new WaterUserContractRef(new WaterUser("Entity Test", + new CwmsId.Builder() + .withName("Base Location") + .withOfficeId(OFFICE_ID) + .build(), "Water Right Test"), "Contract Name Test")) - .withWaterSupplyContractType(new LookupType(OFFICE_ID, "Display Value Test", "Example Tooltip", true)) - .withContractEffectiveDate(new Date()) - .withContractExpirationDate(new Date()) + .withWaterSupplyContract(new LookupType.Builder() + .withActive(true) + .withDisplayValue("Display Value Test") + .withOfficeId(OFFICE_ID) + .withTooltip("Example Tooltip") + .build()) + .withContractEffectiveDate(new Date(1719854376)) + .withContractExpirationDate(new Date(1719854376)) .withContractedStorage(1000.0) .withInitialUseAllocation(20.5) .withFutureUseAllocation(79.5) @@ -107,10 +122,13 @@ private WaterSupply buildTestWaterSupply () .build(); } - private LocationType buildLocationType(String pumpLocation) + private Location buildLocationType(String pumpLocation) { - return new LocationType.Builder() - .withLocationRefType( new LocationRefType("Base Location", "Sub location", OFFICE_ID)) + return new Location.Builder() + .withLocationRef( new CwmsId.Builder() + .withName("Base Location") + .withOfficeId(OFFICE_ID) + .build()) .withStateInitial("CA") .withActiveFlag(true) .withBoundingOfficeId(OFFICE_ID) @@ -121,16 +139,16 @@ private LocationType buildLocationType(String pumpLocation) .withHorizontalDatum("WGS84") .withLatitude(0.0) .withLongitude(0.0) - .withLocationKindId("PUMP") - .withLongName(pumpLocation) + .withLocationKindId("Test Locale") + .withTypeOfLocation("PUMP") + .withLongName("Full Location Name") .withMapLabel("Map location") .withNationId("US") .withNearestCity("Davis") .withPublishedLatitude(0.0) .withPublishedLongitude(0.0) .withTimeZoneName("UTC") - .withTypeOfLocation("WGS84") - .withBoundingOfficeName("Sacramento") + .withBoundingOfficeName("Sacramento Office") .withVerticalDatum("WGS84") .withPublicName(pumpLocation) .build(); @@ -143,21 +161,12 @@ private static void assertSame(WaterSupply first, WaterSupply second) () -> assertEquals(first.getContractName(), second.getContractName()), () -> assertEquals(first.getContractNumber(), second.getContractNumber()), () -> assertEquals(first.getWaterUser(), second.getWaterUser()), - () -> assertWaterUserType(first.getUserType(), second.getUserType()), - () -> assertWaterUserContractType(first.getContractType(), second.getContractType()) + () -> assertWaterUserType(first.getUser(), second.getUser()), + () -> assertWaterUserContractType(first.getContract(), second.getContract()) ); } - private static void assertLocationRefType(LocationRefType first, LocationRefType second) - { - assertAll( - () -> assertEquals(first.getBaseLocationId(), second.getBaseLocationId()), - () -> assertEquals(first.getOfficeId(), second.getOfficeId()), - () -> assertEquals(first.getSubLocationId(), second.getSubLocationId()) - ); - } - - private static void assertLocationType(LocationType first, LocationType second) + private static void assertLocationType(Location first, Location second) { assertAll( () -> assertEquals(first.getNearestCity(), second.getNearestCity()), @@ -182,7 +191,7 @@ private static void assertLocationType(LocationType first, LocationType second) () -> assertEquals(first.getTimeZoneName(), second.getTimeZoneName()), () -> assertEquals(first.getCountyName(), second.getCountyName()), () -> assertEquals(first.getStateInitial(), second.getStateInitial()), - () -> assertLocationRefType(first.getLocationRefType(), second.getLocationRefType()) + () -> CwmsIdTest.assertSame(first.getLocationRef(), second.getLocationRef()) ); } @@ -196,20 +205,20 @@ private static void assertLookupType(LookupType first, LookupType second) ); } - private static void assertWaterUserType(WaterUserType first, WaterUserType second) + private static void assertWaterUserType(WaterUser first, WaterUser second) { assertAll( () -> assertEquals(first.getEntityName(), second.getEntityName()), - () -> assertLocationRefType(first.getParentLocationRefType(), second.getParentLocationRefType()), + () -> CwmsIdTest.assertSame(first.getParentLocationRef(), second.getParentLocationRef()), () -> assertEquals(first.getWaterRight(), second.getWaterRight()) ); } - private static void assertWaterUserContractType(WaterUserContractType first, WaterUserContractType second) + private static void assertWaterUserContractType(WaterUserContract first, WaterUserContract second) { assertAll( - () -> assertWaterUserContractRefType(first.getWaterUserContractRefType(), second.getWaterUserContractRefType()), - () -> assertLookupType(first.getWaterSupplyContractType(), second.getWaterSupplyContractType()), + () -> assertWaterUserContractRefType(first.getWaterUserContractRef(), second.getWaterUserContractRef()), + () -> assertLookupType(first.getWaterSupplyContract(), second.getWaterSupplyContract()), () -> assertEquals(first.getContractEffectiveDate(), second.getContractEffectiveDate()), () -> assertEquals(first.getContractExpirationDate(), second.getContractExpirationDate()), () -> assertEquals(first.getContractedStorage(), second.getContractedStorage()), @@ -224,11 +233,11 @@ private static void assertWaterUserContractType(WaterUserContractType first, Wat ); } - private static void assertWaterUserContractRefType(WaterUserContractRefType first, WaterUserContractRefType second) + private static void assertWaterUserContractRefType(WaterUserContractRef first, WaterUserContractRef second) { assertAll( () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertWaterUserType(first.getWaterUserType(), second.getWaterUserType()) + () -> assertWaterUserType(first.getWaterUser(), second.getWaterUser()) ); } } diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json index 2fb8cafce..322c89667 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json @@ -2,36 +2,34 @@ "contract-name": "Test Contract", "contract-number": 1234, "water-user": "Test User", - "user-type": { + "user": { "entity-name": "Test Entity", - "parent-location-ref-type": { - "base-location-id": "Base Location", - "office-id": "SPK", - "sub-location-id": "Sub location" + "parent-location-ref": { + "name": "Base Location", + "office-id": "SPK" }, "water-right": "Water Right test" }, - "contract-type": { - "water-user-contract-ref-type": { - "water-user-type": { + "contract": { + "water-user-contract-ref": { + "water-user": { "entity-name": "Entity Test", - "parent-location-ref-type": { - "base-location-id": "Base Location", - "office-id": "SPK", - "sub-location-id": "Sub Location" + "parent-location-ref": { + "name": "Base Location", + "office-id": "SPK" }, "water-right": "Water Right Test" }, "contract-name": "Contract Name Test" }, - "water-supply-contract-type": { + "water-supply-contract": { "active": true, "office-id": "SPK", "tooltip": "Example Tooltip", "display-value": "Display Value Test" }, - "contract-effective-date": 1719854376876, - "contract-expiration-date": 1719854376876, + "contract-effective-date": 1719854376, + "contract-expiration-date": 1719854376, "contracted-storage": 1000, "initial-use-allocation": 20.5, "future-use-allocation": 79.5, @@ -61,10 +59,9 @@ "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref-type": { - "base-location-id": "Base Location", - "office-id": "SPK", - "sub-location-id": "Sub location" + "location-ref": { + "name": "Base Location", + "office-id": "SPK" } }, "pump-out-below-location": { @@ -90,10 +87,9 @@ "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref-type": { - "base-location-id": "Base Location", - "office-id": "SPK", - "sub-location-id": "Sub location" + "location-ref": { + "name": "Base Location", + "office-id": "SPK" } }, "pump-in-location": { @@ -119,10 +115,9 @@ "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref-type": { - "base-location-id": "Base Location", - "office-id": "SPK", - "sub-location-id": "Sub location" + "location-ref": { + "name": "Base Location", + "office-id": "SPK" } } } From ed7290ff4bbb6bc753d3f90c33e3d771b0511417 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 2 Jul 2024 11:31:15 -0700 Subject: [PATCH 09/39] Removed duplicate location class --- .../cda/data/dto/watersupply/Location.java | 345 ------------------ .../data/dto/watersupply/WaterSupplyTest.java | 38 +- .../cda/data/dto/watersupply/watersupply.json | 52 ++- 3 files changed, 40 insertions(+), 395 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java deleted file mode 100644 index 533d9ef8d..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/Location.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import cwms.cda.data.dto.CwmsId; - -public class Location { - private final String nearestCity; - private final String nationId; - private final String boundingOfficeName; - private final String boundingOfficeId; - private final Double publishedLongitude; - private final Double publishedLatitude; - private final String mapLabel; - private final String locationKindId; - private final boolean activeFlag; - private final String description; - private final String longName; - private final String publicName; - private final String verticalDatum; - private final String elevUnitId; - private final Double elevation; - private final String horizontalDatum; - private final Double longitude; - private final Double latitude; - private final String typeOfLocation; - private final String timeZoneName; - private final String countyName; - private final String stateInitial; - private final CwmsId locationRef; - - private Location() { - this.nearestCity = null; - this.nationId = null; - this.boundingOfficeName = null; - this.boundingOfficeId = null; - this.publishedLongitude = null; - this.publishedLatitude = null; - this.mapLabel = null; - this.locationKindId = null; - this.activeFlag = false; - this.description = null; - this.longName = null; - this.publicName = null; - this.verticalDatum = null; - this.elevUnitId = null; - this.elevation = null; - this.horizontalDatum = null; - this.longitude = null; - this.latitude = null; - this.typeOfLocation = null; - this.timeZoneName = null; - this.countyName = null; - this.stateInitial = null; - this.locationRef = null; - } - - - public Location(Builder builder) { - this.locationRef = builder.locationRef; - this.stateInitial = builder.stateInitial; - this.countyName = builder.countyName; - this.timeZoneName = builder.timeZoneName; - this.typeOfLocation = builder.typeOfLocation; - this.latitude = builder.latitude; - this.longitude = builder.longitude; - this.horizontalDatum = builder.horizontalDatum; - this.elevation = builder.elevation; - this.elevUnitId = builder.elevUnitId; - this.verticalDatum = builder.verticalDatum; - this.publicName = builder.publicName; - this.longName = builder.longName; - this.description = builder.description; - this.activeFlag = builder.activeFlag; - this.locationKindId = builder.locationKindId; - this.mapLabel = builder.mapLabel; - this.publishedLatitude = builder.publishedLatitude; - this.publishedLongitude = builder.publishedLongitude; - this.boundingOfficeId = builder.boundingOfficeId; - this.boundingOfficeName = builder.boundingOfficeName; - this.nationId = builder.nationId; - this.nearestCity = builder.nearestCity; - } - - public String getNearestCity() { - return this.nearestCity; - } - - public String getNationId() { - return this.nationId; - } - - public String getBoundingOfficeName() { - return this.boundingOfficeName; - } - - public String getBoundingOfficeId() { - return this.boundingOfficeId; - } - - public Double getPublishedLongitude() { - return this.publishedLongitude; - } - - public Double getPublishedLatitude() { - return this.publishedLatitude; - } - - public String getMapLabel() { - return this.mapLabel; - } - - public String getLocationKindId() { - return this.locationKindId; - } - - public boolean getActiveFlag() { - return this.activeFlag; - } - - public String getDescription() { - return this.description; - } - - public String getLongName() { - return this.longName; - } - - public String getPublicName() { - return this.publicName; - } - - public String getVerticalDatum() { - return this.verticalDatum; - } - - public String getElevUnitId() { - return this.elevUnitId; - } - - public Double getElevation() { - return this.elevation; - } - - public String getHorizontalDatum() { - return this.horizontalDatum; - } - - public Double getLongitude() { - return this.longitude; - } - - public Double getLatitude() { - return this.latitude; - } - - public String getTypeOfLocation() { - return this.typeOfLocation; - } - - public String getTimeZoneName() { - return this.timeZoneName; - } - - public String getCountyName() { - return this.countyName; - } - - public String getStateInitial() { - return this.stateInitial; - } - - public CwmsId getLocationRef() { - return this.locationRef; - } - - public static class Builder { - private String nearestCity; - private String nationId; - private String boundingOfficeName; - private String boundingOfficeId; - private Double publishedLongitude; - private Double publishedLatitude; - private String mapLabel; - private String locationKindId; - private boolean activeFlag; - private String description; - private String longName; - private String publicName; - private String verticalDatum; - private String elevUnitId; - private Double elevation; - private String horizontalDatum; - private Double longitude; - private Double latitude; - private String typeOfLocation; - private String timeZoneName; - private String countyName; - private String stateInitial; - private CwmsId locationRef; - - public Builder withNearestCity(String nearestCity) { - this.nearestCity = nearestCity; - return this; - } - - public Builder withNationId(String nationId) { - this.nationId = nationId; - return this; - } - - public Builder withBoundingOfficeName(String boundingOfficeName) { - this.boundingOfficeName = boundingOfficeName; - return this; - } - - public Builder withBoundingOfficeId(String boundingOfficeId) { - this.boundingOfficeId = boundingOfficeId; - return this; - } - - public Builder withPublishedLongitude(Double publishedLongitude) { - this.publishedLongitude = publishedLongitude; - return this; - } - - public Builder withPublishedLatitude(Double publishedLatitude) { - this.publishedLatitude = publishedLatitude; - return this; - } - - public Builder withMapLabel(String mapLabel) { - this.mapLabel = mapLabel; - return this; - } - - public Builder withLocationKindId(String locationKindId) { - this.locationKindId = locationKindId; - return this; - } - - public Builder withActiveFlag(boolean activeFlag) { - this.activeFlag = activeFlag; - return this; - } - - public Builder withDescription(String description) { - this.description = description; - return this; - } - - public Builder withLongName(String longName) { - this.longName = longName; - return this; - } - - public Builder withPublicName(String publicName) { - this.publicName = publicName; - return this; - } - - public Builder withVerticalDatum(String verticalDatum) { - this.verticalDatum = verticalDatum; - return this; - } - - public Builder withElevUnitId(String elevUnitId) { - this.elevUnitId = elevUnitId; - return this; - } - - public Builder withElevation(Double elevation) { - this.elevation = elevation; - return this; - } - - public Builder withHorizontalDatum(String horizontalDatum) { - this.horizontalDatum = horizontalDatum; - return this; - } - - public Builder withLongitude(Double longitude) { - this.longitude = longitude; - return this; - } - - public Builder withLatitude(Double latitude) { - this.latitude = latitude; - return this; - } - - public Builder withTypeOfLocation(String typeOfLocation) { - this.typeOfLocation = typeOfLocation; - return this; - } - - public Builder withTimeZoneName(String timeZoneName) { - this.timeZoneName = timeZoneName; - return this; - } - - public Builder withCountyName(String countyName) { - this.countyName = countyName; - return this; - } - - public Builder withStateInitial(String stateInitial) { - this.stateInitial = stateInitial; - return this; - } - - public Builder withLocationRef(CwmsId locationRef) { - this.locationRef = locationRef; - return this; - } - - public Location build() { - return new Location(this); - } - } -} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java index f1d866dbd..af85fb9da 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java @@ -24,16 +24,19 @@ package cwms.cda.data.dto.watersupply; +import cwms.cda.api.enums.Nation; import cwms.cda.api.errors.FieldException; import cwms.cda.data.dto.CwmsId; import cwms.cda.data.dto.CwmsIdTest; import cwms.cda.formatters.Formats; import cwms.cda.data.dto.LookupType; +import cwms.cda.data.dto.Location; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.time.ZoneId; import java.util.Date; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -124,33 +127,29 @@ private WaterSupply buildTestWaterSupply () private Location buildLocationType(String pumpLocation) { - return new Location.Builder() - .withLocationRef( new CwmsId.Builder() - .withName("Base Location") - .withOfficeId(OFFICE_ID) - .build()) + return new Location.Builder(OFFICE_ID, pumpLocation) .withStateInitial("CA") - .withActiveFlag(true) .withBoundingOfficeId(OFFICE_ID) .withDescription("Place for testing") .withElevation(120.0) .withCountyName("Sacramento") - .withElevUnitId("m") .withHorizontalDatum("WGS84") .withLatitude(0.0) .withLongitude(0.0) - .withLocationKindId("Test Locale") - .withTypeOfLocation("PUMP") .withLongName("Full Location Name") .withMapLabel("Map location") - .withNationId("US") .withNearestCity("Davis") .withPublishedLatitude(0.0) .withPublishedLongitude(0.0) - .withTimeZoneName("UTC") - .withBoundingOfficeName("Sacramento Office") + .withTimeZoneName(ZoneId.of("UTC")) .withVerticalDatum("WGS84") .withPublicName(pumpLocation) + .withLocationType("PUMP") + .withActive(true) + .withNation(Nation.US) + .withBoundingOfficeId(OFFICE_ID) + .withElevationUnits("m") + .withLocationKind("PUMP") .build(); } @@ -170,28 +169,27 @@ private static void assertLocationType(Location first, Location second) { assertAll( () -> assertEquals(first.getNearestCity(), second.getNearestCity()), - () -> assertEquals(first.getNationId(), second.getNationId()), - () -> assertEquals(first.getBoundingOfficeName(), second.getBoundingOfficeName()), + () -> assertEquals(first.getNation(), second.getNation()), () -> assertEquals(first.getBoundingOfficeId(), second.getBoundingOfficeId()), () -> assertEquals(first.getPublishedLongitude(), second.getPublishedLongitude()), () -> assertEquals(first.getPublishedLatitude(), second.getPublishedLatitude()), () -> assertEquals(first.getMapLabel(), second.getMapLabel()), - () -> assertEquals(first.getLocationKindId(), second.getLocationKindId()), - () -> assertEquals(first.getActiveFlag(), second.getActiveFlag()), + () -> assertEquals(first.getLocationKind(), second.getLocationKind()), + () -> assertEquals(first.getActive(), second.getActive()), () -> assertEquals(first.getDescription(), second.getDescription()), () -> assertEquals(first.getLongName(), second.getLongName()), () -> assertEquals(first.getPublicName(), second.getPublicName()), () -> assertEquals(first.getVerticalDatum(), second.getVerticalDatum()), - () -> assertEquals(first.getElevUnitId(), second.getElevUnitId()), + () -> assertEquals(first.getElevationUnits(), second.getElevationUnits()), () -> assertEquals(first.getElevation(), second.getElevation()), () -> assertEquals(first.getHorizontalDatum(), second.getHorizontalDatum()), () -> assertEquals(first.getLongitude(), second.getLongitude()), () -> assertEquals(first.getLatitude(), second.getLatitude()), - () -> assertEquals(first.getTypeOfLocation(), second.getTypeOfLocation()), - () -> assertEquals(first.getTimeZoneName(), second.getTimeZoneName()), + () -> assertEquals(first.getLocationType(), second.getLocationType()), + () -> assertEquals(first.getTimezoneName(), second.getTimezoneName()), () -> assertEquals(first.getCountyName(), second.getCountyName()), () -> assertEquals(first.getStateInitial(), second.getStateInitial()), - () -> CwmsIdTest.assertSame(first.getLocationRef(), second.getLocationRef()) + () -> assertEquals(first.getName(), second.getName()) ); } diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json index 322c89667..1244e0401 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json @@ -38,87 +38,79 @@ "total-alloc-percent-activated": 15.2, "pump-out-location": { "nearest-city": "Davis", - "nation-id": "US", - "bounding-office-name": "Sacramento Office", + "nation": "US", "bounding-office-id": "SPK", "published-longitude": 0, "published-latitude": 0, "map-label": "Map location", - "location-kind-id": "Test Locale", - "active-flag": true, + "location-kind": "PUMP", + "active": true, "description": "Place for testing", "long-name": "Full Location Name", "public-name": "Pump Out Location", "vertical-datum": "WGS84", - "elev-unit-id": "m", + "elevation-units": "m", "elevation": 120, "horizontal-datum": "WGS84", "longitude": 0, "latitude": 0, - "type-of-location": "PUMP", + "location-type": "PUMP", "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref": { - "name": "Base Location", - "office-id": "SPK" - } + "name": "Pump Out Location", + "office-id": "SPK" }, "pump-out-below-location": { "nearest-city": "Davis", - "nation-id": "US", - "bounding-office-name": "Sacramento Office", + "nation": "US", "bounding-office-id": "SPK", "published-longitude": 0, "published-latitude": 0, "map-label": "Map location", - "location-kind-id": "Test Locale", - "active-flag": true, + "location-kind": "PUMP", + "active": true, "description": "Place for testing", "long-name": "Full Location Name", "public-name": "Pump Out Below Location", "vertical-datum": "WGS84", - "elev-unit-id": "m", + "elevation-units": "m", "elevation": 120, "horizontal-datum": "WGS84", "longitude": 0, "latitude": 0, - "type-of-location": "PUMP", + "location-type": "PUMP", "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref": { - "name": "Base Location", - "office-id": "SPK" - } + "name": "Pump Out Below Location", + "office-id": "SPK" }, "pump-in-location": { "nearest-city": "Davis", - "nation-id": "US", - "bounding-office-name": "Sacramento Office", + "nation": "US", "bounding-office-id": "SPK", "published-longitude": 0, "published-latitude": 0, "map-label": "Map location", - "location-kind-id": "Test Locale", - "active-flag": true, + "location-kind": "PUMP", + "active": true, "description": "Place for testing", "long-name": "Full Location Name", "public-name": "Pump In Location", "vertical-datum": "WGS84", - "elev-unit-id": "m", + "elevation-units": "m", "elevation": 120, "horizontal-datum": "WGS84", "longitude": 0, "latitude": 0, - "type-of-location": "PUMP", + "location-type": "PUMP", "time-zone-name": "UTC", "county-name": "Sacramento", "state-initial": "CA", - "location-ref": { - "name": "Base Location", - "office-id": "SPK" - } + "name": "Pump In Location", + "office-id": "SPK" + } } } \ No newline at end of file From 92ea19fa8519f3709bd6dd8fcef0be87d6e5d242 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Tue, 2 Jul 2024 11:32:23 -0700 Subject: [PATCH 10/39] Delete LookupType.java --- .../cda/data/dto/watersupply/LookupType.java | 60 ------------------- 1 file changed, 60 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java deleted file mode 100644 index 39f8bf572..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/LookupType.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -public class LookupType { - private boolean active; - private String officeId; - private String tooltip; - private String displayValue; - - public LookupType() { - } - - public LookupType(String officeId, String displayValue, String tooltip, boolean active) { - this.officeId = officeId; - this.displayValue = displayValue; - this.tooltip = tooltip; - this.active = active; - } - - public String getOfficeId() { - return this.officeId; - } - - public String getDisplayValue() { - return this.displayValue; - } - - public String getTooltip() { - return this.tooltip; - } - - public boolean getActive() { - return this.active; - } -} From 26e395f0bc6cc2e4488968f9b4dd484a6d66ae75 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 1 Jul 2024 16:56:51 -0700 Subject: [PATCH 11/39] First draft of Water Supply DAO --- .../data/dao/watersupply/WaterSupplyDao.java | 328 ++++++++++++++++++ 1 file changed, 328 insertions(+) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java new file mode 100644 index 000000000..567458d96 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java @@ -0,0 +1,328 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dao.watersupply; + +import cwms.cda.data.dao.JooqDao; +import cwms.cda.data.dto.watersupply.LocationRefType; +import cwms.cda.data.dto.watersupply.LocationType; +import cwms.cda.data.dto.watersupply.LookupType; +import cwms.cda.data.dto.watersupply.WaterSupply; +import cwms.cda.data.dto.watersupply.WaterUserContractRefType; +import cwms.cda.data.dto.watersupply.WaterUserContractType; +import cwms.cda.data.dto.watersupply.WaterUserType; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.jooq.DSLContext; +import usace.cwms.db.jooq.dao.CwmsDbWaterSupplyJooq; + +public class WaterSupplyDao extends JooqDao { + public WaterSupplyDao(DSLContext dsl) { + super(dsl); + } + + // TO DO: Get water contract number + public List getAllWaterContracts(LocationRefType projectLocation, String entityName) + throws SQLException { + List retVal = new ArrayList<>(); + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + List waterUserContractTypes = new ArrayList<>(); + + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + + try { + connection(dsl, c -> waterUserContractTypes.addAll(waterSupplyJooq.retrieveContracts(c, locationRefType, + entityName))); + } catch (Exception ex) { + throw new SQLException(ex); + } + + for (usace.cwms.db.dao.ifc.watersupply.WaterUserContractType waterUserContractType : waterUserContractTypes) { + WaterSupply waterSupply = new WaterSupply.Builder() + .withContractName(waterUserContractType.getWaterUserContractRefType().getContractName()) + .withWaterUser(waterUserContractType.getWaterUserContractRefType() + .getWaterUserType().getEntityName()) + .withUserType(map(waterUserContractType.getWaterUserContractRefType().getWaterUserType(), + projectLocation)) + .withContractType(map(waterUserContractType, projectLocation)) + .build(); + retVal.add(waterSupply); + } + + return retVal; + } + + public List getAllWaterContractTypes(String officeId) throws SQLException { + List retVal = new ArrayList<>(); + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + try { + connection(dsl, c -> { + List contractTypeList = + waterSupplyJooq.getContractTypes(c, officeId); + for (usace.cwms.db.dao.ifc.cat.LookupType lookupType : contractTypeList) { + LookupType waterUserContractType = map(lookupType); + retVal.add(waterUserContractType); + } + }); + } catch (Exception ex) { + throw new SQLException(ex); + } + return retVal; + } + + public List getAllWaterUsers(LocationRefType projectLocation) throws SQLException { + List retVal = new ArrayList<>(); + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + + try { + connection(dsl, c -> { + List waterUserTypes = + waterSupplyJooq.retrieveWaterUsers(c, locationRefType); + for (usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUserType : waterUserTypes) { + WaterUserType waterUser = map(waterUserType, projectLocation); + retVal.add(waterUser); + } + }); + } catch (Exception ex) { + throw new SQLException(ex); + } + return retVal; + } + + public WaterUserType getWaterUser(LocationRefType projectLocation, String entityName) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + List userList = new ArrayList<>(); + + connection(dsl, c -> userList.addAll(waterSupplyJooq.retrieveWaterUsers(c, map(projectLocation)))); + + for (usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUser : userList) { + if (waterUser.getEntityName().equals(entityName)) { + return map(waterUser, projectLocation); + } + } + return null; + } + + public void storeWaterContract(WaterUserContractType waterContractType, boolean failIfExists, boolean ignoreNulls) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + List waterUserContractTypeModified = new ArrayList<>(); + waterUserContractTypeModified.add(map(waterContractType, waterContractType.getWaterUserContractRefType(), + waterContractType.getWaterUserContractRefType().getWaterUserType().getParentLocationRefType())); + connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, + failIfExists, ignoreNulls)); + } + + public void renameWaterUser(String oldWaterUser, String newWaterUser, LocationRefType projectLocation) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + + connection(dsl, c -> waterSupplyJooq.renameWaterUser(c, locationRefType, oldWaterUser, newWaterUser)); + } + + public void storeWaterUser(WaterUserType waterUserType) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(waterUserType.getParentLocationRefType()); + + List waterUserTypeModified = new ArrayList<>(); + waterUserTypeModified.add(new usace.cwms.db.dao.ifc.watersupply.WaterUserType(waterUserType.getEntityName(), + locationRefType, waterUserType.getWaterRight())); + + connection(dsl, c -> waterSupplyJooq.storeWaterUsers(c, waterUserTypeModified, true)); + } + + public void renameWaterContract(WaterUserContractRefType waterContractRefType, String oldContractName, + String newContractName) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType waterUserContractRefType = + map(waterContractRefType, waterContractRefType.getWaterUserType().getParentLocationRefType()); + + connection(dsl, c -> waterSupplyJooq.renameContract(c, waterUserContractRefType, + oldContractName, newContractName)); + } + + public void deleteWaterUser(LocationRefType location, String entityName, String deleteAction) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(location); + + connection(dsl, c -> waterSupplyJooq.deleteWaterUser(c, locationRefType, entityName, deleteAction)); + } + + public void deleteWaterContract(WaterUserContractRefType waterUserContractRefType, String deleteAction) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType waterUserContractRefTypeModified = + map(waterUserContractRefType, waterUserContractRefType.getWaterUserType().getParentLocationRefType()); + + connection(dsl, c -> waterSupplyJooq.deleteContract(c, waterUserContractRefTypeModified, deleteAction)); + } + + public void storeWaterContractTypes(WaterUserContractType waterUserContractType, boolean failIfExists) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + List waterUserContractTypeModified = new ArrayList<>(); + waterUserContractTypeModified.add(map(waterUserContractType, + waterUserContractType.getWaterUserContractRefType(), + waterUserContractType.getWaterUserContractRefType().getWaterUserType().getParentLocationRefType())); + connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, failIfExists)); + } + + public void removePumpFromContract(WaterUserContractRefType waterUserContractRefType, String pumpLocId, + String usageId, boolean deleteAccounting) { + CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); + + usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType contractRefType = + map(waterUserContractRefType, waterUserContractRefType.getWaterUserType().getParentLocationRefType()); + connection(dsl, c -> waterSupplyJooq.disassociatePump(c, contractRefType, pumpLocId, + usageId, deleteAccounting)); + } + + private WaterUserType map(usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUserType, + LocationRefType projectLocation) { + return new WaterUserType(waterUserType.getEntityName(), + projectLocation, waterUserType.getWaterRight()); + } + + private usace.cwms.db.dao.ifc.watersupply.WaterUserType map(WaterUserType waterUserType, + LocationRefType projectLocation) { + return new usace.cwms.db.dao.ifc.watersupply.WaterUserType(waterUserType.getEntityName(), + map(projectLocation), waterUserType.getWaterRight()); + } + + private LookupType map(usace.cwms.db.dao.ifc.cat.LookupType lookupType) { + return new LookupType(lookupType.getOfficeId(), + lookupType.getDisplayValue(), lookupType.getTooltip(), lookupType.getActive()); + } + + private usace.cwms.db.dao.ifc.cat.LookupType map(LookupType lookupType) { + return new usace.cwms.db.dao.ifc.cat.LookupType(lookupType.getOfficeId(), + lookupType.getDisplayValue(), lookupType.getTooltip(), lookupType.getActive()); + } + + private usace.cwms.db.dao.ifc.loc.LocationRefType map(LocationRefType projectLocation) { + return new usace.cwms.db.dao.ifc.loc.LocationRefType(projectLocation.getBaseLocationId(), + projectLocation.getSubLocationId(), projectLocation.getOfficeId()); + } + + private LocationRefType map(usace.cwms.db.dao.ifc.loc.LocationRefType projectLocation) { + return new LocationRefType(projectLocation.getBaseLocationId(), projectLocation.getSubLocationId(), + projectLocation.getOfficeId()); + } + + private usace.cwms.db.dao.ifc.loc.LocationType map(LocationType locationType) { + return new usace.cwms.db.dao.ifc.loc.LocationType(map(locationType.getLocationRefType()), + locationType.getStateInitial(), locationType.getCountyName(), + locationType.getTimeZoneName(), locationType.getTypeOfLocation(), + locationType.getLatitude(), locationType.getLongitude(), + locationType.getHorizontalDatum(), locationType.getElevation(), + locationType.getElevUnitId(), locationType.getVerticalDatum(), + locationType.getPublicName(), locationType.getLongName(), + locationType.getDescription(), locationType.getActiveFlag(), + locationType.getLocationKindId(), locationType.getMapLabel(), + locationType.getPublishedLatitude(), locationType.getPublishedLongitude(), + locationType.getBoundingOfficeId(), locationType.getBoundingOfficeName(), + locationType.getNationId(), locationType.getNearestCity()); + } + + private LocationType map(usace.cwms.db.dao.ifc.loc.LocationType locationType) { + return new LocationType.Builder() + .withBoundingOfficeName(locationType.getBoundingOfficeName()) + .withCountyName(locationType.getCountyName()) + .withDescription(locationType.getDescription()) + .withBoundingOfficeId(locationType.getBoundingOfficeId()) + .withActiveFlag(locationType.getActiveFlag()) + .withStateInitial(locationType.getStateInitial()) + .withElevUnitId(locationType.getElevUnitId()) + .withLatitude(locationType.getLatitude()) + .withHorizontalDatum(locationType.getHorizontalDatum()) + .withLocationKindId(locationType.getLocationKindId()) + .withMapLabel(locationType.getMapLabel()) + .withLongitude(locationType.getLongitude()) + .withLongName(locationType.getLongName()) + .withPublishedLatitude(locationType.getPublishedLatitude()) + .withPublishedLongitude(locationType.getPublishedLongitude()) + .withPublicName(locationType.getPublicName()) + .withElevation(locationType.getElevation()) + .withNearestCity(locationType.getNearestCity()) + .withNationId(locationType.getNationId()) + .withVerticalDatum(locationType.getVerticalDatum()) + .withTimeZoneName(locationType.getTimeZoneName()) + .withTypeOfLocation(locationType.getLocationType()) + .withLocationRefType(map(locationType.getLocationRef())) + .build(); + } + + private usace.cwms.db.dao.ifc.watersupply.WaterUserContractType map(WaterUserContractType contract, + WaterUserContractRefType waterUserContractRefType, LocationRefType projectLocation) { + return new usace.cwms.db.dao.ifc.watersupply.WaterUserContractType(map(waterUserContractRefType, + projectLocation), + map(contract.getWaterSupplyContractType()), contract.getContractEffectiveDate(), + contract.getContractExpirationDate(), contract.getContractedStorage(), + contract.getInitialUseAllocation(), contract.getFutureUseAllocation(), + contract.getStorageUnitsId(), contract.getFutureUsePercentActivated(), + contract.getTotalAllocPercentActivated(), map(contract.getPumpOutLocation()), + map(contract.getPumpOutBelowLocation()), map(contract.getPumpInLocation())); + } + + private WaterUserContractType map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractType contract, + LocationRefType projectLocation) { + return new WaterUserContractType.Builder() + .withWaterSupplyContractType(map(contract.getWaterSupplyContractType())) + .withWaterUserContractRefType(map(contract.getWaterUserContractRefType(), projectLocation)) + .withContractEffectiveDate(contract.getContractEffectiveDate()) + .withContractExpirationDate(contract.getContractExpirationDate()) + .withContractedStorage(contract.getContractedStorage()) + .withInitialUseAllocation(contract.getInitialUseAllocation()) + .withFutureUseAllocation(contract.getFutureUseAllocation()) + .withStorageUnitsId(contract.getStorageUnitsId()) + .withFutureUsePercentActivated(contract.getFutureUsePercentActivated()) + .withTotalAllocPercentActivated(contract.getTotalAllocPercentActivated()) + .withPumpOutLocation(map(contract.getPumpOutLocation())) + .withPumpOutBelowLocation(map(contract.getPumpOutBelowLocation())) + .withPumpInLocation(map(contract.getPumpInLocation())) + .build(); + } + + private usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType map(WaterUserContractRefType contract, + LocationRefType projectLocation) { + return new usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType(map(contract.getWaterUserType(), + projectLocation), contract.getContractName()); + } + + private WaterUserContractRefType map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType contract, + LocationRefType projectLocation) { + return new WaterUserContractRefType(map(contract.getWaterUserType(), projectLocation), + contract.getContractName()); + } +} From 52ab24834c2d2cd6608a7499869ef2352b18e2c7 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 2 Jul 2024 13:33:32 -0700 Subject: [PATCH 12/39] Updated Dao to reflect class renames and removals --- .../data/dao/watersupply/WaterSupplyDao.java | 230 +++++++++--------- 1 file changed, 116 insertions(+), 114 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java index 567458d96..dfdad0b06 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java @@ -26,18 +26,25 @@ package cwms.cda.data.dao.watersupply; +import cwms.cda.api.enums.Nation; import cwms.cda.data.dao.JooqDao; -import cwms.cda.data.dto.watersupply.LocationRefType; -import cwms.cda.data.dto.watersupply.LocationType; -import cwms.cda.data.dto.watersupply.LookupType; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.LookupType; import cwms.cda.data.dto.watersupply.WaterSupply; -import cwms.cda.data.dto.watersupply.WaterUserContractRefType; -import cwms.cda.data.dto.watersupply.WaterUserContractType; -import cwms.cda.data.dto.watersupply.WaterUserType; +import cwms.cda.data.dto.watersupply.WaterUser; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.data.dto.watersupply.WaterUserContractRef; import java.sql.SQLException; +import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import org.jooq.DSLContext; +import usace.cwms.db.dao.ifc.loc.LocationRefType; +import usace.cwms.db.dao.ifc.loc.LocationType; +import usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType; +import usace.cwms.db.dao.ifc.watersupply.WaterUserContractType; +import usace.cwms.db.dao.ifc.watersupply.WaterUserType; import usace.cwms.db.jooq.dao.CwmsDbWaterSupplyJooq; public class WaterSupplyDao extends JooqDao { @@ -46,13 +53,13 @@ public WaterSupplyDao(DSLContext dsl) { } // TO DO: Get water contract number - public List getAllWaterContracts(LocationRefType projectLocation, String entityName) + public List getAllWaterContracts(CwmsId projectLocation, String entityName) throws SQLException { List retVal = new ArrayList<>(); CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - List waterUserContractTypes = new ArrayList<>(); + List waterUserContractTypes = new ArrayList<>(); - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + LocationRefType locationRefType = map(projectLocation); try { connection(dsl, c -> waterUserContractTypes.addAll(waterSupplyJooq.retrieveContracts(c, locationRefType, @@ -61,14 +68,14 @@ public List getAllWaterContracts(LocationRefType projectLocation, S throw new SQLException(ex); } - for (usace.cwms.db.dao.ifc.watersupply.WaterUserContractType waterUserContractType : waterUserContractTypes) { + for (WaterUserContractType waterUserContractType : waterUserContractTypes) { WaterSupply waterSupply = new WaterSupply.Builder() .withContractName(waterUserContractType.getWaterUserContractRefType().getContractName()) .withWaterUser(waterUserContractType.getWaterUserContractRefType() .getWaterUserType().getEntityName()) - .withUserType(map(waterUserContractType.getWaterUserContractRefType().getWaterUserType(), + .withUser(map(waterUserContractType.getWaterUserContractRefType().getWaterUserType(), projectLocation)) - .withContractType(map(waterUserContractType, projectLocation)) + .withContract(map(waterUserContractType, projectLocation)) .build(); retVal.add(waterSupply); } @@ -94,18 +101,18 @@ public List getAllWaterContractTypes(String officeId) throws SQLExce return retVal; } - public List getAllWaterUsers(LocationRefType projectLocation) throws SQLException { - List retVal = new ArrayList<>(); + public List getAllWaterUsers(CwmsId projectLocation) throws SQLException { + List retVal = new ArrayList<>(); CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + LocationRefType locationRefType = map(projectLocation); try { connection(dsl, c -> { - List waterUserTypes = + List waterUserTypes = waterSupplyJooq.retrieveWaterUsers(c, locationRefType); - for (usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUserType : waterUserTypes) { - WaterUserType waterUser = map(waterUserType, projectLocation); + for (WaterUserType waterUserType : waterUserTypes) { + WaterUser waterUser = map(waterUserType, projectLocation); retVal.add(waterUser); } }); @@ -115,14 +122,14 @@ public List getAllWaterUsers(LocationRefType projectLocation) thr return retVal; } - public WaterUserType getWaterUser(LocationRefType projectLocation, String entityName) { + public WaterUser getWaterUser(CwmsId projectLocation, String entityName) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - List userList = new ArrayList<>(); + List userList = new ArrayList<>(); connection(dsl, c -> userList.addAll(waterSupplyJooq.retrieveWaterUsers(c, map(projectLocation)))); - for (usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUser : userList) { + for (WaterUserType waterUser : userList) { if (waterUser.getEntityName().equals(entityName)) { return map(waterUser, projectLocation); } @@ -130,99 +137,103 @@ public WaterUserType getWaterUser(LocationRefType projectLocation, String entity return null; } - public void storeWaterContract(WaterUserContractType waterContractType, boolean failIfExists, boolean ignoreNulls) { + public void storeWaterContract(WaterUserContract waterContractType, boolean failIfExists, boolean ignoreNulls) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - List waterUserContractTypeModified = new ArrayList<>(); - waterUserContractTypeModified.add(map(waterContractType, waterContractType.getWaterUserContractRefType(), - waterContractType.getWaterUserContractRefType().getWaterUserType().getParentLocationRefType())); + List waterUserContractTypeModified = new ArrayList<>(); + waterUserContractTypeModified.add(map(waterContractType, waterContractType.getWaterUserContractRef(), + waterContractType.getWaterUserContractRef().getWaterUser().getParentLocationRef())); connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, failIfExists, ignoreNulls)); } - public void renameWaterUser(String oldWaterUser, String newWaterUser, LocationRefType projectLocation) { + public void renameWaterUser(String oldWaterUser, String newWaterUser, CwmsId projectLocation) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(projectLocation); + LocationRefType locationRefType = map(projectLocation); connection(dsl, c -> waterSupplyJooq.renameWaterUser(c, locationRefType, oldWaterUser, newWaterUser)); } - public void storeWaterUser(WaterUserType waterUserType) { + public void storeWaterUser(WaterUser waterUserType) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(waterUserType.getParentLocationRefType()); + usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(waterUserType.getParentLocationRef()); - List waterUserTypeModified = new ArrayList<>(); + List waterUserTypeModified = new ArrayList<>(); waterUserTypeModified.add(new usace.cwms.db.dao.ifc.watersupply.WaterUserType(waterUserType.getEntityName(), locationRefType, waterUserType.getWaterRight())); connection(dsl, c -> waterSupplyJooq.storeWaterUsers(c, waterUserTypeModified, true)); } - public void renameWaterContract(WaterUserContractRefType waterContractRefType, String oldContractName, + public void renameWaterContract(WaterUserContractRef waterContractRefType, String oldContractName, String newContractName) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType waterUserContractRefType = - map(waterContractRefType, waterContractRefType.getWaterUserType().getParentLocationRefType()); + WaterUserContractRefType waterUserContractRefType = + map(waterContractRefType, waterContractRefType.getWaterUser().getParentLocationRef()); connection(dsl, c -> waterSupplyJooq.renameContract(c, waterUserContractRefType, oldContractName, newContractName)); } - public void deleteWaterUser(LocationRefType location, String entityName, String deleteAction) { + public void deleteWaterUser(CwmsId location, String entityName, String deleteAction) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(location); + LocationRefType locationRefType = map(location); connection(dsl, c -> waterSupplyJooq.deleteWaterUser(c, locationRefType, entityName, deleteAction)); } - public void deleteWaterContract(WaterUserContractRefType waterUserContractRefType, String deleteAction) { + public void deleteWaterContract(WaterUserContractRef waterUserContractRefType, String deleteAction) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType waterUserContractRefTypeModified = - map(waterUserContractRefType, waterUserContractRefType.getWaterUserType().getParentLocationRefType()); + WaterUserContractRefType waterUserContractRefTypeModified = + map(waterUserContractRefType, waterUserContractRefType.getWaterUser().getParentLocationRef()); connection(dsl, c -> waterSupplyJooq.deleteContract(c, waterUserContractRefTypeModified, deleteAction)); } - public void storeWaterContractTypes(WaterUserContractType waterUserContractType, boolean failIfExists) { + public void storeWaterContractTypes(WaterUserContract waterUserContractType, boolean failIfExists) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - List waterUserContractTypeModified = new ArrayList<>(); + List waterUserContractTypeModified = new ArrayList<>(); waterUserContractTypeModified.add(map(waterUserContractType, - waterUserContractType.getWaterUserContractRefType(), - waterUserContractType.getWaterUserContractRefType().getWaterUserType().getParentLocationRefType())); + waterUserContractType.getWaterUserContractRef(), + waterUserContractType.getWaterUserContractRef().getWaterUser().getParentLocationRef())); connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, failIfExists)); } - public void removePumpFromContract(WaterUserContractRefType waterUserContractRefType, String pumpLocId, + public void removePumpFromContract(WaterUserContractRef waterUserContractRefType, String pumpLocId, String usageId, boolean deleteAccounting) { CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType contractRefType = - map(waterUserContractRefType, waterUserContractRefType.getWaterUserType().getParentLocationRefType()); + WaterUserContractRefType contractRefType = + map(waterUserContractRefType, waterUserContractRefType.getWaterUser().getParentLocationRef()); connection(dsl, c -> waterSupplyJooq.disassociatePump(c, contractRefType, pumpLocId, usageId, deleteAccounting)); } - private WaterUserType map(usace.cwms.db.dao.ifc.watersupply.WaterUserType waterUserType, - LocationRefType projectLocation) { - return new WaterUserType(waterUserType.getEntityName(), + private WaterUser map(WaterUserType waterUserType, + CwmsId projectLocation) { + return new WaterUser(waterUserType.getEntityName(), projectLocation, waterUserType.getWaterRight()); } - private usace.cwms.db.dao.ifc.watersupply.WaterUserType map(WaterUserType waterUserType, - LocationRefType projectLocation) { - return new usace.cwms.db.dao.ifc.watersupply.WaterUserType(waterUserType.getEntityName(), + private WaterUserType map(WaterUser waterUserType, + CwmsId projectLocation) { + return new WaterUserType(waterUserType.getEntityName(), map(projectLocation), waterUserType.getWaterRight()); } private LookupType map(usace.cwms.db.dao.ifc.cat.LookupType lookupType) { - return new LookupType(lookupType.getOfficeId(), - lookupType.getDisplayValue(), lookupType.getTooltip(), lookupType.getActive()); + return new LookupType.Builder() + .withOfficeId(lookupType.getOfficeId()) + .withDisplayValue(lookupType.getDisplayValue()) + .withTooltip(lookupType.getTooltip()) + .withActive(lookupType.getActive()) + .build(); } private usace.cwms.db.dao.ifc.cat.LookupType map(LookupType lookupType) { @@ -230,64 +241,55 @@ private usace.cwms.db.dao.ifc.cat.LookupType map(LookupType lookupType) { lookupType.getDisplayValue(), lookupType.getTooltip(), lookupType.getActive()); } - private usace.cwms.db.dao.ifc.loc.LocationRefType map(LocationRefType projectLocation) { - return new usace.cwms.db.dao.ifc.loc.LocationRefType(projectLocation.getBaseLocationId(), - projectLocation.getSubLocationId(), projectLocation.getOfficeId()); - } - - private LocationRefType map(usace.cwms.db.dao.ifc.loc.LocationRefType projectLocation) { - return new LocationRefType(projectLocation.getBaseLocationId(), projectLocation.getSubLocationId(), - projectLocation.getOfficeId()); + private LocationRefType map(CwmsId projectLocation) { + return new LocationRefType(projectLocation.getName(),"", + projectLocation.getOfficeId()); } - private usace.cwms.db.dao.ifc.loc.LocationType map(LocationType locationType) { - return new usace.cwms.db.dao.ifc.loc.LocationType(map(locationType.getLocationRefType()), - locationType.getStateInitial(), locationType.getCountyName(), - locationType.getTimeZoneName(), locationType.getTypeOfLocation(), - locationType.getLatitude(), locationType.getLongitude(), - locationType.getHorizontalDatum(), locationType.getElevation(), - locationType.getElevUnitId(), locationType.getVerticalDatum(), - locationType.getPublicName(), locationType.getLongName(), - locationType.getDescription(), locationType.getActiveFlag(), - locationType.getLocationKindId(), locationType.getMapLabel(), - locationType.getPublishedLatitude(), locationType.getPublishedLongitude(), - locationType.getBoundingOfficeId(), locationType.getBoundingOfficeName(), - locationType.getNationId(), locationType.getNearestCity()); + private LocationType map(Location location) { + return new LocationType(new LocationRefType(location.getName(), + "", location.getOfficeId()), + location.getStateInitial(), location.getCountyName(), + location.getTimezoneName(), location.getLocationType(), + location.getLatitude(), location.getLongitude(), + location.getHorizontalDatum(), location.getElevation(), + location.getElevationUnits(), location.getVerticalDatum(), + location.getPublicName(), location.getLongName(), + location.getDescription(), location.getActive(), + location.getLocationKind(), location.getMapLabel(), + location.getPublishedLatitude(), location.getPublishedLongitude(), + location.getBoundingOfficeId(), location.getBoundingOfficeId(), + location.getNation().toString(), location.getNearestCity()); } - private LocationType map(usace.cwms.db.dao.ifc.loc.LocationType locationType) { - return new LocationType.Builder() - .withBoundingOfficeName(locationType.getBoundingOfficeName()) - .withCountyName(locationType.getCountyName()) - .withDescription(locationType.getDescription()) - .withBoundingOfficeId(locationType.getBoundingOfficeId()) - .withActiveFlag(locationType.getActiveFlag()) - .withStateInitial(locationType.getStateInitial()) - .withElevUnitId(locationType.getElevUnitId()) - .withLatitude(locationType.getLatitude()) - .withHorizontalDatum(locationType.getHorizontalDatum()) - .withLocationKindId(locationType.getLocationKindId()) - .withMapLabel(locationType.getMapLabel()) - .withLongitude(locationType.getLongitude()) - .withLongName(locationType.getLongName()) - .withPublishedLatitude(locationType.getPublishedLatitude()) - .withPublishedLongitude(locationType.getPublishedLongitude()) - .withPublicName(locationType.getPublicName()) - .withElevation(locationType.getElevation()) - .withNearestCity(locationType.getNearestCity()) - .withNationId(locationType.getNationId()) - .withVerticalDatum(locationType.getVerticalDatum()) - .withTimeZoneName(locationType.getTimeZoneName()) - .withTypeOfLocation(locationType.getLocationType()) - .withLocationRefType(map(locationType.getLocationRef())) + private Location map(LocationType location) { + return new Location.Builder(location.getBoundingOfficeId(), location.getPublicName()) + .withLocationKind(location.getLocationKindId()) + .withStateInitial(location.getStateInitial()) + .withCountyName(location.getCountyName()) + .withTimeZoneName(ZoneId.of(location.getTimeZoneName())) + .withLatitude(location.getLatitude()) + .withLongitude(location.getLongitude()) + .withHorizontalDatum(location.getHorizontalDatum()) + .withElevation(location.getElevation()) + .withElevationUnits(location.getElevUnitId()) + .withVerticalDatum(location.getVerticalDatum()) + .withLongName(location.getLongName()) + .withDescription(location.getDescription()) + .withActive(location.getActiveFlag()) + .withMapLabel(location.getMapLabel()) + .withPublishedLatitude(location.getPublishedLatitude()) + .withPublishedLongitude(location.getPublishedLongitude()) + .withNation(Nation.valueOf(location.getNationId())) + .withNearestCity(location.getNearestCity()) .build(); } - private usace.cwms.db.dao.ifc.watersupply.WaterUserContractType map(WaterUserContractType contract, - WaterUserContractRefType waterUserContractRefType, LocationRefType projectLocation) { - return new usace.cwms.db.dao.ifc.watersupply.WaterUserContractType(map(waterUserContractRefType, + private WaterUserContractType map(WaterUserContract contract, + WaterUserContractRef waterUserContractRef, CwmsId projectLocation) { + return new WaterUserContractType(map(waterUserContractRef, projectLocation), - map(contract.getWaterSupplyContractType()), contract.getContractEffectiveDate(), + map(contract.getWaterSupplyContract()), contract.getContractEffectiveDate(), contract.getContractExpirationDate(), contract.getContractedStorage(), contract.getInitialUseAllocation(), contract.getFutureUseAllocation(), contract.getStorageUnitsId(), contract.getFutureUsePercentActivated(), @@ -295,11 +297,11 @@ private usace.cwms.db.dao.ifc.watersupply.WaterUserContractType map(WaterUserCon map(contract.getPumpOutBelowLocation()), map(contract.getPumpInLocation())); } - private WaterUserContractType map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractType contract, - LocationRefType projectLocation) { - return new WaterUserContractType.Builder() - .withWaterSupplyContractType(map(contract.getWaterSupplyContractType())) - .withWaterUserContractRefType(map(contract.getWaterUserContractRefType(), projectLocation)) + private WaterUserContract map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractType contract, + CwmsId projectLocation) { + return new WaterUserContract.Builder() + .withWaterSupplyContract(map(contract.getWaterSupplyContractType())) + .withWaterUserContractRef(map(contract.getWaterUserContractRefType(), projectLocation)) .withContractEffectiveDate(contract.getContractEffectiveDate()) .withContractExpirationDate(contract.getContractExpirationDate()) .withContractedStorage(contract.getContractedStorage()) @@ -314,15 +316,15 @@ private WaterUserContractType map(usace.cwms.db.dao.ifc.watersupply.WaterUserCon .build(); } - private usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType map(WaterUserContractRefType contract, - LocationRefType projectLocation) { - return new usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType(map(contract.getWaterUserType(), + private WaterUserContractRefType map(WaterUserContractRef contract, + CwmsId projectLocation) { + return new WaterUserContractRefType(map(contract.getWaterUser(), projectLocation), contract.getContractName()); } - private WaterUserContractRefType map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType contract, - LocationRefType projectLocation) { - return new WaterUserContractRefType(map(contract.getWaterUserType(), projectLocation), + private WaterUserContractRef map(WaterUserContractRefType contract, + CwmsId projectLocation) { + return new WaterUserContractRef(map(contract.getWaterUserType(), projectLocation), contract.getContractName()); } } From 335cd3dea26927b5bddbbb6d68b8e5758d7eb9d1 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 3 Jul 2024 17:03:22 -0700 Subject: [PATCH 13/39] DAO Testing in progress --- .../data/dao/watersupply/WaterSupplyDao.java | 330 ------------------ .../cda/data/dto/watersupply/WaterSupply.java | 147 -------- .../data/dto/watersupply/WaterSupplyTest.java | 242 ------------- .../cda/data/dto/watersupply/watersupply.json | 116 ------ 4 files changed, 835 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java delete mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java deleted file mode 100644 index dfdad0b06..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyDao.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dao.watersupply; - -import cwms.cda.api.enums.Nation; -import cwms.cda.data.dao.JooqDao; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.Location; -import cwms.cda.data.dto.LookupType; -import cwms.cda.data.dto.watersupply.WaterSupply; -import cwms.cda.data.dto.watersupply.WaterUser; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.data.dto.watersupply.WaterUserContractRef; -import java.sql.SQLException; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.List; -import org.jooq.DSLContext; -import usace.cwms.db.dao.ifc.loc.LocationRefType; -import usace.cwms.db.dao.ifc.loc.LocationType; -import usace.cwms.db.dao.ifc.watersupply.WaterUserContractRefType; -import usace.cwms.db.dao.ifc.watersupply.WaterUserContractType; -import usace.cwms.db.dao.ifc.watersupply.WaterUserType; -import usace.cwms.db.jooq.dao.CwmsDbWaterSupplyJooq; - -public class WaterSupplyDao extends JooqDao { - public WaterSupplyDao(DSLContext dsl) { - super(dsl); - } - - // TO DO: Get water contract number - public List getAllWaterContracts(CwmsId projectLocation, String entityName) - throws SQLException { - List retVal = new ArrayList<>(); - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - List waterUserContractTypes = new ArrayList<>(); - - LocationRefType locationRefType = map(projectLocation); - - try { - connection(dsl, c -> waterUserContractTypes.addAll(waterSupplyJooq.retrieveContracts(c, locationRefType, - entityName))); - } catch (Exception ex) { - throw new SQLException(ex); - } - - for (WaterUserContractType waterUserContractType : waterUserContractTypes) { - WaterSupply waterSupply = new WaterSupply.Builder() - .withContractName(waterUserContractType.getWaterUserContractRefType().getContractName()) - .withWaterUser(waterUserContractType.getWaterUserContractRefType() - .getWaterUserType().getEntityName()) - .withUser(map(waterUserContractType.getWaterUserContractRefType().getWaterUserType(), - projectLocation)) - .withContract(map(waterUserContractType, projectLocation)) - .build(); - retVal.add(waterSupply); - } - - return retVal; - } - - public List getAllWaterContractTypes(String officeId) throws SQLException { - List retVal = new ArrayList<>(); - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - try { - connection(dsl, c -> { - List contractTypeList = - waterSupplyJooq.getContractTypes(c, officeId); - for (usace.cwms.db.dao.ifc.cat.LookupType lookupType : contractTypeList) { - LookupType waterUserContractType = map(lookupType); - retVal.add(waterUserContractType); - } - }); - } catch (Exception ex) { - throw new SQLException(ex); - } - return retVal; - } - - public List getAllWaterUsers(CwmsId projectLocation) throws SQLException { - List retVal = new ArrayList<>(); - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - LocationRefType locationRefType = map(projectLocation); - - try { - connection(dsl, c -> { - List waterUserTypes = - waterSupplyJooq.retrieveWaterUsers(c, locationRefType); - for (WaterUserType waterUserType : waterUserTypes) { - WaterUser waterUser = map(waterUserType, projectLocation); - retVal.add(waterUser); - } - }); - } catch (Exception ex) { - throw new SQLException(ex); - } - return retVal; - } - - public WaterUser getWaterUser(CwmsId projectLocation, String entityName) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - List userList = new ArrayList<>(); - - connection(dsl, c -> userList.addAll(waterSupplyJooq.retrieveWaterUsers(c, map(projectLocation)))); - - for (WaterUserType waterUser : userList) { - if (waterUser.getEntityName().equals(entityName)) { - return map(waterUser, projectLocation); - } - } - return null; - } - - public void storeWaterContract(WaterUserContract waterContractType, boolean failIfExists, boolean ignoreNulls) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - List waterUserContractTypeModified = new ArrayList<>(); - waterUserContractTypeModified.add(map(waterContractType, waterContractType.getWaterUserContractRef(), - waterContractType.getWaterUserContractRef().getWaterUser().getParentLocationRef())); - connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, - failIfExists, ignoreNulls)); - } - - public void renameWaterUser(String oldWaterUser, String newWaterUser, CwmsId projectLocation) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - LocationRefType locationRefType = map(projectLocation); - - connection(dsl, c -> waterSupplyJooq.renameWaterUser(c, locationRefType, oldWaterUser, newWaterUser)); - } - - public void storeWaterUser(WaterUser waterUserType) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - usace.cwms.db.dao.ifc.loc.LocationRefType locationRefType = map(waterUserType.getParentLocationRef()); - - List waterUserTypeModified = new ArrayList<>(); - waterUserTypeModified.add(new usace.cwms.db.dao.ifc.watersupply.WaterUserType(waterUserType.getEntityName(), - locationRefType, waterUserType.getWaterRight())); - - connection(dsl, c -> waterSupplyJooq.storeWaterUsers(c, waterUserTypeModified, true)); - } - - public void renameWaterContract(WaterUserContractRef waterContractRefType, String oldContractName, - String newContractName) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - WaterUserContractRefType waterUserContractRefType = - map(waterContractRefType, waterContractRefType.getWaterUser().getParentLocationRef()); - - connection(dsl, c -> waterSupplyJooq.renameContract(c, waterUserContractRefType, - oldContractName, newContractName)); - } - - public void deleteWaterUser(CwmsId location, String entityName, String deleteAction) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - LocationRefType locationRefType = map(location); - - connection(dsl, c -> waterSupplyJooq.deleteWaterUser(c, locationRefType, entityName, deleteAction)); - } - - public void deleteWaterContract(WaterUserContractRef waterUserContractRefType, String deleteAction) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - WaterUserContractRefType waterUserContractRefTypeModified = - map(waterUserContractRefType, waterUserContractRefType.getWaterUser().getParentLocationRef()); - - connection(dsl, c -> waterSupplyJooq.deleteContract(c, waterUserContractRefTypeModified, deleteAction)); - } - - public void storeWaterContractTypes(WaterUserContract waterUserContractType, boolean failIfExists) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - List waterUserContractTypeModified = new ArrayList<>(); - waterUserContractTypeModified.add(map(waterUserContractType, - waterUserContractType.getWaterUserContractRef(), - waterUserContractType.getWaterUserContractRef().getWaterUser().getParentLocationRef())); - connection(dsl, c -> waterSupplyJooq.storeContracts(c, waterUserContractTypeModified, failIfExists)); - } - - public void removePumpFromContract(WaterUserContractRef waterUserContractRefType, String pumpLocId, - String usageId, boolean deleteAccounting) { - CwmsDbWaterSupplyJooq waterSupplyJooq = new CwmsDbWaterSupplyJooq(); - - WaterUserContractRefType contractRefType = - map(waterUserContractRefType, waterUserContractRefType.getWaterUser().getParentLocationRef()); - connection(dsl, c -> waterSupplyJooq.disassociatePump(c, contractRefType, pumpLocId, - usageId, deleteAccounting)); - } - - private WaterUser map(WaterUserType waterUserType, - CwmsId projectLocation) { - return new WaterUser(waterUserType.getEntityName(), - projectLocation, waterUserType.getWaterRight()); - } - - private WaterUserType map(WaterUser waterUserType, - CwmsId projectLocation) { - return new WaterUserType(waterUserType.getEntityName(), - map(projectLocation), waterUserType.getWaterRight()); - } - - private LookupType map(usace.cwms.db.dao.ifc.cat.LookupType lookupType) { - return new LookupType.Builder() - .withOfficeId(lookupType.getOfficeId()) - .withDisplayValue(lookupType.getDisplayValue()) - .withTooltip(lookupType.getTooltip()) - .withActive(lookupType.getActive()) - .build(); - } - - private usace.cwms.db.dao.ifc.cat.LookupType map(LookupType lookupType) { - return new usace.cwms.db.dao.ifc.cat.LookupType(lookupType.getOfficeId(), - lookupType.getDisplayValue(), lookupType.getTooltip(), lookupType.getActive()); - } - - private LocationRefType map(CwmsId projectLocation) { - return new LocationRefType(projectLocation.getName(),"", - projectLocation.getOfficeId()); - } - - private LocationType map(Location location) { - return new LocationType(new LocationRefType(location.getName(), - "", location.getOfficeId()), - location.getStateInitial(), location.getCountyName(), - location.getTimezoneName(), location.getLocationType(), - location.getLatitude(), location.getLongitude(), - location.getHorizontalDatum(), location.getElevation(), - location.getElevationUnits(), location.getVerticalDatum(), - location.getPublicName(), location.getLongName(), - location.getDescription(), location.getActive(), - location.getLocationKind(), location.getMapLabel(), - location.getPublishedLatitude(), location.getPublishedLongitude(), - location.getBoundingOfficeId(), location.getBoundingOfficeId(), - location.getNation().toString(), location.getNearestCity()); - } - - private Location map(LocationType location) { - return new Location.Builder(location.getBoundingOfficeId(), location.getPublicName()) - .withLocationKind(location.getLocationKindId()) - .withStateInitial(location.getStateInitial()) - .withCountyName(location.getCountyName()) - .withTimeZoneName(ZoneId.of(location.getTimeZoneName())) - .withLatitude(location.getLatitude()) - .withLongitude(location.getLongitude()) - .withHorizontalDatum(location.getHorizontalDatum()) - .withElevation(location.getElevation()) - .withElevationUnits(location.getElevUnitId()) - .withVerticalDatum(location.getVerticalDatum()) - .withLongName(location.getLongName()) - .withDescription(location.getDescription()) - .withActive(location.getActiveFlag()) - .withMapLabel(location.getMapLabel()) - .withPublishedLatitude(location.getPublishedLatitude()) - .withPublishedLongitude(location.getPublishedLongitude()) - .withNation(Nation.valueOf(location.getNationId())) - .withNearestCity(location.getNearestCity()) - .build(); - } - - private WaterUserContractType map(WaterUserContract contract, - WaterUserContractRef waterUserContractRef, CwmsId projectLocation) { - return new WaterUserContractType(map(waterUserContractRef, - projectLocation), - map(contract.getWaterSupplyContract()), contract.getContractEffectiveDate(), - contract.getContractExpirationDate(), contract.getContractedStorage(), - contract.getInitialUseAllocation(), contract.getFutureUseAllocation(), - contract.getStorageUnitsId(), contract.getFutureUsePercentActivated(), - contract.getTotalAllocPercentActivated(), map(contract.getPumpOutLocation()), - map(contract.getPumpOutBelowLocation()), map(contract.getPumpInLocation())); - } - - private WaterUserContract map(usace.cwms.db.dao.ifc.watersupply.WaterUserContractType contract, - CwmsId projectLocation) { - return new WaterUserContract.Builder() - .withWaterSupplyContract(map(contract.getWaterSupplyContractType())) - .withWaterUserContractRef(map(contract.getWaterUserContractRefType(), projectLocation)) - .withContractEffectiveDate(contract.getContractEffectiveDate()) - .withContractExpirationDate(contract.getContractExpirationDate()) - .withContractedStorage(contract.getContractedStorage()) - .withInitialUseAllocation(contract.getInitialUseAllocation()) - .withFutureUseAllocation(contract.getFutureUseAllocation()) - .withStorageUnitsId(contract.getStorageUnitsId()) - .withFutureUsePercentActivated(contract.getFutureUsePercentActivated()) - .withTotalAllocPercentActivated(contract.getTotalAllocPercentActivated()) - .withPumpOutLocation(map(contract.getPumpOutLocation())) - .withPumpOutBelowLocation(map(contract.getPumpOutBelowLocation())) - .withPumpInLocation(map(contract.getPumpInLocation())) - .build(); - } - - private WaterUserContractRefType map(WaterUserContractRef contract, - CwmsId projectLocation) { - return new WaterUserContractRefType(map(contract.getWaterUser(), - projectLocation), contract.getContractName()); - } - - private WaterUserContractRef map(WaterUserContractRefType contract, - CwmsId projectLocation) { - return new WaterUserContractRef(map(contract.getWaterUserType(), projectLocation), - contract.getContractName()); - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java deleted file mode 100644 index a1f7d9368..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupply.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import cwms.cda.api.errors.FieldException; -import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.annotations.FormattableWith; -import cwms.cda.formatters.json.JsonV1; - -@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) -@JsonDeserialize(builder = WaterSupply.Builder.class) -public class WaterSupply implements CwmsDTOBase { - private final String contractName; - private final Integer contractNumber; - private final String waterUser; - private final WaterUser user; - private final WaterUserContract contract; - - private WaterSupply(Builder builder) { - contractName = builder.contractName; - contractNumber = builder.contractNumber; - waterUser = builder.waterUser; - user = builder.user; - contract = builder.contract; - } - - public String getContractName() { - return contractName; - } - - public Integer getContractNumber() { - return contractNumber; - } - - public String getWaterUser() { - return waterUser; - } - - public WaterUser getUser() { - return user; - } - - public WaterUserContract getContract() { - return contract; - } - - public static class Builder { - private String contractName; - private Integer contractNumber; - private String waterUser; - private WaterUser user; - private WaterUserContract contract; - - public Builder withContractName(String contractName) { - this.contractName = contractName; - return this; - } - - public Builder withContractNumber(Integer contractNumber) { - this.contractNumber = contractNumber; - return this; - } - - public Builder withWaterUser(String waterUser) { - this.waterUser = waterUser; - return this; - } - - public Builder withUser(WaterUser user) { - this.user = user; - return this; - } - - public Builder withContract(WaterUserContract contract) { - this.contract = contract; - return this; - } - - public WaterSupply build() { - return new WaterSupply(this); - } - } - - @Override - public void validate() throws FieldException { - if (contractName == null || contractName.isEmpty()) { - throw new FieldException("Contract Name cannot be null or empty"); - } - if (contractNumber == null) { - throw new FieldException("Contract Number cannot be null"); - } - if (waterUser == null || waterUser.isEmpty()) { - throw new FieldException("Water User cannot be null or empty"); - } - if (user == null) { - throw new FieldException("User Type cannot be null"); - } - if (user.getEntityName() == null) { - throw new FieldException("User Type Entity Name cannot be null"); - } - if (user.getWaterRight() == null) { - throw new FieldException("User Type Water Right cannot be null"); - } - if (contract == null) { - throw new FieldException("Contract Type cannot be null"); - } - if (contract.getWaterUserContractRef() == null) { - throw new FieldException("Water User Contract Ref Type cannot be null"); - } - if (contract.getWaterSupplyContract() == null) { - throw new FieldException("Water Supply Contract Type cannot be null"); - } - if (contract.getContractEffectiveDate() == null) { - throw new FieldException("Contract Effective Date cannot be null"); - } - if (contract.getInitialUseAllocation() == null) { - throw new FieldException("Contract Initial Use Allocation cannot be null"); - } - if (contract.getContractedStorage() == null) { - throw new FieldException("Contracted Storage cannot be null"); - } - } -} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java deleted file mode 100644 index af85fb9da..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyTest.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import cwms.cda.api.enums.Nation; -import cwms.cda.api.errors.FieldException; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.CwmsIdTest; -import cwms.cda.formatters.Formats; -import cwms.cda.data.dto.LookupType; -import cwms.cda.data.dto.Location; -import org.apache.commons.io.IOUtils; -import org.junit.jupiter.api.Test; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.ZoneId; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -class WaterSupplyTest { - - private static final String OFFICE_ID = "SPK"; - - @Test - void testWaterSupplySerializationRoundTrip() { - WaterSupply waterSupply = buildTestWaterSupply(); - String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), waterSupply); - WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); - assertSame(waterSupply, deserialized); - } - - @Test - void testWaterSupplySerializationRoundTripFromFile() throws Exception - { - WaterSupply waterSupply = buildTestWaterSupply(); - InputStream resource = this.getClass().getResourceAsStream("/cwms/cda/data/dto/watersupply/watersupply.json"); - assertNotNull(resource); - String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); - WaterSupply deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupply.class), serialized, WaterSupply.class); - assertSame(waterSupply, deserialized); - } - - @Test - void testValidate() - { - assertAll(() -> { - WaterSupply waterSupply = buildTestWaterSupply(); - assertDoesNotThrow(waterSupply::validate); - }, () -> { - WaterSupply waterSupply = new WaterSupply.Builder() - .withContractName("Test Contract") - .build(); - assertThrows(FieldException.class, waterSupply::validate, - "Expected validate() to throw FieldException for missing fields, but it didn't"); - } - ); - } - - private WaterSupply buildTestWaterSupply () - { - return new WaterSupply.Builder() - .withContractName("Test Contract") - .withContractNumber(1234) - .withWaterUser("Test User") - .withUser(new WaterUser("Test Entity", - new CwmsId.Builder() - .withName("Base Location") - .withOfficeId(OFFICE_ID) - .build(), - "Water Right test")) - .withContract(new WaterUserContract.Builder() - .withWaterUserContractRef(new WaterUserContractRef(new WaterUser("Entity Test", - new CwmsId.Builder() - .withName("Base Location") - .withOfficeId(OFFICE_ID) - .build(), - "Water Right Test"), - "Contract Name Test")) - .withWaterSupplyContract(new LookupType.Builder() - .withActive(true) - .withDisplayValue("Display Value Test") - .withOfficeId(OFFICE_ID) - .withTooltip("Example Tooltip") - .build()) - .withContractEffectiveDate(new Date(1719854376)) - .withContractExpirationDate(new Date(1719854376)) - .withContractedStorage(1000.0) - .withInitialUseAllocation(20.5) - .withFutureUseAllocation(79.5) - .withStorageUnitsId("Test Storage Unit") - .withFutureUsePercentActivated(25.5) - .withTotalAllocPercentActivated(15.2) - .withPumpOutLocation(buildLocationType("Pump Out Location")) - .withPumpOutBelowLocation(buildLocationType("Pump Out Below Location")) - .withPumpInLocation(buildLocationType("Pump In Location")) - .build()) - .build(); - } - - private Location buildLocationType(String pumpLocation) - { - return new Location.Builder(OFFICE_ID, pumpLocation) - .withStateInitial("CA") - .withBoundingOfficeId(OFFICE_ID) - .withDescription("Place for testing") - .withElevation(120.0) - .withCountyName("Sacramento") - .withHorizontalDatum("WGS84") - .withLatitude(0.0) - .withLongitude(0.0) - .withLongName("Full Location Name") - .withMapLabel("Map location") - .withNearestCity("Davis") - .withPublishedLatitude(0.0) - .withPublishedLongitude(0.0) - .withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("WGS84") - .withPublicName(pumpLocation) - .withLocationType("PUMP") - .withActive(true) - .withNation(Nation.US) - .withBoundingOfficeId(OFFICE_ID) - .withElevationUnits("m") - .withLocationKind("PUMP") - .build(); - } - - - private static void assertSame(WaterSupply first, WaterSupply second) - { - assertAll( - () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertEquals(first.getContractNumber(), second.getContractNumber()), - () -> assertEquals(first.getWaterUser(), second.getWaterUser()), - () -> assertWaterUserType(first.getUser(), second.getUser()), - () -> assertWaterUserContractType(first.getContract(), second.getContract()) - ); - } - - private static void assertLocationType(Location first, Location second) - { - assertAll( - () -> assertEquals(first.getNearestCity(), second.getNearestCity()), - () -> assertEquals(first.getNation(), second.getNation()), - () -> assertEquals(first.getBoundingOfficeId(), second.getBoundingOfficeId()), - () -> assertEquals(first.getPublishedLongitude(), second.getPublishedLongitude()), - () -> assertEquals(first.getPublishedLatitude(), second.getPublishedLatitude()), - () -> assertEquals(first.getMapLabel(), second.getMapLabel()), - () -> assertEquals(first.getLocationKind(), second.getLocationKind()), - () -> assertEquals(first.getActive(), second.getActive()), - () -> assertEquals(first.getDescription(), second.getDescription()), - () -> assertEquals(first.getLongName(), second.getLongName()), - () -> assertEquals(first.getPublicName(), second.getPublicName()), - () -> assertEquals(first.getVerticalDatum(), second.getVerticalDatum()), - () -> assertEquals(first.getElevationUnits(), second.getElevationUnits()), - () -> assertEquals(first.getElevation(), second.getElevation()), - () -> assertEquals(first.getHorizontalDatum(), second.getHorizontalDatum()), - () -> assertEquals(first.getLongitude(), second.getLongitude()), - () -> assertEquals(first.getLatitude(), second.getLatitude()), - () -> assertEquals(first.getLocationType(), second.getLocationType()), - () -> assertEquals(first.getTimezoneName(), second.getTimezoneName()), - () -> assertEquals(first.getCountyName(), second.getCountyName()), - () -> assertEquals(first.getStateInitial(), second.getStateInitial()), - () -> assertEquals(first.getName(), second.getName()) - ); - } - - private static void assertLookupType(LookupType first, LookupType second) - { - assertAll( - () -> assertEquals(first.getOfficeId(), second.getOfficeId()), - () -> assertEquals(first.getActive(), second.getActive()), - () -> assertEquals(first.getDisplayValue(), second.getDisplayValue()), - () -> assertEquals(first.getTooltip(), second.getTooltip()) - ); - } - - private static void assertWaterUserType(WaterUser first, WaterUser second) - { - assertAll( - () -> assertEquals(first.getEntityName(), second.getEntityName()), - () -> CwmsIdTest.assertSame(first.getParentLocationRef(), second.getParentLocationRef()), - () -> assertEquals(first.getWaterRight(), second.getWaterRight()) - ); - } - - private static void assertWaterUserContractType(WaterUserContract first, WaterUserContract second) - { - assertAll( - () -> assertWaterUserContractRefType(first.getWaterUserContractRef(), second.getWaterUserContractRef()), - () -> assertLookupType(first.getWaterSupplyContract(), second.getWaterSupplyContract()), - () -> assertEquals(first.getContractEffectiveDate(), second.getContractEffectiveDate()), - () -> assertEquals(first.getContractExpirationDate(), second.getContractExpirationDate()), - () -> assertEquals(first.getContractedStorage(), second.getContractedStorage()), - () -> assertEquals(first.getInitialUseAllocation(), second.getInitialUseAllocation()), - () -> assertEquals(first.getFutureUseAllocation(), second.getFutureUseAllocation()), - () -> assertEquals(first.getStorageUnitsId(), second.getStorageUnitsId()), - () -> assertEquals(first.getFutureUsePercentActivated(), second.getFutureUsePercentActivated()), - () -> assertEquals(first.getTotalAllocPercentActivated(), second.getTotalAllocPercentActivated()), - () -> assertLocationType(first.getPumpOutLocation(), second.getPumpOutLocation()), - () -> assertLocationType(first.getPumpOutBelowLocation(), second.getPumpOutBelowLocation()), - () -> assertLocationType(first.getPumpInLocation(), second.getPumpInLocation()) - ); - } - - private static void assertWaterUserContractRefType(WaterUserContractRef first, WaterUserContractRef second) - { - assertAll( - () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertWaterUserType(first.getWaterUser(), second.getWaterUser()) - ); - } -} - diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json deleted file mode 100644 index 1244e0401..000000000 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/watersupply.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "contract-name": "Test Contract", - "contract-number": 1234, - "water-user": "Test User", - "user": { - "entity-name": "Test Entity", - "parent-location-ref": { - "name": "Base Location", - "office-id": "SPK" - }, - "water-right": "Water Right test" - }, - "contract": { - "water-user-contract-ref": { - "water-user": { - "entity-name": "Entity Test", - "parent-location-ref": { - "name": "Base Location", - "office-id": "SPK" - }, - "water-right": "Water Right Test" - }, - "contract-name": "Contract Name Test" - }, - "water-supply-contract": { - "active": true, - "office-id": "SPK", - "tooltip": "Example Tooltip", - "display-value": "Display Value Test" - }, - "contract-effective-date": 1719854376, - "contract-expiration-date": 1719854376, - "contracted-storage": 1000, - "initial-use-allocation": 20.5, - "future-use-allocation": 79.5, - "storage-units-id": "Test Storage Unit", - "future-use-percent-activated": 25.5, - "total-alloc-percent-activated": 15.2, - "pump-out-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump Out Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump Out Location", - "office-id": "SPK" - }, - "pump-out-below-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump Out Below Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump Out Below Location", - "office-id": "SPK" - }, - "pump-in-location": { - "nearest-city": "Davis", - "nation": "US", - "bounding-office-id": "SPK", - "published-longitude": 0, - "published-latitude": 0, - "map-label": "Map location", - "location-kind": "PUMP", - "active": true, - "description": "Place for testing", - "long-name": "Full Location Name", - "public-name": "Pump In Location", - "vertical-datum": "WGS84", - "elevation-units": "m", - "elevation": 120, - "horizontal-datum": "WGS84", - "longitude": 0, - "latitude": 0, - "location-type": "PUMP", - "time-zone-name": "UTC", - "county-name": "Sacramento", - "state-initial": "CA", - "name": "Pump In Location", - "office-id": "SPK" - - } - } -} \ No newline at end of file From ee271fc2a2edb5187d9a582d0f0888aa1c7e5190 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 9 Jul 2024 17:01:55 -0700 Subject: [PATCH 14/39] First draft of Water supply controllers, tests in progress --- .../cwms/cda/api/WaterContractController.java | 308 ++++++++++++++++++ .../cda/api/WaterContractTypeController.java | 163 +++++++++ .../cwms/cda/api/WaterPumpController.java | 139 ++++++++ .../cwms/cda/api/WaterUserController.java | 261 +++++++++++++++ 4 files changed, 871 insertions(+) create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java new file mode 100644 index 000000000..76997cfd3 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java @@ -0,0 +1,308 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.errors.CdaError; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.data.dto.watersupply.WaterUserContractRef; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import io.javalin.apibuilder.CrudHandler; +import io.javalin.core.util.Header; +import io.javalin.http.Context; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiContent; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +public class WaterContractController implements CrudHandler { + private final Logger LOGGER = Logger.getLogger(WaterContractController.class.getName()); + public static final String TAG = "Water Contracts"; + private static final String WATER_USER = "water-user"; + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi( + queryParams = { + + @OpenApiParam(name = NAME, description = "Specifies the name of the contract.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location id of the contract.", required = true), + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "Specifies the project id of the contract.", required = true), + @OpenApiParam(name = WATER_USER, description = "Specifies the water user of the contract.", required = true), + }, + responses = { + @OpenApiResponse(status = STATUS_200, + content = { + @OpenApiContent(from = WaterUserContract.class, type = Formats.JSONV1), + @OpenApiContent(from = WaterUserContract.class, type = Formats.JSON) + }), + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Return all water contracts", + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}", + method = HttpMethod.GET, + tags = {TAG} + ) + @Override + public void getAll(@NotNull Context ctx) { + final String office = ctx.queryParam("office"); + final String name = ctx.queryParam("name"); + final String locationId = ctx.queryParam("locationId"); + DSLContext dsl = getDslContext(ctx); + String result; + CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterContractDao contractDao = getContractDao(dsl); + List contracts = contractDao.getAllWaterContracts(projectLocation, name); + + if (contracts.isEmpty()) { + CdaError error = new CdaError("No contracts found for the provided parameters."); + LOGGER.log(Level.SEVERE, "Error retrieving all contracts"); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + result = Formats.format(contentType, contracts, WaterUserContract.class); + ctx.result(result); + ctx.status(HttpServletResponse.SC_OK); + } + + + @OpenApi( + queryParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = NAME, description = "Specifies the name of the contract.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location id of the contract.", required = true), + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = STATUS_200, + content = { + @OpenApiContent(from = WaterUserContract.class, type = Formats.JSONV1), + @OpenApiContent(from = WaterUserContract.class, type = Formats.JSON) + }), + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Return a specified water contract", + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", + method = HttpMethod.GET, + tags = {TAG} + ) + + @Override + public void getOne(@NotNull Context ctx, @NotNull String contractName){ + final String office = ctx.queryParam("office"); + final String name = ctx.queryParam("name"); + final String locationId = ctx.queryParam("locationId"); + DSLContext dsl = getDslContext(ctx); + String result; + CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterContractDao contractDao = getContractDao(dsl); + List contracts = contractDao.getAllWaterContracts(projectLocation, name); + + if (contracts.isEmpty()) { + CdaError error = new CdaError("No contracts found for the provided parameters."); + LOGGER.log(Level.SEVERE, "Error retrieving contracts"); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + for (WaterUserContract contract : contracts) { + if (contract.getContractId().getName().equals(contractName)) { + contracts.clear(); + contracts.add(contract); + result = Formats.format(contentType, contracts, WaterUserContract.class); + ctx.result(result); + ctx.status(HttpServletResponse.SC_OK); + return; + } + } + CdaError error = new CdaError("No contract found for the provided name."); + LOGGER.log(Level.SEVERE, "Error retrieving contract"); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + } + + + @OpenApi( + responses = { + @OpenApiResponse(status = "204", description = "Basin successfully stored to CWMS."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + description = "Create a new water contract", + method = HttpMethod.POST, + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts", + tags = {TAG} + ) + + @Override + public void create(@NotNull Context ctx){ + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterUserContract waterContract = Formats.parseContent(contentType, ctx.body(), WaterUserContract.class); + + String newContractName = waterContract.getContractId().getName(); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.storeWaterContract(waterContract, true, false); + ctx.status(HttpServletResponse.SC_CREATED).json(newContractName + " created successfully"); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = NAME, description = "Specifies the new name of the contract.", required = true) + }, + pathParams = { + @OpenApiParam(name = "contractName", description = "Specifies the name of the contract to be renamed.", required = true), + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = "404", description = "The provided combination of " + + "parameters did not find a contract"), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Renames a water contract", + method = HttpMethod.PATCH, + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", + tags = {TAG} + ) + + @Override + public void update(@NotNull Context ctx, @NotNull String contractName){ + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + String newName = ctx.queryParam(NAME); + WaterUserContract waterContract = Formats.parseContent(contentType, ctx.body(), WaterUserContract.class); + WaterContractDao contractDao = getContractDao(dsl); + WaterUserContractRef ref = new WaterUserContractRef(waterContract.getWaterUser(), + waterContract.getContractId().getName()); + contractDao.renameWaterContract(ref, contractName, newName); + ctx.status(HttpServletResponse.SC_OK).json("Contract renamed successfully"); + } + + + @OpenApi( + queryParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location for the contract.", required = true), + @OpenApiParam(name = DELETE_MODE, description = "Specifies the delete method used."), + }, + pathParams = { + @OpenApiParam(name = NAME, description = "The name of the contract to be deleted."), + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Delete a specified water contract", + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", + method = HttpMethod.DELETE, + tags = {TAG} + ) + + @Override + public void delete(@NotNull Context ctx, @NotNull String contractName){ + + DSLContext dsl = getDslContext(ctx); + String deleteMethod = ctx.queryParam(DELETE_MODE); + String locationId = ctx.queryParam(LOCATION_ID); + String office = ctx.queryParam(OFFICE); + WaterContractDao contractDao = getContractDao(dsl); + CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); + + List retContracts = contractDao.getAllWaterContracts(projectLocation, contractName); + + if (retContracts.isEmpty()) { + CdaError error = new CdaError("No contract found for the provided parameters."); + LOGGER.log(Level.SEVERE, "Error retrieving contracts"); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + for (WaterUserContract contract : retContracts) { + if (contract.getContractId().getName().equals(contractName)) { + contractDao.deleteWaterContract(contract, deleteMethod); + ctx.status(HttpServletResponse.SC_NO_CONTENT).json(contractName + " deleted successfully"); + return; + } + } + CdaError error = new CdaError("No contract found for the provided name."); + LOGGER.log(Level.SEVERE, "No matching contract found for deletion."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java new file mode 100644 index 000000000..34d9a3355 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java @@ -0,0 +1,163 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.errors.CdaError; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import io.javalin.apibuilder.CrudHandler; +import io.javalin.core.util.Header; +import io.javalin.http.Context; +import io.javalin.http.HttpCode; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiContent; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; +import usace.cwms.db.dao.ifc.watersupply.WaterUserContractType; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +public class WaterContractTypeController implements CrudHandler { + private static final Logger LOGGER = Logger.getLogger(WaterContractTypeController.class.getName()); + public static final String TAG = "Water Contracts"; + + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi ( + queryParams = { + @OpenApiParam(name = OFFICE, required = true, + description = "The office Id the contract is associated with.") + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = "200", content = { + @OpenApiContent(from = WaterUserContractType.class, type = Formats.JSONV1), + @OpenApiContent(from = WaterUserContractType.class, type = Formats.JSON) + }), + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Get all water contract types", + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}/types", + method = HttpMethod.GET, + tags = {TAG} + ) + + @Override + public void getAll(@NotNull Context ctx){ + String officeId = ctx.queryParam(OFFICE); + DSLContext dsl = getDslContext(ctx); + String result; + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); + ctx.contentType(contentType.toString()); + WaterContractDao dao = getContractDao(dsl); + List typeList = dao.getAllWaterContractTypes(officeId); + + if (typeList.isEmpty()) { + CdaError error = new CdaError("No contract types found for office: " + officeId); + LOGGER.log(Level.SEVERE, "Error retrieving contract types"); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + result = Formats.format(contentType, typeList, LookupType.class); + ctx.result(result); + ctx.status(HttpServletResponse.SC_OK); + } + + @OpenApi( + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = "204", description = "Contract type successfully stored to CWMS."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Create a new water contract type", + method = HttpMethod.POST, + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}/types", + tags = {TAG} + ) + + @Override + public void create(@NotNull Context ctx){ + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); + ctx.contentType(contentType.toString()); + LookupType contractType = Formats.parseContent(contentType, ctx.body(), LookupType.class); + List types = new ArrayList<>(); + types.add(contractType); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.storeWaterContractTypes(types, true); + ctx.status(HttpServletResponse.SC_CREATED).json("Contract type successfully stored to CWMS."); + } + + @OpenApi(ignore = true) + @Override + public void getOne(@NotNull Context ctx, @NotNull String id){ + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi(ignore = true) + @Override + public void update(@NotNull Context ctx, @NotNull String oldName){ + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi(ignore = true) + @Override + public void delete(@NotNull Context ctx, @NotNull String id){ + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + +} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java new file mode 100644 index 000000000..58498e25d --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java @@ -0,0 +1,139 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.errors.CdaError; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import io.javalin.apibuilder.CrudHandler; +import io.javalin.http.Context; +import io.javalin.http.HttpCode; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +public class WaterPumpController implements CrudHandler { + private static final Logger LOGGER = Logger.getLogger(WaterPumpController.class.getName()); + public static final String TAG = "Water Contracts"; + private static final String USAGE_ID = "usage-id"; + private static final String CONTRACT_NAME = "contract-name"; + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi(ignore = true) + @Override + public void getAll(@NotNull Context ctx) { + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi(ignore = true) + @Override + public void getOne(@NotNull Context ctx, @NotNull String id) { + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi(ignore = true) + @Override + public void create(@NotNull Context ctx) { + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi(ignore = true) + @Override + public void update(@NotNull Context ctx, @NotNull String id) { + ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = USAGE_ID, required = true, + description = "The pump usage id associated with the contract."), + @OpenApiParam(name = DELETE, type = boolean.class, required = true, + description = "Whether to delete the associated accounting data.") + }, + pathParams = { + @OpenApiParam(name = NAME, description = "The name of the pump to be " + + "removed from the specified contract.", required = true), + @OpenApiParam(name = OFFICE, description = "The office the project is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The name of the project.", required = true), + @OpenApiParam(name = CONTRACT_NAME, description = "The name of the contract the pump is associated with.", required = true), + }, + responses = { + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Delete a pump from a contract", + path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{office}/{contract-name}/pumps/{office}/{name}", + method = HttpMethod.DELETE, + tags = {TAG} + ) + + @Override + public void delete(@NotNull Context ctx, @NotNull String pumpLocationName) { + DSLContext dsl = getDslContext(ctx); + boolean deleteAccounting = Boolean.parseBoolean(ctx.queryParam(DELETE)); + String usageId = ctx.queryParam(USAGE_ID); + String officeId = ctx.pathParam(OFFICE); + String projectName = ctx.pathParam(PROJECT_ID); + String contractName = ctx.pathParam(CONTRACT_NAME); + WaterContractDao contractDao = getContractDao(dsl); + CwmsId projectLocation = new CwmsId.Builder().withName(projectName).withOfficeId(officeId).build(); + List contract = contractDao.getAllWaterContracts(projectLocation, contractName); + + if (contract.isEmpty()) { + CdaError error = new CdaError("No contract found for the provided name."); + LOGGER.log(Level.SEVERE, "No matching contract found."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + for (WaterUserContract waterUserContract : contract) { + if (waterUserContract.getContractId().getName().equals(contractName)) { + contractDao.removePumpFromContract(waterUserContract, pumpLocationName, usageId, deleteAccounting); + } + } + } + + + +} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java new file mode 100644 index 000000000..c18f64848 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java @@ -0,0 +1,261 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.errors.CdaError; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.watersupply.WaterUser; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import io.javalin.apibuilder.CrudHandler; +import io.javalin.core.util.Header; +import io.javalin.http.Context; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiContent; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +public class WaterUserController implements CrudHandler { + private static final Logger LOGGER = Logger.getLogger(WaterUserController.class.getName()); + public static final String TAG = "Water Contracts"; + + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = LOCATION_ID, description = "Specifies the parent location id of the contract.", required = true) + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = STATUS_200, + content = { + @OpenApiContent(type = Formats.JSONV1, from = WaterUserContract.class) + } + ) + }, + description = "Gets all water users.", + method = HttpMethod.GET, + path = "/projects/{office}/{project-id}/water-user", + tags = {TAG} + ) + + @Override + public void getAll(@NotNull Context ctx) { + DSLContext dsl = getDslContext(ctx); + String office = ctx.queryParam(OFFICE); + String locationId = ctx.queryParam(LOCATION_ID); + CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); + String result; + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterContractDao contractDao = getContractDao(dsl); + List users = contractDao.getAllWaterUsers(projectLocation); + + if (users.isEmpty()) { + CdaError error = new CdaError("No water users found for the provided parameters."); + LOGGER.log(Level.SEVERE, "Error retrieving all water users."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + result = Formats.format(contentType, users, WaterUserContract.class); + ctx.result(result); + ctx.status(HttpServletResponse.SC_OK); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location id of the contract.", required = true) + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = STATUS_200, + content = { + @OpenApiContent(type = Formats.JSONV1, from = WaterUserContract.class) + } + ) + }, + description = "Gets a specified water user.", + method = HttpMethod.GET, + path = "/projects/{office}/{project-id}/water-user", + tags = {TAG} + ) + + @Override + public void getOne(@NotNull Context ctx, @NotNull String entityName) { + String location = ctx.queryParam(LOCATION_ID); + CwmsId projectLocation = new CwmsId.Builder().withOfficeId(ctx.queryParam(OFFICE)).withName(location).build(); + DSLContext dsl = getDslContext(ctx); + String result; + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterContractDao contractDao = getContractDao(dsl); + WaterUser user = contractDao.getWaterUser(projectLocation, entityName); + + if (user == null) { + CdaError error = new CdaError("No water user found for the provided parameters."); + LOGGER.log(Level.SEVERE, "Error retrieving water user."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + List params = new ArrayList<>(); + params.add(user); + result = Formats.format(contentType, params, WaterUserContract.class); + ctx.result(result); + ctx.status(HttpServletResponse.SC_OK); + } + + @OpenApi( + responses = { + @OpenApiResponse(status = STATUS_204, description = "Water user successfully stored to CWMS."), + @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) + }, + description = "Stores a water user to CWMS.", + method = HttpMethod.POST, + path = "/projects/{office}/{project-id}/water-user", + tags = {TAG} + ) + @Override + public void create(@NotNull Context ctx) { + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + WaterUser user = Formats.parseContent(contentType, ctx.body(), WaterUser.class); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.storeWaterUser(user, true); + ctx.status(HttpServletResponse.SC_CREATED).json(user.getEntityName() + " user created successfully."); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = NAME, description = "Specifies the" + + " new name of the water user entity.", required = true), + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location id of the contract.", required = true) + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = STATUS_204, description = "Water user successfully updated in CWMS."), + @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") + }, + description = "Updates a water user in CWMS.", + method = HttpMethod.PATCH, + path = "/projects/{office}/{project-id}/water-user/{water-user}", + tags = {TAG} + ) + @Override + public void update(@NotNull Context ctx, @NotNull String oldName) { + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); + ctx.contentType(contentType.toString()); + String newName = ctx.queryParam(NAME); + String office = ctx.queryParam(OFFICE); + String locationId = ctx.queryParam(LOCATION_ID); + CwmsId location = new CwmsId.Builder().withName(locationId).withOfficeId(office).build(); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.renameWaterUser(oldName, newName, location); + ctx.status(HttpServletResponse.SC_OK).json("Water user renamed successfully."); + + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = OFFICE, description = "Specifies the" + + " office that the contract is associated with.", required = true), + @OpenApiParam(name = LOCATION_ID, description = + "Specifies the parent location id of the contract.", required = true), + @OpenApiParam(name = DELETE_MODE, description = "Specifies the delete method used."), + }, + pathParams = { + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) + }, + responses = { + @OpenApiResponse(status = STATUS_204, description = "Water user successfully deleted from CWMS."), + @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") + }, + description = "Deletes a water user from CWMS.", + method = HttpMethod.DELETE, + path = "/projects/{office}/{project-id}/water-user/{water-user}", + tags = {TAG} + ) + @Override + public void delete(@NotNull Context ctx, @NotNull String entityName) { + DSLContext dsl = getDslContext(ctx); + String office = ctx.queryParam(OFFICE); + String locationId = ctx.queryParam(LOCATION_ID); + String deleteMode = ctx.queryParam(DELETE_MODE); + CwmsId location = new CwmsId.Builder().withName(locationId).withOfficeId(office).build(); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.deleteWaterUser(location, entityName, deleteMode); + ctx.status(HttpServletResponse.SC_OK).json("Water user deleted successfully."); + } +} From 68cbcb99ca3833a3c0e374b7dbfc767657b379fe Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Fri, 12 Jul 2024 11:27:14 -0700 Subject: [PATCH 15/39] Controllers working, testing still in progress --- .../cwms/cda/api/WaterContractController.java | 308 ------- .../cda/api/WaterContractTypeController.java | 163 ---- .../cwms/cda/api/WaterPumpController.java | 139 ---- .../cwms/cda/api/WaterUserController.java | 261 ------ .../WaterContractTypeController.java | 106 +++ .../WaterPumpDeleteController.java | 158 ++++ .../WaterContractTypeControllerTestIT.java | 116 +++ .../api/WaterPumpDeleteControllerTestIT.java | 769 ++++++++++++++++++ .../WaterUserContractControllerTestIT.java | 354 ++++++++ 9 files changed, 1503 insertions(+), 871 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java create mode 100644 cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java deleted file mode 100644 index 76997cfd3..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractController.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.errors.CdaError; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.data.dto.watersupply.WaterUserContractRef; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import io.javalin.apibuilder.CrudHandler; -import io.javalin.core.util.Header; -import io.javalin.http.Context; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiContent; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; - -import javax.servlet.http.HttpServletResponse; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -public class WaterContractController implements CrudHandler { - private final Logger LOGGER = Logger.getLogger(WaterContractController.class.getName()); - public static final String TAG = "Water Contracts"; - private static final String WATER_USER = "water-user"; - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi( - queryParams = { - - @OpenApiParam(name = NAME, description = "Specifies the name of the contract.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location id of the contract.", required = true), - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "Specifies the project id of the contract.", required = true), - @OpenApiParam(name = WATER_USER, description = "Specifies the water user of the contract.", required = true), - }, - responses = { - @OpenApiResponse(status = STATUS_200, - content = { - @OpenApiContent(from = WaterUserContract.class, type = Formats.JSONV1), - @OpenApiContent(from = WaterUserContract.class, type = Formats.JSON) - }), - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Return all water contracts", - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}", - method = HttpMethod.GET, - tags = {TAG} - ) - @Override - public void getAll(@NotNull Context ctx) { - final String office = ctx.queryParam("office"); - final String name = ctx.queryParam("name"); - final String locationId = ctx.queryParam("locationId"); - DSLContext dsl = getDslContext(ctx); - String result; - CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterContractDao contractDao = getContractDao(dsl); - List contracts = contractDao.getAllWaterContracts(projectLocation, name); - - if (contracts.isEmpty()) { - CdaError error = new CdaError("No contracts found for the provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving all contracts"); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - result = Formats.format(contentType, contracts, WaterUserContract.class); - ctx.result(result); - ctx.status(HttpServletResponse.SC_OK); - } - - - @OpenApi( - queryParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = NAME, description = "Specifies the name of the contract.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location id of the contract.", required = true), - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = STATUS_200, - content = { - @OpenApiContent(from = WaterUserContract.class, type = Formats.JSONV1), - @OpenApiContent(from = WaterUserContract.class, type = Formats.JSON) - }), - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Return a specified water contract", - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", - method = HttpMethod.GET, - tags = {TAG} - ) - - @Override - public void getOne(@NotNull Context ctx, @NotNull String contractName){ - final String office = ctx.queryParam("office"); - final String name = ctx.queryParam("name"); - final String locationId = ctx.queryParam("locationId"); - DSLContext dsl = getDslContext(ctx); - String result; - CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterContractDao contractDao = getContractDao(dsl); - List contracts = contractDao.getAllWaterContracts(projectLocation, name); - - if (contracts.isEmpty()) { - CdaError error = new CdaError("No contracts found for the provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving contracts"); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - for (WaterUserContract contract : contracts) { - if (contract.getContractId().getName().equals(contractName)) { - contracts.clear(); - contracts.add(contract); - result = Formats.format(contentType, contracts, WaterUserContract.class); - ctx.result(result); - ctx.status(HttpServletResponse.SC_OK); - return; - } - } - CdaError error = new CdaError("No contract found for the provided name."); - LOGGER.log(Level.SEVERE, "Error retrieving contract"); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - } - - - @OpenApi( - responses = { - @OpenApiResponse(status = "204", description = "Basin successfully stored to CWMS."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - description = "Create a new water contract", - method = HttpMethod.POST, - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts", - tags = {TAG} - ) - - @Override - public void create(@NotNull Context ctx){ - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterUserContract waterContract = Formats.parseContent(contentType, ctx.body(), WaterUserContract.class); - - String newContractName = waterContract.getContractId().getName(); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.storeWaterContract(waterContract, true, false); - ctx.status(HttpServletResponse.SC_CREATED).json(newContractName + " created successfully"); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = NAME, description = "Specifies the new name of the contract.", required = true) - }, - pathParams = { - @OpenApiParam(name = "contractName", description = "Specifies the name of the contract to be renamed.", required = true), - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = "404", description = "The provided combination of " - + "parameters did not find a contract"), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Renames a water contract", - method = HttpMethod.PATCH, - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", - tags = {TAG} - ) - - @Override - public void update(@NotNull Context ctx, @NotNull String contractName){ - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - String newName = ctx.queryParam(NAME); - WaterUserContract waterContract = Formats.parseContent(contentType, ctx.body(), WaterUserContract.class); - WaterContractDao contractDao = getContractDao(dsl); - WaterUserContractRef ref = new WaterUserContractRef(waterContract.getWaterUser(), - waterContract.getContractId().getName()); - contractDao.renameWaterContract(ref, contractName, newName); - ctx.status(HttpServletResponse.SC_OK).json("Contract renamed successfully"); - } - - - @OpenApi( - queryParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location for the contract.", required = true), - @OpenApiParam(name = DELETE_MODE, description = "Specifies the delete method used."), - }, - pathParams = { - @OpenApiParam(name = NAME, description = "The name of the contract to be deleted."), - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Delete a specified water contract", - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}", - method = HttpMethod.DELETE, - tags = {TAG} - ) - - @Override - public void delete(@NotNull Context ctx, @NotNull String contractName){ - - DSLContext dsl = getDslContext(ctx); - String deleteMethod = ctx.queryParam(DELETE_MODE); - String locationId = ctx.queryParam(LOCATION_ID); - String office = ctx.queryParam(OFFICE); - WaterContractDao contractDao = getContractDao(dsl); - CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); - - List retContracts = contractDao.getAllWaterContracts(projectLocation, contractName); - - if (retContracts.isEmpty()) { - CdaError error = new CdaError("No contract found for the provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving contracts"); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - for (WaterUserContract contract : retContracts) { - if (contract.getContractId().getName().equals(contractName)) { - contractDao.deleteWaterContract(contract, deleteMethod); - ctx.status(HttpServletResponse.SC_NO_CONTENT).json(contractName + " deleted successfully"); - return; - } - } - CdaError error = new CdaError("No contract found for the provided name."); - LOGGER.log(Level.SEVERE, "No matching contract found for deletion."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java deleted file mode 100644 index 34d9a3355..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/WaterContractTypeController.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.errors.CdaError; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.LookupType; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import io.javalin.apibuilder.CrudHandler; -import io.javalin.core.util.Header; -import io.javalin.http.Context; -import io.javalin.http.HttpCode; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiContent; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; -import usace.cwms.db.dao.ifc.watersupply.WaterUserContractType; - -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -public class WaterContractTypeController implements CrudHandler { - private static final Logger LOGGER = Logger.getLogger(WaterContractTypeController.class.getName()); - public static final String TAG = "Water Contracts"; - - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi ( - queryParams = { - @OpenApiParam(name = OFFICE, required = true, - description = "The office Id the contract is associated with.") - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = "200", content = { - @OpenApiContent(from = WaterUserContractType.class, type = Formats.JSONV1), - @OpenApiContent(from = WaterUserContractType.class, type = Formats.JSON) - }), - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Get all water contract types", - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}/types", - method = HttpMethod.GET, - tags = {TAG} - ) - - @Override - public void getAll(@NotNull Context ctx){ - String officeId = ctx.queryParam(OFFICE); - DSLContext dsl = getDslContext(ctx); - String result; - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); - ctx.contentType(contentType.toString()); - WaterContractDao dao = getContractDao(dsl); - List typeList = dao.getAllWaterContractTypes(officeId); - - if (typeList.isEmpty()) { - CdaError error = new CdaError("No contract types found for office: " + officeId); - LOGGER.log(Level.SEVERE, "Error retrieving contract types"); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - result = Formats.format(contentType, typeList, LookupType.class); - ctx.result(result); - ctx.status(HttpServletResponse.SC_OK); - } - - @OpenApi( - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = "204", description = "Contract type successfully stored to CWMS."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Create a new water contract type", - method = HttpMethod.POST, - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{office}/{project-id}/types", - tags = {TAG} - ) - - @Override - public void create(@NotNull Context ctx){ - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); - ctx.contentType(contentType.toString()); - LookupType contractType = Formats.parseContent(contentType, ctx.body(), LookupType.class); - List types = new ArrayList<>(); - types.add(contractType); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.storeWaterContractTypes(types, true); - ctx.status(HttpServletResponse.SC_CREATED).json("Contract type successfully stored to CWMS."); - } - - @OpenApi(ignore = true) - @Override - public void getOne(@NotNull Context ctx, @NotNull String id){ - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi(ignore = true) - @Override - public void update(@NotNull Context ctx, @NotNull String oldName){ - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi(ignore = true) - @Override - public void delete(@NotNull Context ctx, @NotNull String id){ - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - -} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java deleted file mode 100644 index 58498e25d..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/WaterPumpController.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.errors.CdaError; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import io.javalin.apibuilder.CrudHandler; -import io.javalin.http.Context; -import io.javalin.http.HttpCode; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; - -import javax.servlet.http.HttpServletResponse; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -public class WaterPumpController implements CrudHandler { - private static final Logger LOGGER = Logger.getLogger(WaterPumpController.class.getName()); - public static final String TAG = "Water Contracts"; - private static final String USAGE_ID = "usage-id"; - private static final String CONTRACT_NAME = "contract-name"; - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi(ignore = true) - @Override - public void getAll(@NotNull Context ctx) { - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi(ignore = true) - @Override - public void getOne(@NotNull Context ctx, @NotNull String id) { - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi(ignore = true) - @Override - public void create(@NotNull Context ctx) { - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi(ignore = true) - @Override - public void update(@NotNull Context ctx, @NotNull String id) { - ctx.status(HttpCode.NOT_IMPLEMENTED).json(CdaError.notImplemented()); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = USAGE_ID, required = true, - description = "The pump usage id associated with the contract."), - @OpenApiParam(name = DELETE, type = boolean.class, required = true, - description = "Whether to delete the associated accounting data.") - }, - pathParams = { - @OpenApiParam(name = NAME, description = "The name of the pump to be " - + "removed from the specified contract.", required = true), - @OpenApiParam(name = OFFICE, description = "The office the project is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The name of the project.", required = true), - @OpenApiParam(name = CONTRACT_NAME, description = "The name of the contract the pump is associated with.", required = true), - }, - responses = { - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Delete a pump from a contract", - path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{office}/{contract-name}/pumps/{office}/{name}", - method = HttpMethod.DELETE, - tags = {TAG} - ) - - @Override - public void delete(@NotNull Context ctx, @NotNull String pumpLocationName) { - DSLContext dsl = getDslContext(ctx); - boolean deleteAccounting = Boolean.parseBoolean(ctx.queryParam(DELETE)); - String usageId = ctx.queryParam(USAGE_ID); - String officeId = ctx.pathParam(OFFICE); - String projectName = ctx.pathParam(PROJECT_ID); - String contractName = ctx.pathParam(CONTRACT_NAME); - WaterContractDao contractDao = getContractDao(dsl); - CwmsId projectLocation = new CwmsId.Builder().withName(projectName).withOfficeId(officeId).build(); - List contract = contractDao.getAllWaterContracts(projectLocation, contractName); - - if (contract.isEmpty()) { - CdaError error = new CdaError("No contract found for the provided name."); - LOGGER.log(Level.SEVERE, "No matching contract found."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - for (WaterUserContract waterUserContract : contract) { - if (waterUserContract.getContractId().getName().equals(contractName)) { - contractDao.removePumpFromContract(waterUserContract, pumpLocationName, usageId, deleteAccounting); - } - } - } - - - -} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java b/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java deleted file mode 100644 index c18f64848..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/WaterUserController.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.errors.CdaError; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.watersupply.WaterUser; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import io.javalin.apibuilder.CrudHandler; -import io.javalin.core.util.Header; -import io.javalin.http.Context; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiContent; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; - -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -public class WaterUserController implements CrudHandler { - private static final Logger LOGGER = Logger.getLogger(WaterUserController.class.getName()); - public static final String TAG = "Water Contracts"; - - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = LOCATION_ID, description = "Specifies the parent location id of the contract.", required = true) - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = STATUS_200, - content = { - @OpenApiContent(type = Formats.JSONV1, from = WaterUserContract.class) - } - ) - }, - description = "Gets all water users.", - method = HttpMethod.GET, - path = "/projects/{office}/{project-id}/water-user", - tags = {TAG} - ) - - @Override - public void getAll(@NotNull Context ctx) { - DSLContext dsl = getDslContext(ctx); - String office = ctx.queryParam(OFFICE); - String locationId = ctx.queryParam(LOCATION_ID); - CwmsId projectLocation = new CwmsId.Builder().withOfficeId(office).withName(locationId).build(); - String result; - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterContractDao contractDao = getContractDao(dsl); - List users = contractDao.getAllWaterUsers(projectLocation); - - if (users.isEmpty()) { - CdaError error = new CdaError("No water users found for the provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving all water users."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - result = Formats.format(contentType, users, WaterUserContract.class); - ctx.result(result); - ctx.status(HttpServletResponse.SC_OK); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location id of the contract.", required = true) - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = STATUS_200, - content = { - @OpenApiContent(type = Formats.JSONV1, from = WaterUserContract.class) - } - ) - }, - description = "Gets a specified water user.", - method = HttpMethod.GET, - path = "/projects/{office}/{project-id}/water-user", - tags = {TAG} - ) - - @Override - public void getOne(@NotNull Context ctx, @NotNull String entityName) { - String location = ctx.queryParam(LOCATION_ID); - CwmsId projectLocation = new CwmsId.Builder().withOfficeId(ctx.queryParam(OFFICE)).withName(location).build(); - DSLContext dsl = getDslContext(ctx); - String result; - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterContractDao contractDao = getContractDao(dsl); - WaterUser user = contractDao.getWaterUser(projectLocation, entityName); - - if (user == null) { - CdaError error = new CdaError("No water user found for the provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving water user."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - List params = new ArrayList<>(); - params.add(user); - result = Formats.format(contentType, params, WaterUserContract.class); - ctx.result(result); - ctx.status(HttpServletResponse.SC_OK); - } - - @OpenApi( - responses = { - @OpenApiResponse(status = STATUS_204, description = "Water user successfully stored to CWMS."), - @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true) - }, - description = "Stores a water user to CWMS.", - method = HttpMethod.POST, - path = "/projects/{office}/{project-id}/water-user", - tags = {TAG} - ) - @Override - public void create(@NotNull Context ctx) { - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - WaterUser user = Formats.parseContent(contentType, ctx.body(), WaterUser.class); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.storeWaterUser(user, true); - ctx.status(HttpServletResponse.SC_CREATED).json(user.getEntityName() + " user created successfully."); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = NAME, description = "Specifies the" - + " new name of the water user entity.", required = true), - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location id of the contract.", required = true) - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = STATUS_204, description = "Water user successfully updated in CWMS."), - @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") - }, - description = "Updates a water user in CWMS.", - method = HttpMethod.PATCH, - path = "/projects/{office}/{project-id}/water-user/{water-user}", - tags = {TAG} - ) - @Override - public void update(@NotNull Context ctx, @NotNull String oldName) { - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, WaterUserContract.class); - ctx.contentType(contentType.toString()); - String newName = ctx.queryParam(NAME); - String office = ctx.queryParam(OFFICE); - String locationId = ctx.queryParam(LOCATION_ID); - CwmsId location = new CwmsId.Builder().withName(locationId).withOfficeId(office).build(); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.renameWaterUser(oldName, newName, location); - ctx.status(HttpServletResponse.SC_OK).json("Water user renamed successfully."); - - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = OFFICE, description = "Specifies the" - + " office that the contract is associated with.", required = true), - @OpenApiParam(name = LOCATION_ID, description = - "Specifies the parent location id of the contract.", required = true), - @OpenApiParam(name = DELETE_MODE, description = "Specifies the delete method used."), - }, - pathParams = { - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = STATUS_204, description = "Water user successfully deleted from CWMS."), - @OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented") - }, - description = "Deletes a water user from CWMS.", - method = HttpMethod.DELETE, - path = "/projects/{office}/{project-id}/water-user/{water-user}", - tags = {TAG} - ) - @Override - public void delete(@NotNull Context ctx, @NotNull String entityName) { - DSLContext dsl = getDslContext(ctx); - String office = ctx.queryParam(OFFICE); - String locationId = ctx.queryParam(LOCATION_ID); - String deleteMode = ctx.queryParam(DELETE_MODE); - CwmsId location = new CwmsId.Builder().withName(locationId).withOfficeId(office).build(); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.deleteWaterUser(location, entityName, deleteMode); - ctx.status(HttpServletResponse.SC_OK).json("Water user deleted successfully."); - } -} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java new file mode 100644 index 000000000..797008f71 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java @@ -0,0 +1,106 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api.watersupply; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.Timer; +import cwms.cda.api.Controllers; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import io.javalin.core.util.Header; +import io.javalin.http.Context; +import io.javalin.http.Handler; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import java.util.ArrayList; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; + + +public class WaterContractTypeController implements Handler { + public static final String TAG = "Water Contracts"; + private final MetricRegistry metrics; + + private Timer.Context markAndTime(String subject) { + return Controllers.markAndTime(metrics, getClass().getName(), subject); + } + + public WaterContractTypeController(MetricRegistry metrics) { + this.metrics = metrics; + } + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi( + pathParams = { + @OpenApiParam(name = NAME, description = "The name of the contract.", required = true), + @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", + required = true), + @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", + required = true), + @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", + required = true) + }, + responses = { + @OpenApiResponse(status = "204", description = "Contract type successfully stored to CWMS."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Create a new water contract type", + method = HttpMethod.POST, + path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{name}/types", + tags = {TAG} + ) + + @Override + public void handle(@NotNull Context ctx) { + try (Timer.Context ignored = markAndTime(CREATE)) { + DSLContext dsl = getDslContext(ctx); + String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; + ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); + ctx.contentType(contentType.toString()); + LookupType contractType = Formats.parseContent(contentType, ctx.body(), LookupType.class); + List types = new ArrayList<>(); + types.add(contractType); + WaterContractDao contractDao = getContractDao(dsl); + contractDao.storeWaterContractTypes(types, true); + ctx.status(HttpServletResponse.SC_CREATED).json("Contract type successfully stored to CWMS."); + } + } + +} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java new file mode 100644 index 000000000..e09f40198 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java @@ -0,0 +1,158 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api.watersupply; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.data.dao.JooqDao.getDslContext; + +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.Timer; +import cwms.cda.api.Controllers; +import cwms.cda.api.errors.CdaError; +import cwms.cda.data.dao.watersupply.WaterContractDao; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import io.javalin.http.Context; +import io.javalin.http.Handler; +import io.javalin.plugin.openapi.annotations.HttpMethod; +import io.javalin.plugin.openapi.annotations.OpenApi; +import io.javalin.plugin.openapi.annotations.OpenApiParam; +import io.javalin.plugin.openapi.annotations.OpenApiResponse; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.http.HttpServletResponse; +import org.jetbrains.annotations.NotNull; +import org.jooq.DSLContext; + + +public class WaterPumpDeleteController implements Handler { + private static final Logger LOGGER = Logger.getLogger(WaterPumpDeleteController.class.getName()); + public static final String TAG = "Water Contracts"; + private static final String USAGE_ID = "usage-id"; + private static final String CONTRACT_NAME = "contract-name"; + private static final String PUMP_TYPE = "pump-type"; + private final MetricRegistry metrics; + + private Timer.Context markAndTime(String subject) { + return Controllers.markAndTime(metrics, getClass().getName(), subject); + } + + public WaterPumpDeleteController(MetricRegistry metrics) { + this.metrics = metrics; + } + + @NotNull + protected WaterContractDao getContractDao(DSLContext dsl) { + return new WaterContractDao(dsl); + } + + @OpenApi( + queryParams = { + @OpenApiParam(name = USAGE_ID, required = true, + description = "The pump usage id associated with the contract."), + @OpenApiParam(name = PUMP_TYPE, required = true, + description = "The type of pump to be removed from the contract." + + " Expected values: IN, OUT, OUT BELOW"), + @OpenApiParam(name = DELETE, type = boolean.class, required = true, + description = "Whether to delete the associated accounting data.") + }, + pathParams = { + @OpenApiParam(name = NAME, description = "The name of the pump to be " + + "removed from the specified contract.", required = true), + @OpenApiParam(name = OFFICE, description = "The office the project is associated with.", required = true), + @OpenApiParam(name = PROJECT_ID, description = "The name of the project.", required = true), + @OpenApiParam(name = CONTRACT_NAME, description = "The name of the contract the pump is associated with.", + required = true), + }, + responses = { + @OpenApiResponse(status = "404", description = "The provided combination of parameters" + + " did not find any contracts."), + @OpenApiResponse(status = "501", description = "Requested format is not implemented.") + }, + description = "Delete a pump from a contract", + path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{office}/{contract-name}" + + "/pumps/{office}/{name}", + method = HttpMethod.DELETE, + tags = {TAG} + ) + + @Override + public void handle(@NotNull Context ctx) { + try (Timer.Context ignored = markAndTime(DELETE)) { + DSLContext dsl = getDslContext(ctx); + boolean deleteAccounting = Boolean.parseBoolean(ctx.queryParam(DELETE)); + String usageId = ctx.queryParam(USAGE_ID); + String officeId = ctx.pathParam(OFFICE); + String projectName = ctx.pathParam(PROJECT_ID); + String contractName = ctx.pathParam(CONTRACT_NAME); + String pumpType = ctx.queryParam(PUMP_TYPE); + assert pumpType != null; + WaterContractDao contractDao = getContractDao(dsl); + CwmsId projectLocation = new CwmsId.Builder().withName(projectName).withOfficeId(officeId).build(); + List contract = contractDao.getAllWaterContracts(projectLocation, contractName); + + if (contract.isEmpty()) { + CdaError error = new CdaError("No contract found for the provided name."); + LOGGER.log(Level.SEVERE, "No matching contract found."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + for (WaterUserContract waterUserContract : contract) { + if (waterUserContract.getContractId().getName().equals(contractName)) { + switch (pumpType) { + case "IN": + contractDao.removePumpFromContract(waterUserContract, + waterUserContract.getPumpInLocation().getPumpLocation().getName(), + usageId, deleteAccounting); + break; + case "OUT": + contractDao.removePumpFromContract(waterUserContract, + waterUserContract.getPumpOutLocation().getPumpLocation().getName(), + usageId, deleteAccounting); + break; + case "OUT BELOW": + contractDao.removePumpFromContract(waterUserContract, + waterUserContract.getPumpOutBelowLocation().getPumpLocation().getName(), + usageId, deleteAccounting); + break; + default: + CdaError error = new CdaError("Invalid pump type provided."); + LOGGER.log(Level.SEVERE, "Invalid pump type provided."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); + return; + } + + } + } + } + } + + + +} diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java new file mode 100644 index 000000000..36e39fef0 --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java @@ -0,0 +1,116 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.watersupply.WaterContractController; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import fixtures.TestAccounts; +import io.restassured.filter.log.LogDetail; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletResponse; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + +@Tag("integration") +class WaterContractTypeControllerTestIT extends DataApiTestIT { + private static final String OFFICE_ID = "SPK"; + private static final WaterUserContract CONTRACT; + static { + try (InputStream contractStream = WaterContractController.class.getResourceAsStream("/cwms/cda/api/waterusercontract.json")){ + assert contractStream != null; + String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); + CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); + } catch(Exception ex) { + throw new RuntimeException(ex); + } + } + + @Test + void test_create_get_WaterContractType() { + // Test Structure + // 1) Create a WaterContractType + // 2) Get the WaterContractType, assert it exists + + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); + + // create water contract type + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + // get water contract type and assert that it exists + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .pathParam(OFFICE, OFFICE_ID) + .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName() + "/types") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + .body("office-id", equalTo(OFFICE_ID)) + .body("display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) + .body("tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) + .body("active", equalTo(CONTRACT.getWaterContract().getActive())) + ; + + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java new file mode 100644 index 000000000..a9e577d6a --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -0,0 +1,769 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.enums.Nation; +import cwms.cda.api.watersupply.WaterContractController; +import cwms.cda.data.dao.JooqDao.DeleteMethod; +import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import fixtures.TestAccounts; +import io.restassured.filter.log.LogDetail; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.ZoneId; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + +@Tag("integration") +class WaterPumpDeleteControllerTestIT extends DataApiTestIT { + private static final String USAGE_ID = "usage-id"; + private static final String OFFICE_ID = "SPK"; + private static final WaterUserContract CONTRACT; + private static final WaterUserContract CONTRACT_NO_PUMP; + private static final String CONTRACT_NAME = "contract-name"; + static { + try ( + InputStream contractStream = WaterContractController.class + .getResourceAsStream("/cwms/cda/api/waterusercontract.json"); + InputStream contractStreamNoPump = WaterContractController.class + .getResourceAsStream("/cwms/cda/api/waterusercontract_no_pump.json") + ) { + assert contractStream != null; + assert contractStreamNoPump != null; + String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); + String contractJsonNoPump = IOUtils.toString(contractStreamNoPump, StandardCharsets.UTF_8); + CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); + CONTRACT_NO_PUMP = Formats.parseContent(new ContentType(Formats.JSONV1), contractJsonNoPump, + WaterUserContract.class); + } catch(Exception ex) { + throw new RuntimeException(ex); + } + } + + @BeforeAll + static void setUp() { + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + + Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), + CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) + .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).withDescription("Contract Location") + .withBoundingOfficeId("SPK").withNearestCity("Sacramento").withStateInitial("CA") + .withCountyName("Sacramento").withTimeZoneName(ZoneId.of("UTC")) + .withLocationType("WATER PROJECT").withPublicName("TEST WATER PROJECT").withPublishedLatitude(89.7) + .withPublishedLongitude(56.9).withElevation(459.1).withElevationUnits("m").withNation(Nation.US) + .withMapLabel("PLACE").withVerticalDatum("WGS84").withActive(true).withLongName("FULL TEST").build(); + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId(), + CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") + .withLongitude(38.0).withLatitude(56.5).build(); + + + String json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), contractLocation); + + // create contract location + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .accept(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/locations") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + json = Formats.format(Formats.parseHeader(Formats.JSON, Location.class), parentLocation); + + // create parent site location + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSON) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/locations") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); + + // create contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(FAIL_IF_EXISTS, "true") + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/PROJECT/water-users/SPK/contracts") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_CREATED)) + .body("office-id", equalTo(CONTRACT.getOfficeId())) + .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) + .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() + .getParentLocationRef().getOfficeId())) + .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser() + .getParentLocationRef().getName())) + .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) + .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) + .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) + .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) + .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) + .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) + .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) + .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) + .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) + .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) + .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) + .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) + .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) + .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getOfficeId())) + .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getName())) + .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLatitude())) + .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLongitude())) + .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getActive())) + .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublicName())) + .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLongName())) + .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getDescription())) + .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLocationType())) + .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLocationKind())) + .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getNation())) + .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getStateInitial())) + .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getCountyName())) + .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getNearestCity())) + .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getHorizontalDatum())) + .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLatitude())) + .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLongitude())) + .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getVerticalDatum())) + .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getElevation())) + .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getMapLabel())) + .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getBoundingOfficeId())) + .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getElevationUnits())) + .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getOfficeId())) + .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getName())) + .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLatitude())) + .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLongitude())) + .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getActive())) + .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getPublicName())) + .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLongName())) + .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getDescription())) + .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLocationType())) + .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLocationKind())) + .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getNation())) + .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getStateInitial())) + .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getCountyName())) + .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getNearestCity())) + .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getElevation())) + .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getMapLabel())) + .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) + .body("pump-in-location.pump-location.office-id", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getOfficeId())) + .body("pump-in-location.pump-location.name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() + .getName())) + .body("pump-in-location.pump-location.latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() + .getLatitude())) + .body("pump-in-location.pump-location.longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() + .getLongitude())) + .body("pump-in-location.pump-location.active", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() + .getActive())) + .body("pump-in-location.pump-location.public-name", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getPublicName())) + .body("pump-in-location.pump-location.long-name", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getLongName())) + .body("pump-in-location.pump-location.description", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getDescription())) + .body("pump-in-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-in-location.pump-location.location-type", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getLocationType())) + .body("pump-in-location.pump-location.location-kind", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getLocationKind())) + .body("pump-in-location.pump-location.nation", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getNation())) + .body("pump-in-location.pump-location.state-initial", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getStateInitial())) + .body("pump-in-location.pump-location.county-name", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getCountyName())) + .body("pump-in-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getNearestCity())) + .body("pump-in-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getHorizontalDatum())) + .body("pump-in-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getPublishedLatitude())) + .body("pump-in-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getPublishedLongitude())) + .body("pump-in-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getVerticalDatum())) + .body("pump-in-location.pump-location.elevation", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getElevation())) + .body("pump-in-location.pump-location.map-label", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getMapLabel())) + .body("pump-in-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getBoundingOfficeId())) + .body("pump-in-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpInLocation() + .getPumpLocation().getElevationUnits())) + ; + + String json_no_pump = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), + CONTRACT_NO_PUMP); + + // Create contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json_no_pump) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(FAIL_IF_EXISTS, "false") + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/SPK/PROJECT/water-users/WATERUSER/contracts") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + .body("office-id", equalTo(CONTRACT_NO_PUMP.getOfficeId())) + .body("water-user.entity-name", equalTo(CONTRACT_NO_PUMP.getWaterUser().getEntityName())) + .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT_NO_PUMP.getWaterUser() + .getParentLocationRef().getOfficeId())) + .body("water-user.parent-location-ref.name", equalTo(CONTRACT_NO_PUMP.getWaterUser() + .getParentLocationRef().getName())) + .body("water-user.water-right", equalTo(CONTRACT_NO_PUMP.getWaterUser().getWaterRight())) + .body("water-contract.office-id", equalTo(CONTRACT_NO_PUMP.getWaterContract().getOfficeId())) + .body("water-contract.display-value", equalTo(CONTRACT_NO_PUMP.getWaterContract().getDisplayValue())) + .body("water-contract.tooltip", equalTo(CONTRACT_NO_PUMP.getWaterContract().getTooltip())) + .body("water-contract.active", equalTo(CONTRACT_NO_PUMP.getWaterContract().getActive())) + .body("contract-effective-date", equalTo(CONTRACT_NO_PUMP.getContractEffectiveDate())) + .body("contract-expiration-date", equalTo(CONTRACT_NO_PUMP.getContractExpirationDate())) + .body("contracted-storage", equalTo(CONTRACT_NO_PUMP.getContractedStorage())) + .body("initial-use-allocation", equalTo(CONTRACT_NO_PUMP.getInitialUseAllocation())) + .body("future-use-allocation", equalTo(CONTRACT_NO_PUMP.getFutureUseAllocation())) + .body("storage-units-id", equalTo(CONTRACT_NO_PUMP.getStorageUnitsId())) + .body("future-use-percent-activated", equalTo(CONTRACT_NO_PUMP.getFutureUsePercentActivated())) + .body("total-alloc-percent-activated", equalTo(CONTRACT_NO_PUMP.getTotalAllocPercentActivated())) + .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getOfficeId())) + .body("pump-out-location.pump-location.name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getName())) + .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getLatitude())) + .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getLongitude())) + .body("pump-out-location.pump-location.active", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getActive())) + .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getPublicName())) + .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getLongName())) + .body("pump-out-location.pump-location.description", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getDescription())) + .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getLocationType())) + .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getLocationKind())) + .body("pump-out-location.pump-location.nation", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getNation())) + .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getStateInitial())) + .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getCountyName())) + .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getNearestCity())) + .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getHorizontalDatum())) + .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT_NO_PUMP + .getPumpOutLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getElevation())) + .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getMapLabel())) + .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT_NO_PUMP + .getPumpOutLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() + .getPumpLocation().getElevationUnits())) + .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getOfficeId())) + .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT_NO_PUMP.getPumpOutBelowLocation() + .getPumpLocation().getName())) + .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getLatitude())) + .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getLongitude())) + .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getActive())) + .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getPublicName())) + .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getLongName())) + .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getDescription())) + .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getTimezoneName())) + .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getLocationType())) + .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getLocationKind())) + .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getNation())) + .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getStateInitial())) + .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getCountyName())) + .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getNearestCity())) + .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getElevation())) + .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getMapLabel())) + .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT_NO_PUMP + .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) + .body("pump-in-location", equalTo(null)) + ; + + + } + + @AfterAll + static void tearDown() throws Exception { + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + + Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), + CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) + .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).build(); + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId(), + CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") + .withLongitude(38.0).withLatitude(56.5).build(); + + String json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), contractLocation); + + // delete contract location + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(OFFICE, OFFICE_ID) + .queryParam(LOCATION_ID, contractLocation.getName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("locations") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), parentLocation); + + // delete parent site location + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(OFFICE, OFFICE_ID) + .queryParam(LOCATION_ID, parentLocation.getName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("locations") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); + + // delete contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(LOCATION_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .queryParam(DELETE_MODE, DeleteMethod.DELETE_ALL.toString()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + CONTRACT.getContractId().getOfficeId() + "/" + + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-users/" + CONTRACT.getWaterUser().getEntityName() + "/contracts" + + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + ; + + String json_no_pump = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), + CONTRACT_NO_PUMP); + + // delete contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json_no_pump) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(LOCATION_ID, CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()) + .queryParam(DELETE_MODE, DeleteMethod.DELETE_ALL.toString()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + CONTRACT_NO_PUMP.getContractId().getOfficeId() + "/" + + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() + + "/water-users/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts" + + CONTRACT_NO_PUMP.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + ; + + } + + @Test + void test_remove_from_contract() { + // Structure of test: + // 1) Remove the pump from the contract + // 2) Retrieve the contract and assert it does not contain the pump + + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + + // Remove pump and assert it is removed + given() + .log().ifValidationFails(LogDetail.ALL, true) + .pathParam(Controllers.OFFICE, OFFICE_ID) + .pathParam(Controllers.PROJECT_ID, CONTRACT.getContractId().getName()) + .pathParam(CONTRACT_NAME, CONTRACT.getWaterContract().getDisplayValue()) + .pathParam(NAME, CONTRACT.getPumpOutLocation().getPumpLocation().getName()) + .queryParam(USAGE_ID, "PUMP1") + .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getContractId().getName() + "/water-user/" + + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName()+ "/pumps/" + OFFICE_ID + "/" + + CONTRACT.getPumpInLocation().getPumpId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + ; + + // Retrieve contract and assert pump is removed + given() + .log().ifValidationFails(LogDetail.ALL, true) + .pathParam(Controllers.OFFICE, OFFICE_ID) + .pathParam(Controllers.PROJECT_ID, CONTRACT.getContractId().getName()) + .pathParam(CONTRACT_NAME, CONTRACT.getContractId().getName()) + .accept(Formats.JSONV1) + .when() + .redirects().follow(true) + .redirects().max(3) + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getContractId().getName() + "/water-user/" + + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + .body("office-id", equalTo(CONTRACT.getOfficeId())) + .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) + .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() + .getParentLocationRef().getOfficeId())) + .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef() + .getName())) + .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) + .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) + .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) + .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) + .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) + .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) + .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) + .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) + .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) + .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) + .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) + .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) + .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) + .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getOfficeId())) + .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation() + .getName())) + .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLatitude())) + .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLongitude())) + .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getActive())) + .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublicName())) + .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLongName())) + .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getDescription())) + .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLocationType())) + .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLocationKind())) + .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getNation())) + .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getStateInitial())) + .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getCountyName())) + .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getNearestCity())) + .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getHorizontalDatum())) + .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLatitude())) + .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLongitude())) + .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getVerticalDatum())) + .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getElevation())) + .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getMapLabel())) + .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getBoundingOfficeId())) + .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getElevationUnits())) + .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getOfficeId())) + .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getName())) + .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLatitude())) + .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLongitude())) + .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getActive())) + .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getPublicName())) + .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLongName())) + .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getDescription())) + .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getTimezoneName())) + .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLocationType())) + .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLocationKind())) + .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getNation())) + .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getStateInitial())) + .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getCountyName())) + .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getNearestCity())) + .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getElevation())) + .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getMapLabel())) + .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) + .body("pump-in-location", equalTo(null)) + ; + } + + @Test + void test_remove_does_not_exist() { + // Structure of test: + // 1) Remove a pump and assert that an error is thrown + // 2) Create a contract with an empty pump + // 3) Try to remove the pump and assert that an error is thrown + + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + + + // Remove pump + given() + .log().ifValidationFails(LogDetail.ALL, true) + .pathParam(Controllers.OFFICE, OFFICE_ID) + .pathParam(Controllers.PROJECT_ID, CONTRACT_NO_PUMP.getContractId().getName()) + .pathParam(CONTRACT_NAME, CONTRACT_NO_PUMP.getWaterContract().getDisplayValue()) + .pathParam(NAME, CONTRACT_NO_PUMP.getPumpOutLocation().getPumpLocation().getName()) + .queryParam(USAGE_ID, "PUMP1") + .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getContractId().getName() + "/water-user/" + + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT_NO_PUMP.getContractId().getName()+ "/pumps/" + OFFICE_ID + "/" + + CONTRACT_NO_PUMP.getPumpInLocation().getPumpId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)) + ; + + + // Remove pump + given() + .log().ifValidationFails(LogDetail.ALL, true) + .pathParam(Controllers.OFFICE, OFFICE_ID) + .pathParam(Controllers.PROJECT_ID, CONTRACT_NO_PUMP.getContractId().getName()) + .pathParam(CONTRACT_NAME, CONTRACT_NO_PUMP.getWaterContract().getDisplayValue()) + .pathParam(NAME, CONTRACT_NO_PUMP.getPumpOutLocation().getPumpLocation().getName()) + .queryParam(USAGE_ID, "PUMP1") + .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getContractId().getName() + "/water-user/" + + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT_NO_PUMP.getContractId().getName()+ "/pumps/" + + CONTRACT_NO_PUMP.getPumpInLocation().getPumpId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)) + ; + + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java new file mode 100644 index 000000000..607e7cbeb --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java @@ -0,0 +1,354 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.api; + +import cwms.cda.api.watersupply.WaterContractController; +import cwms.cda.data.dao.JooqDao; +import cwms.cda.data.dto.watersupply.WaterUserContract; +import cwms.cda.formatters.ContentType; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.json.JsonV1; +import fixtures.TestAccounts; +import io.restassured.filter.log.LogDetail; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import static cwms.cda.api.Controllers.*; +import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + + +@Tag("integration") +class WaterUserContractControllerTestIT extends DataApiTestIT { + private static final String OFFICE_ID = "SPK"; + private static final WaterUserContract CONTRACT; + static { + try (InputStream contractStream = WaterContractController.class.getResourceAsStream("/cwms/cda/api/waterusercontract.json")){ + assert contractStream != null; + String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); + CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); + } catch(Exception ex) { + throw new RuntimeException(ex); + } + } + + @BeforeAll + static void setup() throws Exception { + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT.getWaterUser()); + + // create water user + given() + .log().ifValidationFails(LogDetail.ALL, true) + .accept(Formats.JSONV1) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + } + + @AfterAll + static void tearDown() throws Exception { + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT.getWaterUser()); + + // create water user + given() + .log().ifValidationFails(LogDetail.ALL, true) + .accept(Formats.JSONV1) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + } + + @Test + void test_create_get_delete_WaterUserContract() { + // Test Structure: + // 1) Create a WaterUserContract + // 2) Get the WaterUserContract, assert that it is same as created contract + // 3) Delete the WaterUserContract + // 4) Get the WaterUserContract, assert that it is not found + + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); + + // Create contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(FAIL_IF_EXISTS, "true") + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_CREATED)) + ; + + // get contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .pathParam(OFFICE, CONTRACT.getOfficeId()) + .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + .body("office-id", equalTo(CONTRACT.getOfficeId())) + .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) + .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId())) + .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef().getName())) + .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) + .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) + .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) + .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) + .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) + .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) + .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) + .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) + .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) + .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) + .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) + .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) + .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) + .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getOfficeId())) + .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getName())) + .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLatitude())) + .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLongitude())) + .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getActive())) + .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublicName())) + .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLongName())) + .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getDescription())) + .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getTimezoneName())) + .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLocationType())) + .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLocationKind())) + .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getNation())) + .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getStateInitial())) + .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getCountyName())) + .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getNearestCity())) + .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getElevation())) + .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getMapLabel())) + .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getElevationUnits())) + .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getOfficeId())) + .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getName())) + .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLatitude())) + .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLongitude())) + .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getActive())) + .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublicName())) + .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLongName())) + .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getDescription())) + .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getTimezoneName())) + .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLocationType())) + .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLocationKind())) + .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getNation())) + .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getStateInitial())) + .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getCountyName())) + .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getNearestCity())) + .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) + .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getElevation())) + .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getMapLabel())) + .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) + .body("pump-in-location.pump-location.office-id", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getOfficeId())) + .body("pump-in-location.pump-location.name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getName())) + .body("pump-in-location.pump-location.latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLatitude())) + .body("pump-in-location.pump-location.longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLongitude())) + .body("pump-in-location.pump-location.active", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getActive())) + .body("pump-in-location.pump-location.public-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublicName())) + .body("pump-in-location.pump-location.long-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLongName())) + .body("pump-in-location.pump-location.description", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getDescription())) + .body("pump-in-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getTimezoneName())) + .body("pump-in-location.pump-location.location-type", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLocationType())) + .body("pump-in-location.pump-location.location-kind", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLocationKind())) + .body("pump-in-location.pump-location.nation", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getNation())) + .body("pump-in-location.pump-location.state-initial", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getStateInitial())) + .body("pump-in-location.pump-location.county-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getCountyName())) + .body("pump-in-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getNearestCity())) + .body("pump-in-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getHorizontalDatum())) + .body("pump-in-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublishedLatitude())) + .body("pump-in-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublishedLongitude())) + .body("pump-in-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getVerticalDatum())) + .body("pump-in-location.pump-location.elevation", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getElevation())) + .body("pump-in-location.pump-location.map-label", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getMapLabel())) + .body("pump-in-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getBoundingOfficeId())) + .body("pump-in-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getElevationUnits())) + ; + + // delete contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .pathParam(Controllers.OFFICE, OFFICE_ID) + .pathParam(Controllers.PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) + .pathParam(NAME, CONTRACT.getContractId().getName()) + .queryParam(DELETE_MODE, JooqDao.DeleteMethod.DELETE_ALL.toString()) + .queryParam(LOCATION_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .header(AUTH_HEADER, user.toHeaderValue()) + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + ; + + // get contract, assert that it doesn't exist + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .pathParam(OFFICE, CONTRACT.getOfficeId()) + .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NOT_FOUND)) + ; + } + + + @Test + void test_rename_WaterUserContract() { + + TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); + + // create contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(FAIL_IF_EXISTS, "true") + .when() + .redirects().follow(true) + .redirects().max(3) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_CREATED)) + ; + + // rename contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .body(json) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(NAME, "NEW CONTRACT NAME") + .when() + .redirects().follow(true) + .redirects().max(3) + .patch("/projects/" + OFFICE + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + + "/contracts/" + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + ; + + // get contract, assert name is changed + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .pathParam(OFFICE, CONTRACT.getOfficeId()) + .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) + .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) + .when() + .redirects().follow(true) + .redirects().max(3) + .get("/projects/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_OK)) + .body("office-id", equalTo(CONTRACT.getOfficeId())) + .body("contract-id.name", equalTo("NEW CONTRACT NAME")) + ; + } +} \ No newline at end of file From a1de635802bb6884795b61623f1bc8e2140c63db Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 16 Jul 2024 13:55:17 -0700 Subject: [PATCH 16/39] Test cases passed, Controllers working --- .../WaterContractTypeController.java | 106 --- .../WaterPumpDeleteController.java | 44 +- .../WaterContractTypeControllerTestIT.java | 116 --- .../api/WaterPumpDeleteControllerTestIT.java | 814 ++++++------------ .../WaterUserContractControllerTestIT.java | 354 -------- 5 files changed, 272 insertions(+), 1162 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java deleted file mode 100644 index 797008f71..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterContractTypeController.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api.watersupply; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; -import cwms.cda.api.Controllers; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.LookupType; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import io.javalin.core.util.Header; -import io.javalin.http.Context; -import io.javalin.http.Handler; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import java.util.ArrayList; -import java.util.List; -import javax.servlet.http.HttpServletResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; - - -public class WaterContractTypeController implements Handler { - public static final String TAG = "Water Contracts"; - private final MetricRegistry metrics; - - private Timer.Context markAndTime(String subject) { - return Controllers.markAndTime(metrics, getClass().getName(), subject); - } - - public WaterContractTypeController(MetricRegistry metrics) { - this.metrics = metrics; - } - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi( - pathParams = { - @OpenApiParam(name = NAME, description = "The name of the contract.", required = true), - @OpenApiParam(name = OFFICE, description = "The office Id the contract is associated with.", - required = true), - @OpenApiParam(name = PROJECT_ID, description = "The project Id the contract is associated with.", - required = true), - @OpenApiParam(name = WATER_USER, description = "The water user the contract is associated with.", - required = true) - }, - responses = { - @OpenApiResponse(status = "204", description = "Contract type successfully stored to CWMS."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Create a new water contract type", - method = HttpMethod.POST, - path = "/projects/{office}/{project-id}/water-users/{water-user}/contracts/{name}/types", - tags = {TAG} - ) - - @Override - public void handle(@NotNull Context ctx) { - try (Timer.Context ignored = markAndTime(CREATE)) { - DSLContext dsl = getDslContext(ctx); - String formatHeader = ctx.header(Header.ACCEPT) != null ? ctx.header(Header.ACCEPT) : Formats.JSONV1; - ContentType contentType = Formats.parseHeader(formatHeader, LookupType.class); - ctx.contentType(contentType.toString()); - LookupType contractType = Formats.parseContent(contentType, ctx.body(), LookupType.class); - List types = new ArrayList<>(); - types.add(contractType); - WaterContractDao contractDao = getContractDao(dsl); - contractDao.storeWaterContractTypes(types, true); - ctx.status(HttpServletResponse.SC_CREATED).json("Contract type successfully stored to CWMS."); - } - } - -} diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java index e09f40198..5f8fd64ef 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java @@ -53,8 +53,7 @@ public class WaterPumpDeleteController implements Handler { private static final Logger LOGGER = Logger.getLogger(WaterPumpDeleteController.class.getName()); public static final String TAG = "Water Contracts"; - private static final String USAGE_ID = "usage-id"; - private static final String CONTRACT_NAME = "contract-name"; + private static final String CONTRACT_ID = "contract-id"; private static final String PUMP_TYPE = "pump-type"; private final MetricRegistry metrics; @@ -73,8 +72,6 @@ protected WaterContractDao getContractDao(DSLContext dsl) { @OpenApi( queryParams = { - @OpenApiParam(name = USAGE_ID, required = true, - description = "The pump usage id associated with the contract."), @OpenApiParam(name = PUMP_TYPE, required = true, description = "The type of pump to be removed from the contract." + " Expected values: IN, OUT, OUT BELOW"), @@ -86,8 +83,10 @@ protected WaterContractDao getContractDao(DSLContext dsl) { + "removed from the specified contract.", required = true), @OpenApiParam(name = OFFICE, description = "The office the project is associated with.", required = true), @OpenApiParam(name = PROJECT_ID, description = "The name of the project.", required = true), - @OpenApiParam(name = CONTRACT_NAME, description = "The name of the contract the pump is associated with.", + @OpenApiParam(name = CONTRACT_ID, description = "The name of the contract the pump is associated with.", required = true), + @OpenApiParam(name = WATER_USER, description = "The name of the water user the contract " + + "is associated with.", required = true) }, responses = { @OpenApiResponse(status = "404", description = "The provided combination of parameters" @@ -95,8 +94,7 @@ protected WaterContractDao getContractDao(DSLContext dsl) { @OpenApiResponse(status = "501", description = "Requested format is not implemented.") }, description = "Delete a pump from a contract", - path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{office}/{contract-name}" - + "/pumps/{office}/{name}", + path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{contract-id}/pumps/{name}", method = HttpMethod.DELETE, tags = {TAG} ) @@ -106,15 +104,15 @@ public void handle(@NotNull Context ctx) { try (Timer.Context ignored = markAndTime(DELETE)) { DSLContext dsl = getDslContext(ctx); boolean deleteAccounting = Boolean.parseBoolean(ctx.queryParam(DELETE)); - String usageId = ctx.queryParam(USAGE_ID); String officeId = ctx.pathParam(OFFICE); String projectName = ctx.pathParam(PROJECT_ID); - String contractName = ctx.pathParam(CONTRACT_NAME); + String entityName = ctx.pathParam(WATER_USER); String pumpType = ctx.queryParam(PUMP_TYPE); + String contractName = ctx.pathParam(CONTRACT_ID); assert pumpType != null; WaterContractDao contractDao = getContractDao(dsl); CwmsId projectLocation = new CwmsId.Builder().withName(projectName).withOfficeId(officeId).build(); - List contract = contractDao.getAllWaterContracts(projectLocation, contractName); + List contract = contractDao.getAllWaterContracts(projectLocation, entityName); if (contract.isEmpty()) { CdaError error = new CdaError("No contract found for the provided name."); @@ -128,19 +126,22 @@ public void handle(@NotNull Context ctx) { switch (pumpType) { case "IN": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpInLocation().getPumpLocation().getName(), - usageId, deleteAccounting); - break; + waterUserContract.getPumpInLocation().getPumpId().getName(), + pumpType, deleteAccounting); + ctx.status(HttpServletResponse.SC_NO_CONTENT); + return; case "OUT": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutLocation().getPumpLocation().getName(), - usageId, deleteAccounting); - break; - case "OUT BELOW": + waterUserContract.getPumpOutLocation().getPumpId().getName(), + pumpType, deleteAccounting); + ctx.status(HttpServletResponse.SC_NO_CONTENT); + return; + case "BELOW": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutBelowLocation().getPumpLocation().getName(), - usageId, deleteAccounting); - break; + waterUserContract.getPumpOutBelowLocation().getPumpId().getName(), + pumpType, deleteAccounting); + ctx.status(HttpServletResponse.SC_NO_CONTENT); + return; default: CdaError error = new CdaError("Invalid pump type provided."); LOGGER.log(Level.SEVERE, "Invalid pump type provided."); @@ -150,6 +151,9 @@ public void handle(@NotNull Context ctx) { } } + CdaError error = new CdaError("No contract found for the provided name."); + LOGGER.log(Level.SEVERE, "No matching contract found."); + ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java deleted file mode 100644 index 36e39fef0..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.watersupply.WaterContractController; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import fixtures.TestAccounts; -import io.restassured.filter.log.LogDetail; -import org.apache.commons.io.IOUtils; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletResponse; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - -@Tag("integration") -class WaterContractTypeControllerTestIT extends DataApiTestIT { - private static final String OFFICE_ID = "SPK"; - private static final WaterUserContract CONTRACT; - static { - try (InputStream contractStream = WaterContractController.class.getResourceAsStream("/cwms/cda/api/waterusercontract.json")){ - assert contractStream != null; - String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); - CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); - } catch(Exception ex) { - throw new RuntimeException(ex); - } - } - - @Test - void test_create_get_WaterContractType() { - // Test Structure - // 1) Create a WaterContractType - // 2) Get the WaterContractType, assert it exists - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); - - // create water contract type - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - - // get water contract type and assert that it exists - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .pathParam(OFFICE, OFFICE_ID) - .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName() + "/types") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - .body("office-id", equalTo(OFFICE_ID)) - .body("display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) - .body("tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) - .body("active", equalTo(CONTRACT.getWaterContract().getActive())) - ; - - } -} diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java index a9e577d6a..11fef00b2 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -28,37 +28,51 @@ import cwms.cda.api.enums.Nation; import cwms.cda.api.watersupply.WaterContractController; +import cwms.cda.data.dao.DeleteRule; import cwms.cda.data.dao.JooqDao.DeleteMethod; +import cwms.cda.data.dao.LocationsDaoImpl; +import cwms.cda.data.dao.project.ProjectDao; +import cwms.cda.data.dao.watersupply.WaterContractDao; import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.project.Project; +import cwms.cda.data.dto.watersupply.PumpType; +import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; import cwms.cda.formatters.ContentType; import cwms.cda.formatters.Formats; +import cwms.cda.formatters.json.JsonV1; +import fixtures.CwmsDataApiSetupCallback; import fixtures.TestAccounts; import io.restassured.filter.log.LogDetail; +import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.apache.commons.io.IOUtils; +import org.jooq.DSLContext; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; import java.io.InputStream; +import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.ZoneId; -import static cwms.cda.api.Controllers.*; +import static cwms.cda.api.Controllers.DELETE; +import static cwms.cda.api.Controllers.DELETE_MODE; +import static cwms.cda.data.dao.DaoTest.getDslContext; import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; + @Tag("integration") class WaterPumpDeleteControllerTestIT extends DataApiTestIT { private static final String USAGE_ID = "usage-id"; - private static final String OFFICE_ID = "SPK"; + private static final String OFFICE_ID = "SWT"; private static final WaterUserContract CONTRACT; private static final WaterUserContract CONTRACT_NO_PUMP; - private static final String CONTRACT_NAME = "contract-name"; static { try ( InputStream contractStream = WaterContractController.class @@ -79,375 +93,62 @@ class WaterPumpDeleteControllerTestIT extends DataApiTestIT { } @BeforeAll - static void setUp() { - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - + static void setUp() throws Exception { Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) - .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).withDescription("Contract Location") - .withBoundingOfficeId("SPK").withNearestCity("Sacramento").withStateInitial("CA") - .withCountyName("Sacramento").withTimeZoneName(ZoneId.of("UTC")) - .withLocationType("WATER PROJECT").withPublicName("TEST WATER PROJECT").withPublishedLatitude(89.7) - .withPublishedLongitude(56.9).withElevation(459.1).withElevationUnits("m").withNation(Nation.US) - .withMapLabel("PLACE").withVerticalDatum("WGS84").withActive(true).withLongName("FULL TEST").build(); + .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).withVerticalDatum("WGS84") + .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) + .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) + .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId(), CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") - .withLongitude(38.0).withLatitude(56.5).build(); - - - String json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), contractLocation); - - // create contract location - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .accept(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/locations") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - - json = Formats.format(Formats.parseHeader(Formats.JSON, Location.class), parentLocation); - - // create parent site location - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSON) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/locations") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - - json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); - - // create contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(FAIL_IF_EXISTS, "true") - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/PROJECT/water-users/SPK/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_CREATED)) - .body("office-id", equalTo(CONTRACT.getOfficeId())) - .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() - .getParentLocationRef().getOfficeId())) - .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser() - .getParentLocationRef().getName())) - .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) - .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) - .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) - .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) - .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) - .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) - .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) - .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) - .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) - .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) - .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) - .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) - .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) - .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getOfficeId())) - .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getName())) - .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLatitude())) - .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLongitude())) - .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getActive())) - .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublicName())) - .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLongName())) - .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getDescription())) - .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getTimezoneName())) - .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLocationType())) - .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLocationKind())) - .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getNation())) - .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getStateInitial())) - .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getCountyName())) - .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getNearestCity())) - .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getHorizontalDatum())) - .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLatitude())) - .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLongitude())) - .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getVerticalDatum())) - .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getElevation())) - .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getMapLabel())) - .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getBoundingOfficeId())) - .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getElevationUnits())) - .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getOfficeId())) - .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getName())) - .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLatitude())) - .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLongitude())) - .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getActive())) - .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getPublicName())) - .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLongName())) - .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getDescription())) - .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getTimezoneName())) - .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLocationType())) - .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLocationKind())) - .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getNation())) - .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getStateInitial())) - .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getCountyName())) - .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getNearestCity())) - .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getElevation())) - .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getMapLabel())) - .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) - .body("pump-in-location.pump-location.office-id", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getOfficeId())) - .body("pump-in-location.pump-location.name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() - .getName())) - .body("pump-in-location.pump-location.latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() - .getLatitude())) - .body("pump-in-location.pump-location.longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() - .getLongitude())) - .body("pump-in-location.pump-location.active", equalTo(CONTRACT.getPumpInLocation().getPumpLocation() - .getActive())) - .body("pump-in-location.pump-location.public-name", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getPublicName())) - .body("pump-in-location.pump-location.long-name", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getLongName())) - .body("pump-in-location.pump-location.description", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getDescription())) - .body("pump-in-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getTimezoneName())) - .body("pump-in-location.pump-location.location-type", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getLocationType())) - .body("pump-in-location.pump-location.location-kind", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getLocationKind())) - .body("pump-in-location.pump-location.nation", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getNation())) - .body("pump-in-location.pump-location.state-initial", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getStateInitial())) - .body("pump-in-location.pump-location.county-name", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getCountyName())) - .body("pump-in-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getNearestCity())) - .body("pump-in-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getHorizontalDatum())) - .body("pump-in-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getPublishedLatitude())) - .body("pump-in-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getPublishedLongitude())) - .body("pump-in-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getVerticalDatum())) - .body("pump-in-location.pump-location.elevation", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getElevation())) - .body("pump-in-location.pump-location.map-label", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getMapLabel())) - .body("pump-in-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getBoundingOfficeId())) - .body("pump-in-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpInLocation() - .getPumpLocation().getElevationUnits())) - ; - - String json_no_pump = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), - CONTRACT_NO_PUMP); - - // Create contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json_no_pump) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(FAIL_IF_EXISTS, "false") - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/SPK/PROJECT/water-users/WATERUSER/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - .body("office-id", equalTo(CONTRACT_NO_PUMP.getOfficeId())) - .body("water-user.entity-name", equalTo(CONTRACT_NO_PUMP.getWaterUser().getEntityName())) - .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT_NO_PUMP.getWaterUser() - .getParentLocationRef().getOfficeId())) - .body("water-user.parent-location-ref.name", equalTo(CONTRACT_NO_PUMP.getWaterUser() - .getParentLocationRef().getName())) - .body("water-user.water-right", equalTo(CONTRACT_NO_PUMP.getWaterUser().getWaterRight())) - .body("water-contract.office-id", equalTo(CONTRACT_NO_PUMP.getWaterContract().getOfficeId())) - .body("water-contract.display-value", equalTo(CONTRACT_NO_PUMP.getWaterContract().getDisplayValue())) - .body("water-contract.tooltip", equalTo(CONTRACT_NO_PUMP.getWaterContract().getTooltip())) - .body("water-contract.active", equalTo(CONTRACT_NO_PUMP.getWaterContract().getActive())) - .body("contract-effective-date", equalTo(CONTRACT_NO_PUMP.getContractEffectiveDate())) - .body("contract-expiration-date", equalTo(CONTRACT_NO_PUMP.getContractExpirationDate())) - .body("contracted-storage", equalTo(CONTRACT_NO_PUMP.getContractedStorage())) - .body("initial-use-allocation", equalTo(CONTRACT_NO_PUMP.getInitialUseAllocation())) - .body("future-use-allocation", equalTo(CONTRACT_NO_PUMP.getFutureUseAllocation())) - .body("storage-units-id", equalTo(CONTRACT_NO_PUMP.getStorageUnitsId())) - .body("future-use-percent-activated", equalTo(CONTRACT_NO_PUMP.getFutureUsePercentActivated())) - .body("total-alloc-percent-activated", equalTo(CONTRACT_NO_PUMP.getTotalAllocPercentActivated())) - .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getOfficeId())) - .body("pump-out-location.pump-location.name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getName())) - .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getLatitude())) - .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getLongitude())) - .body("pump-out-location.pump-location.active", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getActive())) - .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getPublicName())) - .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getLongName())) - .body("pump-out-location.pump-location.description", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getDescription())) - .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getTimezoneName())) - .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getLocationType())) - .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getLocationKind())) - .body("pump-out-location.pump-location.nation", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getNation())) - .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getStateInitial())) - .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getCountyName())) - .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getNearestCity())) - .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getHorizontalDatum())) - .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT_NO_PUMP - .getPumpOutLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getElevation())) - .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getMapLabel())) - .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT_NO_PUMP - .getPumpOutLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT_NO_PUMP.getPumpOutLocation() - .getPumpLocation().getElevationUnits())) - .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getOfficeId())) - .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT_NO_PUMP.getPumpOutBelowLocation() - .getPumpLocation().getName())) - .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getLatitude())) - .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getLongitude())) - .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getActive())) - .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getPublicName())) - .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getLongName())) - .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getDescription())) - .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getTimezoneName())) - .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getLocationType())) - .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getLocationKind())) - .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getNation())) - .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getStateInitial())) - .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getCountyName())) - .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getNearestCity())) - .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getElevation())) - .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getMapLabel())) - .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT_NO_PUMP - .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) - .body("pump-in-location", equalTo(null)) - ; - - + .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") + .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) + .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) + .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") + .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") + .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) + .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) + .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); + Project project = new Project.Builder().withLocation(parentLocation).withFederalCost(BigDecimal.valueOf(123456789)) + .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT.getWaterUser().getEntityName()) + .build(); + Project project1 = new Project.Builder().withLocation(parentLocation2).withFederalCost(BigDecimal.valueOf(123456789)) + .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) + .build(); + WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), + CONTRACT.getWaterUser().getParentLocationRef(), + CONTRACT.getWaterUser().getWaterRight()); + WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); + + CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); + databaseLink.connection(c -> { + DSLContext ctx = getDslContext(c, OFFICE_ID); + LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); + ProjectDao projectDao = new ProjectDao(ctx); + WaterContractDao waterContractDao = new WaterContractDao(ctx); + try { + locationsDao.storeLocation(contractLocation); + locationsDao.storeLocation(parentLocation); + locationsDao.storeLocation(parentLocation2); + projectDao.store(project, true); + projectDao.store(project1, true); + waterContractDao.storeWaterUser(waterUser, true); + waterContractDao.storeWaterUser(waterUserNoPump, true); + } catch (IOException e) { + throw new RuntimeException(e); + } + }, CwmsDataApiSetupCallback.getWebUser()); } @AfterAll static void tearDown() throws Exception { - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).build(); @@ -455,120 +156,78 @@ static void tearDown() throws Exception { CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") + .withLongitude(38.0).withLatitude(56.5).build(); + WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), + CONTRACT.getWaterUser().getParentLocationRef(), + CONTRACT.getWaterUser().getWaterRight()); + WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); + + CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); + databaseLink.connection(c -> { + DSLContext ctx = getDslContext(c, OFFICE_ID); + LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); + WaterContractDao waterContractDao = new WaterContractDao(ctx); + ProjectDao projectDao = new ProjectDao(ctx); + waterContractDao.deleteWaterUser(waterUser.getParentLocationRef(), waterUser.getEntityName(), + DeleteRule.DELETE_ALL.toString()); + waterContractDao.deleteWaterUser(waterUserNoPump.getParentLocationRef(), waterUserNoPump.getEntityName(), + DeleteRule.DELETE_ALL.toString()); + projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getParentLocationRef().getName(), + DeleteRule.DELETE_ALL); + projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName(), + DeleteRule.DELETE_ALL); + locationsDao.deleteLocation(contractLocation.getName(), contractLocation.getOfficeId(), true); + locationsDao.deleteLocation(parentLocation.getName(), parentLocation.getOfficeId(), true); + locationsDao.deleteLocation(parentLocation2.getName(), parentLocation2.getOfficeId(), true); + }, CwmsDataApiSetupCallback.getWebUser()); + } - String json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), contractLocation); - - // delete contract location - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(OFFICE, OFFICE_ID) - .queryParam(LOCATION_ID, contractLocation.getName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("locations") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; + @Test + void test_remove_from_contract() throws Exception { + final String PUMP_TYPE = "pump-type"; + // Structure of test: + // 1) Create contract with pump + // 2) Remove the pump from the contract + // 3) Retrieve the contract and assert it does not contain the pump + // 4) Delete the contract - json = Formats.format(Formats.parseHeader(Formats.JSONV1, Location.class), parentLocation); + TestAccounts.KeyUser user = TestAccounts.KeyUser.SWT_NORMAL; + String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT); - // delete parent site location + // Create contract with pump given() .log().ifValidationFails(LogDetail.ALL, true) .contentType(Formats.JSONV1) - .body(json) + .accept(Formats.JSONV1) .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(OFFICE, OFFICE_ID) - .queryParam(LOCATION_ID, parentLocation.getName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("locations") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - - json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); - - // delete contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(LOCATION_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .queryParam(DELETE_MODE, DeleteMethod.DELETE_ALL.toString()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + CONTRACT.getContractId().getOfficeId() + "/" - + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-users/" + CONTRACT.getWaterUser().getEntityName() + "/contracts" - + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) - ; - - String json_no_pump = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), - CONTRACT_NO_PUMP); - - // delete contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json_no_pump) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(LOCATION_ID, CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()) - .queryParam(DELETE_MODE, DeleteMethod.DELETE_ALL.toString()) .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + CONTRACT_NO_PUMP.getContractId().getOfficeId() + "/" - + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() - + "/water-users/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts" - + CONTRACT_NO_PUMP.getContractId().getName()) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + .statusCode(is(HttpServletResponse.SC_CREATED)) ; - } - - @Test - void test_remove_from_contract() { - // Structure of test: - // 1) Remove the pump from the contract - // 2) Retrieve the contract and assert it does not contain the pump - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - // Remove pump and assert it is removed given() - .log().ifValidationFails(LogDetail.ALL, true) - .pathParam(Controllers.OFFICE, OFFICE_ID) - .pathParam(Controllers.PROJECT_ID, CONTRACT.getContractId().getName()) - .pathParam(CONTRACT_NAME, CONTRACT.getWaterContract().getDisplayValue()) - .pathParam(NAME, CONTRACT.getPumpOutLocation().getPumpLocation().getName()) - .queryParam(USAGE_ID, "PUMP1") - .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .queryParam(DELETE, false) + .queryParam(PUMP_TYPE, PumpType.PUMP_IN.getName()) .header(AUTH_HEADER, user.toHeaderValue()) .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getContractId().getName() + "/water-user/" - + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName()+ "/pumps/" + OFFICE_ID + "/" + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + + CONTRACT.getContractId().getName() + "/pumps/" + CONTRACT.getPumpInLocation().getPumpId().getName()) .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -579,176 +238,182 @@ void test_remove_from_contract() { // Retrieve contract and assert pump is removed given() .log().ifValidationFails(LogDetail.ALL, true) - .pathParam(Controllers.OFFICE, OFFICE_ID) - .pathParam(Controllers.PROJECT_ID, CONTRACT.getContractId().getName()) - .pathParam(CONTRACT_NAME, CONTRACT.getContractId().getName()) .accept(Formats.JSONV1) .when() .redirects().follow(true) .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getContractId().getName() + "/water-user/" - + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) .then() .log().ifValidationFails(LogDetail.ALL, true) .assertThat() .statusCode(is(HttpServletResponse.SC_OK)) - .body("office-id", equalTo(CONTRACT.getOfficeId())) - .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() + .body("[0].office-id", equalTo(CONTRACT.getOfficeId())) + .body("[0].water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) + .body("[0].water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() .getParentLocationRef().getOfficeId())) - .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef() + .body("[0].water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef() .getName())) - .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) - .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) - .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) - .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) - .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) - .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) - .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) - .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) - .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) - .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) - .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) - .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) - .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) - .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) + .body("[0].water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) + .body("[0].water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) + .body("[0].water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) + .body("[0].water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) + .body("[0].contract-effective-date", hasToString(String.valueOf(CONTRACT.getContractEffectiveDate().getTime()))) + .body("[0].contract-expiration-date", hasToString(String.valueOf(CONTRACT.getContractExpirationDate().getTime()))) + .body("[0].contracted-storage", hasToString(String.valueOf(CONTRACT.getContractedStorage()))) + .body("[0].initial-use-allocation", hasToString(String.valueOf(CONTRACT.getInitialUseAllocation()))) + .body("[0].future-use-allocation", hasToString(String.valueOf(CONTRACT.getFutureUseAllocation()))) + .body("[0].storage-units-id", hasToString(String.valueOf(CONTRACT.getStorageUnitsId()))) + .body("[0].future-use-percent-activated", hasToString(String.valueOf(CONTRACT.getFutureUsePercentActivated()))) + .body("[0].total-alloc-percent-activated", hasToString(String.valueOf(CONTRACT.getTotalAllocPercentActivated()))) + .body("[0].pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getOfficeId())) - .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation() - .getName())) - .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLatitude())) - .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLongitude())) - .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutLocation().getPumpLocation() + .getName()))) + .body("[0].pump-out-location.pump-id.name", equalTo(CONTRACT.getPumpOutLocation().getPumpId().getName())) + .body("[0].pump-out-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLatitude()))) + .body("[0].pump-out-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLongitude()))) + .body("[0].pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getActive())) - .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getPublicName())) - .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getLongName())) - .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getDescription())) - .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getTimezoneName())) - .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLocationType())) - .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.location-type", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getLocationType()))) + .body("[0].pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getLocationKind())) - .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getNation())) - .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() + .getPumpLocation().getNation().toString())) + .body("[0].pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getStateInitial())) - .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getCountyName())) - .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getNearestCity())) - .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getHorizontalDatum())) - .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLatitude())) - .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLongitude())) - .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.published-latitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLatitude()))) + .body("[0].pump-out-location.pump-location.published-longitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getPublishedLongitude()))) + .body("[0].pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getVerticalDatum())) - .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getElevation())) - .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.elevation", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() + .getPumpLocation().getElevation()))) + .body("[0].pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getMapLabel())) - .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getBoundingOfficeId())) - .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() + .body("[0].pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() .getPumpLocation().getElevationUnits())) - .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getOfficeId())) - .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getName())) - .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLatitude())) - .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLongitude())) - .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getName()))) + .body("[0].pump-out-below-location.pump-id.name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpId().getName())) + .body("[0].pump-out-below-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLatitude()))) + .body("[0].pump-out-below-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLongitude()))) + .body("[0].pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getActive())) - .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getPublicName())) - .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getLongName())) - .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getDescription())) - .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getTimezoneName())) - .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLocationType())) - .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.location-type", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getLocationType()))) + .body("[0].pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getLocationKind())) - .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getNation())) - .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getNation().toString())) + .body("[0].pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getStateInitial())) - .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getCountyName())) - .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getNearestCity())) - .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT + .body("[0].pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT + .body("[0].pump-out-below-location.pump-location.published-latitude", hasToString(String.valueOf(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude()))) + .body("[0].pump-out-below-location.pump-location.published-longitude", hasToString(String.valueOf(CONTRACT + .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude()))) + .body("[0].pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getElevation())) - .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() + .body("[0].pump-out-below-location.pump-location.elevation", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() + .getPumpLocation().getElevation()))) + .body("[0].pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getMapLabel())) - .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT + .body("[0].pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT + .body("[0].pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) - .body("pump-in-location", equalTo(null)) + .body("[0].pump-in-location", equalTo(null)) + ; + + // Delete contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(DELETE_MODE, "DELETE ALL") + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) ; } @Test - void test_remove_does_not_exist() { + void test_remove_does_not_exist() throws Exception { // Structure of test: - // 1) Remove a pump and assert that an error is thrown - // 2) Create a contract with an empty pump - // 3) Try to remove the pump and assert that an error is thrown + // 1) Create contract with no pump + // 2) Try to remove the pump from contract and assert that an error is thrown + // 3) Delete the contract - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; + TestAccounts.KeyUser user = TestAccounts.KeyUser.SWT_NORMAL; + String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT_NO_PUMP); - - // Remove pump + // Create contract with no pump given() .log().ifValidationFails(LogDetail.ALL, true) - .pathParam(Controllers.OFFICE, OFFICE_ID) - .pathParam(Controllers.PROJECT_ID, CONTRACT_NO_PUMP.getContractId().getName()) - .pathParam(CONTRACT_NAME, CONTRACT_NO_PUMP.getWaterContract().getDisplayValue()) - .pathParam(NAME, CONTRACT_NO_PUMP.getPumpOutLocation().getPumpLocation().getName()) - .queryParam(USAGE_ID, "PUMP1") - .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .contentType(Formats.JSONV1) + .accept(Formats.JSONV1) + .body(json) .header(AUTH_HEADER, user.toHeaderValue()) .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getContractId().getName() + "/water-user/" - + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT_NO_PUMP.getContractId().getName()+ "/pumps/" + OFFICE_ID + "/" - + CONTRACT_NO_PUMP.getPumpInLocation().getPumpId().getName()) + .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) .assertThat() - .statusCode(is(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)) + .statusCode(is(HttpServletResponse.SC_CREATED)) ; - // Remove pump given() .log().ifValidationFails(LogDetail.ALL, true) - .pathParam(Controllers.OFFICE, OFFICE_ID) - .pathParam(Controllers.PROJECT_ID, CONTRACT_NO_PUMP.getContractId().getName()) - .pathParam(CONTRACT_NAME, CONTRACT_NO_PUMP.getWaterContract().getDisplayValue()) - .pathParam(NAME, CONTRACT_NO_PUMP.getPumpOutLocation().getPumpLocation().getName()) .queryParam(USAGE_ID, "PUMP1") .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) .header(AUTH_HEADER, user.toHeaderValue()) @@ -758,12 +423,29 @@ void test_remove_does_not_exist() { .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getContractId().getName() + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" + CONTRACT_NO_PUMP.getContractId().getName()+ "/pumps/" - + CONTRACT_NO_PUMP.getPumpInLocation().getPumpId().getName()) + + null) .then() .log().ifValidationFails(LogDetail.ALL, true) .assertThat() .statusCode(is(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)) ; + // Delete contract + given() + .log().ifValidationFails(LogDetail.ALL, true) + .contentType(Formats.JSONV1) + .header(AUTH_HEADER, user.toHeaderValue()) + .queryParam(DELETE_MODE, "DELETE ALL") + .when() + .redirects().follow(true) + .redirects().max(3) + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() + + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + + "/contracts/" + CONTRACT_NO_PUMP.getContractId().getName()) + .then() + .log().ifValidationFails(LogDetail.ALL, true) + .assertThat() + .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) + ; } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java deleted file mode 100644 index 607e7cbeb..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterUserContractControllerTestIT.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.watersupply.WaterContractController; -import cwms.cda.data.dao.JooqDao; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.json.JsonV1; -import fixtures.TestAccounts; -import io.restassured.filter.log.LogDetail; -import org.apache.commons.io.IOUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletResponse; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - - -@Tag("integration") -class WaterUserContractControllerTestIT extends DataApiTestIT { - private static final String OFFICE_ID = "SPK"; - private static final WaterUserContract CONTRACT; - static { - try (InputStream contractStream = WaterContractController.class.getResourceAsStream("/cwms/cda/api/waterusercontract.json")){ - assert contractStream != null; - String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); - CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); - } catch(Exception ex) { - throw new RuntimeException(ex); - } - } - - @BeforeAll - static void setup() throws Exception { - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT.getWaterUser()); - - // create water user - given() - .log().ifValidationFails(LogDetail.ALL, true) - .accept(Formats.JSONV1) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - } - - @AfterAll - static void tearDown() throws Exception { - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT.getWaterUser()); - - // create water user - given() - .log().ifValidationFails(LogDetail.ALL, true) - .accept(Formats.JSONV1) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - } - - @Test - void test_create_get_delete_WaterUserContract() { - // Test Structure: - // 1) Create a WaterUserContract - // 2) Get the WaterUserContract, assert that it is same as created contract - // 3) Delete the WaterUserContract - // 4) Get the WaterUserContract, assert that it is not found - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); - - // Create contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(FAIL_IF_EXISTS, "true") - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_CREATED)) - ; - - // get contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .pathParam(OFFICE, CONTRACT.getOfficeId()) - .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - .body("office-id", equalTo(CONTRACT.getOfficeId())) - .body("water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId())) - .body("water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef().getName())) - .body("water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) - .body("water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) - .body("water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) - .body("water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) - .body("water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) - .body("contract-effective-date", equalTo(CONTRACT.getContractEffectiveDate())) - .body("contract-expiration-date", equalTo(CONTRACT.getContractExpirationDate())) - .body("contracted-storage", equalTo(CONTRACT.getContractedStorage())) - .body("initial-use-allocation", equalTo(CONTRACT.getInitialUseAllocation())) - .body("future-use-allocation", equalTo(CONTRACT.getFutureUseAllocation())) - .body("storage-units-id", equalTo(CONTRACT.getStorageUnitsId())) - .body("future-use-percent-activated", equalTo(CONTRACT.getFutureUsePercentActivated())) - .body("total-alloc-percent-activated", equalTo(CONTRACT.getTotalAllocPercentActivated())) - .body("pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getOfficeId())) - .body("pump-out-location.pump-location.name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getName())) - .body("pump-out-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLatitude())) - .body("pump-out-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLongitude())) - .body("pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getActive())) - .body("pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublicName())) - .body("pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLongName())) - .body("pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getDescription())) - .body("pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getTimezoneName())) - .body("pump-out-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLocationType())) - .body("pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getLocationKind())) - .body("pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getNation())) - .body("pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getStateInitial())) - .body("pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getCountyName())) - .body("pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getNearestCity())) - .body("pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-out-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getElevation())) - .body("pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getMapLabel())) - .body("pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation().getPumpLocation().getElevationUnits())) - .body("pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getOfficeId())) - .body("pump-out-below-location.pump-location.name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getName())) - .body("pump-out-below-location.pump-location.latitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLatitude())) - .body("pump-out-below-location.pump-location.longitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLongitude())) - .body("pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getActive())) - .body("pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublicName())) - .body("pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLongName())) - .body("pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getDescription())) - .body("pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getTimezoneName())) - .body("pump-out-below-location.pump-location.location-type", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLocationType())) - .body("pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getLocationKind())) - .body("pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getNation())) - .body("pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getStateInitial())) - .body("pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getCountyName())) - .body("pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getNearestCity())) - .body("pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-out-below-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-out-below-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) - .body("pump-out-below-location.pump-location.elevation", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getElevation())) - .body("pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getMapLabel())) - .body("pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) - .body("pump-in-location.pump-location.office-id", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getOfficeId())) - .body("pump-in-location.pump-location.name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getName())) - .body("pump-in-location.pump-location.latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLatitude())) - .body("pump-in-location.pump-location.longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLongitude())) - .body("pump-in-location.pump-location.active", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getActive())) - .body("pump-in-location.pump-location.public-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublicName())) - .body("pump-in-location.pump-location.long-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLongName())) - .body("pump-in-location.pump-location.description", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getDescription())) - .body("pump-in-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getTimezoneName())) - .body("pump-in-location.pump-location.location-type", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLocationType())) - .body("pump-in-location.pump-location.location-kind", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getLocationKind())) - .body("pump-in-location.pump-location.nation", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getNation())) - .body("pump-in-location.pump-location.state-initial", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getStateInitial())) - .body("pump-in-location.pump-location.county-name", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getCountyName())) - .body("pump-in-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getNearestCity())) - .body("pump-in-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getHorizontalDatum())) - .body("pump-in-location.pump-location.published-latitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublishedLatitude())) - .body("pump-in-location.pump-location.published-longitude", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getPublishedLongitude())) - .body("pump-in-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getVerticalDatum())) - .body("pump-in-location.pump-location.elevation", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getElevation())) - .body("pump-in-location.pump-location.map-label", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getMapLabel())) - .body("pump-in-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getBoundingOfficeId())) - .body("pump-in-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpInLocation().getPumpLocation().getElevationUnits())) - ; - - // delete contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .pathParam(Controllers.OFFICE, OFFICE_ID) - .pathParam(Controllers.PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) - .pathParam(NAME, CONTRACT.getContractId().getName()) - .queryParam(DELETE_MODE, JooqDao.DeleteMethod.DELETE_ALL.toString()) - .queryParam(LOCATION_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" - + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) - ; - - // get contract, assert that it doesn't exist - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .pathParam(OFFICE, CONTRACT.getOfficeId()) - .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NOT_FOUND)) - ; - } - - - @Test - void test_rename_WaterUserContract() { - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - String json = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterUserContract.class), CONTRACT); - - // create contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(FAIL_IF_EXISTS, "true") - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_CREATED)) - ; - - // rename contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(NAME, "NEW CONTRACT NAME") - .when() - .redirects().follow(true) - .redirects().max(3) - .patch("/projects/" + OFFICE + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() - + "/contracts/" + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - ; - - // get contract, assert name is changed - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .pathParam(OFFICE, CONTRACT.getOfficeId()) - .pathParam(PROJECT_ID, CONTRACT.getWaterUser().getParentLocationRef().getName()) - .pathParam(WATER_USER, CONTRACT.getWaterUser().getEntityName()) - .when() - .redirects().follow(true) - .redirects().max(3) - .get("/projects/" + CONTRACT.getWaterUser().getParentLocationRef().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - .body("office-id", equalTo(CONTRACT.getOfficeId())) - .body("contract-id.name", equalTo("NEW CONTRACT NAME")) - ; - } -} \ No newline at end of file From e5c0de55e467ec8d2373fbbcabec70fb4c143a71 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Tue, 16 Jul 2024 15:32:27 -0700 Subject: [PATCH 17/39] Fixed Water Supply Controller tests to match DTO changes --- .../cwms/cda/api/watersupply/WaterPumpDeleteController.java | 6 +++--- .../java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java | 4 +--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java index 5f8fd64ef..9f0f8a83b 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java @@ -126,19 +126,19 @@ public void handle(@NotNull Context ctx) { switch (pumpType) { case "IN": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpInLocation().getPumpId().getName(), + waterUserContract.getPumpInLocation().getPumpLocation().getName(), pumpType, deleteAccounting); ctx.status(HttpServletResponse.SC_NO_CONTENT); return; case "OUT": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutLocation().getPumpId().getName(), + waterUserContract.getPumpOutLocation().getPumpLocation().getName(), pumpType, deleteAccounting); ctx.status(HttpServletResponse.SC_NO_CONTENT); return; case "BELOW": contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutBelowLocation().getPumpId().getName(), + waterUserContract.getPumpOutBelowLocation().getPumpLocation().getName(), pumpType, deleteAccounting); ctx.status(HttpServletResponse.SC_NO_CONTENT); return; diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java index 11fef00b2..8b378553f 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -228,7 +228,7 @@ void test_remove_from_contract() throws Exception { .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName() + "/pumps/" - + CONTRACT.getPumpInLocation().getPumpId().getName()) + + CONTRACT.getPumpInLocation().getPumpLocation().getName()) .then() .log().ifValidationFails(LogDetail.ALL, true) .assertThat() @@ -272,7 +272,6 @@ void test_remove_from_contract() throws Exception { .getPumpLocation().getOfficeId())) .body("[0].pump-out-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutLocation().getPumpLocation() .getName()))) - .body("[0].pump-out-location.pump-id.name", equalTo(CONTRACT.getPumpOutLocation().getPumpId().getName())) .body("[0].pump-out-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() .getPumpLocation().getLatitude()))) .body("[0].pump-out-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() @@ -319,7 +318,6 @@ void test_remove_from_contract() throws Exception { .getPumpLocation().getOfficeId())) .body("[0].pump-out-below-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getName()))) - .body("[0].pump-out-below-location.pump-id.name", equalTo(CONTRACT.getPumpOutBelowLocation().getPumpId().getName())) .body("[0].pump-out-below-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() .getPumpLocation().getLatitude()))) .body("[0].pump-out-below-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() From 750fd25e548208ebcf1e040413cb066083c2fa65 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Thu, 18 Jul 2024 08:57:34 -0700 Subject: [PATCH 18/39] Updated Controllers to match DTO and DAO changes --- .../api/WaterPumpDeleteControllerTestIT.java | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java index 8b378553f..c5b6e6f30 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -100,15 +100,15 @@ static void setUp() throws Exception { .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId(), - CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectLocationRef().getOfficeId(), + CONTRACT.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) @@ -121,10 +121,10 @@ static void setUp() throws Exception { .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) .build(); WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getParentLocationRef(), + CONTRACT.getWaterUser().getProjectLocationRef(), CONTRACT.getWaterUser().getWaterRight()); WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef(), CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); @@ -152,19 +152,19 @@ static void tearDown() throws Exception { Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getParentLocationRef().getOfficeId(), - CONTRACT.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectLocationRef().getOfficeId(), + CONTRACT.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getParentLocationRef(), + CONTRACT.getWaterUser().getProjectLocationRef(), CONTRACT.getWaterUser().getWaterRight()); WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef(), CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); @@ -173,13 +173,13 @@ static void tearDown() throws Exception { LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); WaterContractDao waterContractDao = new WaterContractDao(ctx); ProjectDao projectDao = new ProjectDao(ctx); - waterContractDao.deleteWaterUser(waterUser.getParentLocationRef(), waterUser.getEntityName(), + waterContractDao.deleteWaterUser(waterUser.getProjectLocationRef(), waterUser.getEntityName(), DeleteRule.DELETE_ALL.toString()); - waterContractDao.deleteWaterUser(waterUserNoPump.getParentLocationRef(), waterUserNoPump.getEntityName(), + waterContractDao.deleteWaterUser(waterUserNoPump.getProjectLocationRef(), waterUserNoPump.getEntityName(), DeleteRule.DELETE_ALL.toString()); - projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getParentLocationRef().getName(), + projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getProjectLocationRef().getName(), DeleteRule.DELETE_ALL); - projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName(), + projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName(), DeleteRule.DELETE_ALL); locationsDao.deleteLocation(contractLocation.getName(), contractLocation.getOfficeId(), true); locationsDao.deleteLocation(parentLocation.getName(), parentLocation.getOfficeId(), true); @@ -209,7 +209,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -220,12 +220,12 @@ void test_remove_from_contract() throws Exception { // Remove pump and assert it is removed given() .queryParam(DELETE, false) - .queryParam(PUMP_TYPE, PumpType.PUMP_IN.getName()) + .queryParam(PUMP_TYPE, PumpType.IN.getName()) .header(AUTH_HEADER, user.toHeaderValue()) .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName() + "/pumps/" + CONTRACT.getPumpInLocation().getPumpLocation().getName()) @@ -242,7 +242,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) .then() @@ -251,15 +251,15 @@ void test_remove_from_contract() throws Exception { .statusCode(is(HttpServletResponse.SC_OK)) .body("[0].office-id", equalTo(CONTRACT.getOfficeId())) .body("[0].water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("[0].water-user.parent-location-ref.office-id", equalTo(CONTRACT.getWaterUser() - .getParentLocationRef().getOfficeId())) - .body("[0].water-user.parent-location-ref.name", equalTo(CONTRACT.getWaterUser().getParentLocationRef() + .body("[0].water-user.project-location-ref.office-id", equalTo(CONTRACT.getWaterUser() + .getProjectLocationRef().getOfficeId())) + .body("[0].water-user.project-location-ref.name", equalTo(CONTRACT.getWaterUser().getProjectLocationRef() .getName())) .body("[0].water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) - .body("[0].water-contract.office-id", equalTo(CONTRACT.getWaterContract().getOfficeId())) - .body("[0].water-contract.display-value", equalTo(CONTRACT.getWaterContract().getDisplayValue())) - .body("[0].water-contract.tooltip", equalTo(CONTRACT.getWaterContract().getTooltip())) - .body("[0].water-contract.active", equalTo(CONTRACT.getWaterContract().getActive())) + .body("[0].contract-type.office-id", equalTo(CONTRACT.getContractType().getOfficeId())) + .body("[0].contract-type.display-value", equalTo(CONTRACT.getContractType().getDisplayValue())) + .body("[0].contract-type.tooltip", equalTo(CONTRACT.getContractType().getTooltip())) + .body("[0].contract-type.active", equalTo(CONTRACT.getContractType().getActive())) .body("[0].contract-effective-date", hasToString(String.valueOf(CONTRACT.getContractEffectiveDate().getTime()))) .body("[0].contract-expiration-date", hasToString(String.valueOf(CONTRACT.getContractExpirationDate().getTime()))) .body("[0].contracted-storage", hasToString(String.valueOf(CONTRACT.getContractedStorage()))) @@ -372,7 +372,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getParentLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -401,7 +401,7 @@ void test_remove_does_not_exist() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() + .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -413,7 +413,7 @@ void test_remove_does_not_exist() throws Exception { given() .log().ifValidationFails(LogDetail.ALL, true) .queryParam(USAGE_ID, "PUMP1") - .queryParam(Controllers.DELETE, DeleteMethod.DELETE_ALL.toString()) + .queryParam(DELETE, DeleteMethod.DELETE_ALL.toString()) .header(AUTH_HEADER, user.toHeaderValue()) .when() .redirects().follow(true) @@ -437,7 +437,7 @@ void test_remove_does_not_exist() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getParentLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName() + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" + CONTRACT_NO_PUMP.getContractId().getName()) .then() From 3f01352ab0d7733588ec8c2edc8762a52e5f6c10 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 22 Jul 2024 12:04:54 -0700 Subject: [PATCH 19/39] Renamed Project Location Ref to Project ID, Removed deprecated Location ID input parameter --- .../api/WaterPumpDeleteControllerTestIT.java | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java index c5b6e6f30..3d0fc5348 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -100,15 +100,15 @@ static void setUp() throws Exception { .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectLocationRef().getOfficeId(), - CONTRACT.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectId().getOfficeId(), + CONTRACT.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectId().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) @@ -121,10 +121,10 @@ static void setUp() throws Exception { .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) .build(); WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getProjectLocationRef(), + CONTRACT.getWaterUser().getProjectId(), CONTRACT.getWaterUser().getWaterRight()); WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getProjectId(), CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); @@ -152,19 +152,19 @@ static void tearDown() throws Exception { Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectLocationRef().getOfficeId(), - CONTRACT.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectId().getOfficeId(), + CONTRACT.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName()).withLocationKind("PROJECT") + Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectId().getOfficeId(), + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getProjectLocationRef(), + CONTRACT.getWaterUser().getProjectId(), CONTRACT.getWaterUser().getWaterRight()); WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef(), + CONTRACT_NO_PUMP.getWaterUser().getProjectId(), CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); @@ -173,13 +173,13 @@ static void tearDown() throws Exception { LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); WaterContractDao waterContractDao = new WaterContractDao(ctx); ProjectDao projectDao = new ProjectDao(ctx); - waterContractDao.deleteWaterUser(waterUser.getProjectLocationRef(), waterUser.getEntityName(), + waterContractDao.deleteWaterUser(waterUser.getProjectId(), waterUser.getEntityName(), DeleteRule.DELETE_ALL.toString()); - waterContractDao.deleteWaterUser(waterUserNoPump.getProjectLocationRef(), waterUserNoPump.getEntityName(), + waterContractDao.deleteWaterUser(waterUserNoPump.getProjectId(), waterUserNoPump.getEntityName(), DeleteRule.DELETE_ALL.toString()); - projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getProjectLocationRef().getName(), + projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getProjectId().getName(), DeleteRule.DELETE_ALL); - projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName(), + projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName(), DeleteRule.DELETE_ALL); locationsDao.deleteLocation(contractLocation.getName(), contractLocation.getOfficeId(), true); locationsDao.deleteLocation(parentLocation.getName(), parentLocation.getOfficeId(), true); @@ -209,7 +209,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -225,7 +225,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName() + "/pumps/" + CONTRACT.getPumpInLocation().getPumpLocation().getName()) @@ -242,7 +242,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) .then() @@ -251,9 +251,9 @@ void test_remove_from_contract() throws Exception { .statusCode(is(HttpServletResponse.SC_OK)) .body("[0].office-id", equalTo(CONTRACT.getOfficeId())) .body("[0].water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("[0].water-user.project-location-ref.office-id", equalTo(CONTRACT.getWaterUser() - .getProjectLocationRef().getOfficeId())) - .body("[0].water-user.project-location-ref.name", equalTo(CONTRACT.getWaterUser().getProjectLocationRef() + .body("[0].water-user.project-id.office-id", equalTo(CONTRACT.getWaterUser() + .getProjectId().getOfficeId())) + .body("[0].water-user.project-id.name", equalTo(CONTRACT.getWaterUser().getProjectId() .getName())) .body("[0].water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) .body("[0].contract-type.office-id", equalTo(CONTRACT.getContractType().getOfficeId())) @@ -372,7 +372,7 @@ void test_remove_from_contract() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -401,7 +401,7 @@ void test_remove_does_not_exist() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName() + .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts") .then() .log().ifValidationFails(LogDetail.ALL, true) @@ -437,7 +437,7 @@ void test_remove_does_not_exist() throws Exception { .when() .redirects().follow(true) .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectLocationRef().getName() + .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName() + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" + CONTRACT_NO_PUMP.getContractId().getName()) .then() From 5547fb9b8cb945a4ca2955b0c90a0b273aa99b3c Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 24 Jul 2024 12:37:21 -0700 Subject: [PATCH 20/39] Incorporated changed DTOs (changed constructors to builders) --- .../api/WaterPumpDeleteControllerTestIT.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java index 3d0fc5348..ccb733e0b 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java @@ -58,6 +58,7 @@ import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.ZoneId; +import java.util.Collections; import static cwms.cda.api.Controllers.DELETE; import static cwms.cda.api.Controllers.DELETE_MODE; @@ -120,12 +121,12 @@ static void setUp() throws Exception { Project project1 = new Project.Builder().withLocation(parentLocation2).withFederalCost(BigDecimal.valueOf(123456789)) .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) .build(); - WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getProjectId(), - CONTRACT.getWaterUser().getWaterRight()); - WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getProjectId(), - CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); + WaterUser waterUser = new WaterUser.Builder().withEntityName(CONTRACT.getWaterUser().getEntityName()) + .withProjectId(CONTRACT.getWaterUser().getProjectId()) + .withWaterRight(CONTRACT.getWaterUser().getWaterRight()).build(); + WaterUser waterUserNoPump = new WaterUser.Builder().withEntityName(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) + .withProjectId(CONTRACT_NO_PUMP.getWaterUser().getProjectId()) + .withWaterRight(CONTRACT_NO_PUMP.getWaterUser().getWaterRight()).build(); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); databaseLink.connection(c -> { @@ -140,6 +141,7 @@ static void setUp() throws Exception { projectDao.store(project, true); projectDao.store(project1, true); waterContractDao.storeWaterUser(waterUser, true); + waterContractDao.storeWaterContractTypes(Collections.singletonList(CONTRACT.getContractType()), false); waterContractDao.storeWaterUser(waterUserNoPump, true); } catch (IOException e) { throw new RuntimeException(e); @@ -160,12 +162,12 @@ static void tearDown() throws Exception { CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") .withLongitude(38.0).withLatitude(56.5).build(); - WaterUser waterUser = new WaterUser(CONTRACT.getWaterUser().getEntityName(), - CONTRACT.getWaterUser().getProjectId(), - CONTRACT.getWaterUser().getWaterRight()); - WaterUser waterUserNoPump = new WaterUser(CONTRACT_NO_PUMP.getWaterUser().getEntityName(), - CONTRACT_NO_PUMP.getWaterUser().getProjectId(), - CONTRACT_NO_PUMP.getWaterUser().getWaterRight()); + WaterUser waterUser = new WaterUser.Builder().withEntityName(CONTRACT.getWaterUser().getEntityName()) + .withProjectId(CONTRACT.getWaterUser().getProjectId()) + .withWaterRight(CONTRACT.getWaterUser().getWaterRight()).build(); + WaterUser waterUserNoPump = new WaterUser.Builder().withEntityName(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) + .withProjectId(CONTRACT_NO_PUMP.getWaterUser().getProjectId()) + .withWaterRight(CONTRACT_NO_PUMP.getWaterUser().getWaterRight()).build(); CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); databaseLink.connection(c -> { From d9c0f1548b2eeba60b85ee4b19c8b869a970dd22 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Thu, 18 Jul 2024 14:17:38 -0700 Subject: [PATCH 21/39] Implemented Water Supply Accounting DTO --- .../watersupply/WaterSupplyAccounting.java | 101 +++++++++ .../WaterSupplyAccountingTest.java | 194 ++++++++++++++++++ .../test/java/cwms/cda/helpers/DTOMatch.java | 12 ++ .../watersupply/water_supply_accounting.json | 44 ++++ 4 files changed, 351 insertions(+) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java create mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java create mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java new file mode 100644 index 000000000..e6baf7e61 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -0,0 +1,101 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; +import java.util.Date; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, + aliases = {Formats.DEFAULT, Formats.JSON}) +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) +public class WaterSupplyAccounting extends CwmsDTOBase { + @JsonProperty(required = true) + private WaterUser waterUser; + @JsonProperty(required = true) + private String contractName; + @JsonProperty(required = true) + private Location pumpLocation; + @JsonProperty(required = true) + private LookupType transferType; + @JsonProperty(required = true) + private Double flow; + @JsonProperty(required = true) + private Date transferDate; + private String comment; + + private WaterSupplyAccounting() { + } + + public WaterSupplyAccounting(WaterUser waterUser, String contractName, Location pumpLocation, + LookupType transferType, Double flow, Date transferDate, String comment) { + this.waterUser = waterUser; + this.contractName = contractName; + this.pumpLocation = pumpLocation; + this.transferType = transferType; + this.flow = flow; + this.transferDate = transferDate; + this.comment = comment; + } + + public WaterUser getWaterUser() { + return this.waterUser; + } + + public String getContractName() { + return this.contractName; + } + + public Location getPumpLocation() { + return this.pumpLocation; + } + + public LookupType getTransferType() { + return this.transferType; + } + + public Double getFlow() { + return this.flow; + } + + public Date getTransferDate() { + return this.transferDate; + } + + public String getComment() { + return this.comment; + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java new file mode 100644 index 000000000..e46907738 --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -0,0 +1,194 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import cwms.cda.api.enums.Nation; +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.Formats; +import cwms.cda.helpers.DTOMatch; +import org.junit.jupiter.api.Test; +import org.testcontainers.shaded.org.apache.commons.io.IOUtils; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.ZoneId; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.*; + +class WaterSupplyAccountingTest { + private static final String OFFICE = "SPK"; + + @Test + void testWaterSupplyAccountingSerializationRoundTrip() { + WaterUser user = new WaterUser("Test Entity", new CwmsId.Builder() + .withOfficeId(OFFICE) + .withName("Test Location") + .build(), + "Test Water Right"); + + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(user, "Test Contract", + new Location.Builder(OFFICE, "NAME").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("PUMP 1").withLatitude(56.8).withLongitude(31.9).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGSV84").build(), + new LookupType.Builder().withActive(true).withTooltip("Test transfer Tip").withOfficeId(OFFICE) + .withDisplayValue("Transfer").build(), 1.0, new Date(), "Test Comment"); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), + waterSupplyAccounting); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + } + + @Test + void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + "Test Contract", + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + InputStream resource = this.getClass().getResourceAsStream( + "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + } + + + @Test + void testValidate() { + assertAll( + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + "Test Contract", + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + assertDoesNotThrow(waterSupplyAccounting::validate, "Expected validation to pass"); + }, + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + null, + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + + "fail due to null contract name"); + }, + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + "Test Contract", + null, + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + + "fail due to null location"); + }, + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + "Test Contract", + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + null, 1.0, new Date(10000012648112L), "Test Comment"); + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + + "fail due to null transfer type"); + }, + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + null, + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), null, new Date(10000012648112L), "Test Comment"); + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + + "fail due to null flow value"); + }, + () -> { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + null, + new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) + .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") + .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") + .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") + .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) + .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") + .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") + .withStateInitial("OR").withCountyName("Test County").build(), + new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build(), 1.0, null, "Test Comment"); + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + + "fail due to null transfer date"); + } + ); + } + +} diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index cef393536..5b44199cb 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -47,6 +47,7 @@ import cwms.cda.data.dto.stream.StreamLocation; import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; +import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; import cwms.cda.data.dto.watersupply.WaterSupplyPump; import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; @@ -355,6 +356,17 @@ private static void assertMatch(Double first, Double second, String message) { assertMatch(first, second, DEFAULT_DELTA, message); } + public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { + assertAll( + () -> assertMatch(first.getWaterUser(), second.getWaterUser()), + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertMatch(first.getPumpLocation(), second.getPumpLocation()), + () -> assertMatch(first.getTransferType(), second.getTransferType()), + () -> assertEquals(first.getFlow(), second.getFlow()), + () -> assertEquals(first.getTransferDate(), second.getTransferDate()), + () -> assertEquals(first.getComment(), second.getComment()) + ); + } @FunctionalInterface public interface AssertMatchMethod{ diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json new file mode 100644 index 000000000..94f0751a4 --- /dev/null +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -0,0 +1,44 @@ +{ + "water-user": { + "entity-name": "Test Entity", + "project-location-ref": { + "name": "Test Location", + "office-id": "SPK" + }, + "water-right": "Test Water Right" + }, + "contract-name": "Test Contract", + "pump-location": { + "name": "Test Pump", + "office-id": "SPK", + "latitude": 45.0, + "longitude": -120.0, + "active": true, + "description": "Test Description", + "map-label": "Test Map Label", + "elevation": 1000.0, + "elevation-units": "m", + "vertical-datum": "NGVD29", + "horizontal-datum": "WGS84", + "published-latitude": 45.0, + "published-longitude": -120.0, + "state-initial": "OR", + "location-kind": "PUMP", + "location-type": "PUMP", + "nation": "US", + "county-name": "Test County", + "timezone-name": "UTC", + "long-name": "Test Long Name", + "public-name": "Test Public Name", + "bounding-office-id": "SPK" + }, + "transfer-type": { + "office-id": "SPK", + "display-value": "Test Transfer Type", + "tooltip": "Test Tool Tip", + "active": true + }, + "flow": 1.0, + "transfer-date": 10000012648112, + "comment": "Test Comment" +} \ No newline at end of file From 8593b6e75ab6463e7273a4ab3a14a8bd8c7b09f8 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Fri, 19 Jul 2024 10:23:42 -0700 Subject: [PATCH 22/39] Refactored DTO, added Mappable data representation --- .../watersupply/WaterSupplyAccounting.java | 331 +++++++++++++++--- .../WaterSupplyPumpAccounting.java | 105 ++++++ ...ava => WaterSupplyPumpAccountingTest.java} | 51 ++- .../test/java/cwms/cda/helpers/DTOMatch.java | 4 +- 4 files changed, 416 insertions(+), 75 deletions(-) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java rename cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/{WaterSupplyAccountingTest.java => WaterSupplyPumpAccountingTest.java} (81%) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index e6baf7e61..e88d99bcd 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -26,76 +26,313 @@ package cwms.cda.data.dto.watersupply; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.PropertyNamingStrategies; -import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.data.dto.Location; -import cwms.cda.data.dto.LookupType; +import cwms.cda.data.dto.CwmsId; import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; +import hec.data.DataObjectException; +import hec.data.TimeWindow; +import hec.data.TimeWindowMap; +import java.util.Collection; import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.NavigableMap; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import rma.util.RMAConst; -@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, - aliases = {Formats.DEFAULT, Formats.JSON}) -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) public class WaterSupplyAccounting extends CwmsDTOBase { - @JsonProperty(required = true) - private WaterUser waterUser; - @JsonProperty(required = true) - private String contractName; - @JsonProperty(required = true) - private Location pumpLocation; - @JsonProperty(required = true) - private LookupType transferType; - @JsonProperty(required = true) - private Double flow; - @JsonProperty(required = true) - private Date transferDate; - private String comment; - - private WaterSupplyAccounting() { - } - - public WaterSupplyAccounting(WaterUser waterUser, String contractName, Location pumpLocation, - LookupType transferType, Double flow, Date transferDate, String comment) { - this.waterUser = waterUser; + private final String contractName; + private final WaterUser waterUser; + private final Map> pumpLocationMap; + private final Map pumpTimeWindowMap; + + public WaterSupplyAccounting(String contractName, WaterUser waterUser, + Map> pumpLocationMap, + Map pumpTimeWindowMap) { this.contractName = contractName; - this.pumpLocation = pumpLocation; - this.transferType = transferType; - this.flow = flow; - this.transferDate = transferDate; - this.comment = comment; + this.waterUser = waterUser; + this.pumpLocationMap = pumpLocationMap; + this.pumpTimeWindowMap = pumpTimeWindowMap; + } + + public String getContractName() { + return this.contractName; } public WaterUser getWaterUser() { return this.waterUser; } - public String getContractName() { - return this.contractName; + public Map> getPumpLocationMap() { + return this.pumpLocationMap; } - public Location getPumpLocation() { - return this.pumpLocation; + public Map getPumpTimeWindowMap() { + return this.pumpTimeWindowMap; } - public LookupType getTransferType() { - return this.transferType; + public Map> getAllPumpAccounting() { + Map> output = new HashMap<>(); + + for (Map.Entry> cwmsIdNavigableMapEntry : this.pumpLocationMap.entrySet()) { + output.put(cwmsIdNavigableMapEntry.getKey(), new TreeMap<>(cwmsIdNavigableMapEntry.getValue())); + } + return output; } - public Double getFlow() { - return this.flow; + public int size() { + int size = 0; + Collection> values = this.pumpLocationMap.values(); + + NavigableMap value; + for (Iterator> it = values.iterator(); it.hasNext(); size += value.size()) { + value = it.next(); + } + return size; } - public Date getTransferDate() { - return this.transferDate; + public Map> getAllPumpAccounting(Date startDate, + Date endDate) { + Map> output = new HashMap<>(); + Set>> entrySet + = this.pumpLocationMap.entrySet(); + + for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { + NavigableMap value = cwmsIdNavigableMapEntry.getValue(); + output.put(cwmsIdNavigableMapEntry.getKey(), value.subMap(startDate, true, endDate, true)); + } + return output; } - public String getComment() { - return this.comment; + public NavigableMap getPumpAccounting(CwmsId pumpId) { + NavigableMap map = this.pumpLocationMap.get(pumpId); + if (map == null) { + map = this.buildPumpAccounting(pumpId); + } + return map; + } + + public NavigableMap getPumpAccounting(CwmsId pumpId, Date startDate, + Date endDate) { + NavigableMap map = this.pumpLocationMap.get(pumpId); + if (map == null) { + map = this.buildPumpAccounting(pumpId); + return map; + } + return map.subMap(startDate, true, endDate, true); + } + + public NavigableMap buildPumpAccounting(CwmsId pumpId) { + NavigableMap accountingMap = this.pumpLocationMap.get(pumpId); + if (accountingMap != null) { + return accountingMap; + } else { + accountingMap = new TreeMap<>(); + this.pumpLocationMap.put(pumpId, accountingMap); + return accountingMap; + } + } + + public void mergeAccounting(CwmsId pumpLocRef, NavigableMap accountingMap, + boolean generateModifiedTimeWindow, boolean preserveModifiedData) { + if (pumpLocRef != null && accountingMap != null && !accountingMap.isEmpty()) { + NavigableMap cacheMap + = this.buildPumpAccounting(pumpLocRef); + TimeWindowMap timeWindowMap; + if (cacheMap != null) { + this.pumpLocationMap.put(pumpLocRef, new TreeMap<>(accountingMap)); + if (generateModifiedTimeWindow) { + timeWindowMap = this.pumpTimeWindowMap.computeIfAbsent(pumpLocRef, k -> new TimeWindowMap()); + if (!accountingMap.isEmpty()) { + try { + timeWindowMap.addTimeWindow(accountingMap.firstKey(), true, + accountingMap.lastKey(), true); + } catch (IllegalArgumentException ex) { + Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, + "Start time cannot be after end time", ex); + } + } + } + } else { + Date key; + if (preserveModifiedData) { + timeWindowMap = this.getTimeWindowMap(pumpLocRef); + if (timeWindowMap != null && !timeWindowMap.isEmpty()) { + Set timeWindowSet = timeWindowMap.getTimeWindowSet(); + + for (TimeWindow timeWindow : timeWindowSet) { + Date timeWindowStartDate = timeWindow.getStartDate(); + key = timeWindow.getStartDate(); + SortedMap modSet + = accountingMap.subMap(timeWindowStartDate, true, key, true); + if (modSet != null && !modSet.isEmpty()) { + Set modSetKeys = new HashSet<>(modSet.keySet()); + accountingMap.keySet().removeAll(modSetKeys); + } + } + } + } + + NavigableMap tempCache = new TreeMap<>(accountingMap); + tempCache = tempCache.subMap(accountingMap.firstKey(), true, + accountingMap.lastKey(), true); + boolean valuesRemoved = tempCache.keySet().removeAll(accountingMap.keySet()); + if (valuesRemoved) { + Set> entrySet = tempCache.entrySet(); + Iterator> it = entrySet.iterator(); + + breakLabel: + while (true) { + Map.Entry entry; + TimeWindowMap pumpTwMap; + do { + if (!it.hasNext()) { + break breakLabel; + } + + entry = it.next(); + key = entry.getKey(); + if (!preserveModifiedData) { + break; + } + + pumpTwMap = this.getTimeWindowMap(pumpLocRef); + } while (pumpTwMap != null && pumpTwMap.containedInTimeWindow(key, true)); + + WaterSupplyPumpAccounting value = entry.getValue(); + value.setUndefined(); + } + } + + cacheMap.putAll(accountingMap); + if (generateModifiedTimeWindow) { + TimeWindowMap timeWindowMap1 = this.pumpTimeWindowMap.get(pumpLocRef); + if (timeWindowMap1 == null) { + timeWindowMap1 = new TimeWindowMap(); + this.pumpTimeWindowMap.put(pumpLocRef, timeWindowMap1); + } + + try { + timeWindowMap1.addTimeWindow(accountingMap.firstKey(), true, + accountingMap.lastKey(), true); + } catch (IllegalArgumentException ex) { + Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, + "Start time cannot be after end time", ex); + } + } + } + } + } + + public void mergeAccounting(WaterSupplyAccounting waterSupplyAccounting, boolean generateModifiedTimeWindow, + boolean preserveModifiedData) throws DataObjectException { + if (!this.getWaterUser().equals(waterSupplyAccounting.getWaterUser())) { + throw new DataObjectException("Cannot merge accountings for different contracts."); + } else { + Map> allPumpAccounting + = waterSupplyAccounting.getAllPumpAccounting(); + Set>> entrySet + = allPumpAccounting.entrySet(); + + for (Map.Entry> entry : entrySet) { + this.mergeAccounting(entry.getKey(), entry.getValue(), + generateModifiedTimeWindow, preserveModifiedData); + } + } + } + + public void removeUndefinedValues() { + Set>> entrySet + = this.pumpLocationMap.entrySet(); + + for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { + NavigableMap pumpAccounting = cwmsIdNavigableMapEntry.getValue(); + Set> valueEntrySet = pumpAccounting.entrySet(); + Set removeKeys = new HashSet<>(); + + for (Map.Entry valueEntry : valueEntrySet) { + WaterSupplyPumpAccounting value = valueEntry.getValue(); + + if (!RMAConst.isValidValue(value.getFlow())) { + removeKeys.add(valueEntry.getKey()); + } + } + + pumpAccounting.keySet().removeAll(removeKeys); + } + } + + public void clearPumpTimeWindowMaps() { + Set> entrySet = this.pumpTimeWindowMap.entrySet(); + + for (Map.Entry cwmsIdTimeWindowMapEntry : entrySet) { + (cwmsIdTimeWindowMapEntry.getValue()).clear(); + } + } + + public TimeWindowMap getTimeWindowMap(CwmsId pumpId) { + return this.pumpTimeWindowMap.get(pumpId); + } + + public WaterSupplyAccounting windowAndLimit(Date startTime, Date endTime, boolean headFlag, int rowLimit) { + WaterSupplyAccounting dst = new WaterSupplyAccounting(this.contractName, this.waterUser, new HashMap<>(), + new HashMap<>()); + Map> allPumpAccounting + = this.getAllPumpAccounting(startTime, endTime); + if (allPumpAccounting != null && !allPumpAccounting.isEmpty()) { + Set>> entrySet + = allPumpAccounting.entrySet(); + Iterator>> it = entrySet.iterator(); + + while (true) { + NavigableMap dstPumpAccounting; + NavigableMap srcPumpAccounting; + do { + if (!it.hasNext()) { + return dst; + } + + Map.Entry> entry = it.next(); + CwmsId pumpId = entry.getKey(); + dstPumpAccounting = dst.buildPumpAccounting(pumpId); + srcPumpAccounting = entry.getValue(); + } while (srcPumpAccounting.isEmpty()); + + Object keySet; + if (headFlag) { + keySet = srcPumpAccounting.keySet(); + } else { + keySet = srcPumpAccounting.descendingKeySet(); + } + + int num = 0; + + for (Iterator>> srcIt + = ((Set) keySet).iterator(); srcIt.hasNext(); ++num) { + Date key = (Date) srcIt.next(); + if (num >= rowLimit) { + break; + } + + WaterSupplyPumpAccounting srcValue = srcPumpAccounting.get(key); + WaterSupplyPumpAccounting srcClone = new WaterSupplyPumpAccounting(srcValue.getWaterUser(), + srcValue.getContractName(), srcValue.getPumpLocation(), srcValue.getTransferType(), + srcValue.getFlow(), srcValue.getTransferDate(), srcValue.getComment()); + dstPumpAccounting.put(key, srcClone); + } + + } + } else { + return dst; + } } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java new file mode 100644 index 000000000..27dc042aa --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java @@ -0,0 +1,105 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; +import java.util.Date; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, + aliases = {Formats.DEFAULT, Formats.JSON}) +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) +public class WaterSupplyPumpAccounting extends CwmsDTOBase { + @JsonProperty(required = true) + private WaterUser waterUser; + @JsonProperty(required = true) + private String contractName; + @JsonProperty(required = true) + private Location pumpLocation; + @JsonProperty(required = true) + private LookupType transferType; + @JsonProperty(required = true) + private Double flow; + @JsonProperty(required = true) + private Date transferDate; + private String comment; + + private WaterSupplyPumpAccounting() { + } + + public WaterSupplyPumpAccounting(WaterUser waterUser, String contractName, Location pumpLocation, + LookupType transferType, Double flow, Date transferDate, String comment) { + this.waterUser = waterUser; + this.contractName = contractName; + this.pumpLocation = pumpLocation; + this.transferType = transferType; + this.flow = flow; + this.transferDate = transferDate; + this.comment = comment; + } + + public WaterUser getWaterUser() { + return this.waterUser; + } + + public String getContractName() { + return this.contractName; + } + + public Location getPumpLocation() { + return this.pumpLocation; + } + + public LookupType getTransferType() { + return this.transferType; + } + + public Double getFlow() { + return this.flow; + } + + public Date getTransferDate() { + return this.transferDate; + } + + public String getComment() { + return this.comment; + } + + public void setUndefined() { + this.flow = Double.NEGATIVE_INFINITY; + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java similarity index 81% rename from cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java rename to cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java index e46907738..b703d450b 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java @@ -35,7 +35,6 @@ import cwms.cda.helpers.DTOMatch; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.org.apache.commons.io.IOUtils; - import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.ZoneId; @@ -43,33 +42,33 @@ import static org.junit.jupiter.api.Assertions.*; -class WaterSupplyAccountingTest { +class WaterSupplyPumpAccountingTest { private static final String OFFICE = "SPK"; @Test - void testWaterSupplyAccountingSerializationRoundTrip() { + void testWaterSupplyPumpAccountingSerializationRoundTrip() { WaterUser user = new WaterUser("Test Entity", new CwmsId.Builder() .withOfficeId(OFFICE) .withName("Test Location") .build(), "Test Water Right"); - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(user, "Test Contract", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(user, "Test Contract", new Location.Builder(OFFICE, "NAME").withLocationType("PUMP").withNation(Nation.US) .withPublicName("PUMP 1").withLatitude(56.8).withLongitude(31.9).withDescription("PUMP") .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGSV84").build(), new LookupType.Builder().withActive(true).withTooltip("Test transfer Tip").withOfficeId(OFFICE) .withDisplayValue("Transfer").build(), 1.0, new Date(), "Test Comment"); - String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), - waterSupplyAccounting); - WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, - WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); - DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyPumpAccounting.class), + waterSupplyPumpAccounting); + WaterSupplyPumpAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyPumpAccounting.class), serialized, WaterSupplyPumpAccounting.class); + DTOMatch.assertMatch(waterSupplyPumpAccounting, deserialized); } @Test - void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Exception { + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -86,9 +85,9 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); assertNotNull(resource); String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); - WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, - WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); - DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + WaterSupplyPumpAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyPumpAccounting.class), serialized, WaterSupplyPumpAccounting.class); + DTOMatch.assertMatch(waterSupplyPumpAccounting, deserialized); } @@ -96,7 +95,7 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception void testValidate() { assertAll( () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -109,10 +108,10 @@ void testValidate() { .withStateInitial("OR").withCountyName("Test County").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); - assertDoesNotThrow(waterSupplyAccounting::validate, "Expected validation to pass"); + assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); }, () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -125,21 +124,21 @@ void testValidate() { .withStateInitial("OR").withCountyName("Test County").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); - assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null contract name"); }, () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", null, new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); - assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null location"); }, () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -151,11 +150,11 @@ void testValidate() { .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") .withStateInitial("OR").withCountyName("Test County").build(), null, 1.0, new Date(10000012648112L), "Test Comment"); - assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer type"); }, () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -168,11 +167,11 @@ void testValidate() { .withStateInitial("OR").withCountyName("Test County").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), null, new Date(10000012648112L), "Test Comment"); - assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null flow value"); }, () -> { - WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting(new WaterUser("Test Entity", + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) @@ -185,7 +184,7 @@ void testValidate() { .withStateInitial("OR").withCountyName("Test County").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, null, "Test Comment"); - assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer date"); } ); diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index 5b44199cb..07ac0b7ff 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -47,7 +47,7 @@ import cwms.cda.data.dto.stream.StreamLocation; import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; -import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; +import cwms.cda.data.dto.watersupply.WaterSupplyPumpAccounting; import cwms.cda.data.dto.watersupply.WaterSupplyPump; import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; @@ -356,7 +356,7 @@ private static void assertMatch(Double first, Double second, String message) { assertMatch(first, second, DEFAULT_DELTA, message); } - public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { + public static void assertMatch(WaterSupplyPumpAccounting first, WaterSupplyPumpAccounting second) { assertAll( () -> assertMatch(first.getWaterUser(), second.getWaterUser()), () -> assertEquals(first.getContractName(), second.getContractName()), From 415f9b4226d2e66d549ad72f9c6a9c4d5e1b8ef3 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Fri, 19 Jul 2024 11:39:01 -0700 Subject: [PATCH 23/39] Changed DTO Location from Location object to CwmsId --- .../WaterSupplyPumpAccounting.java | 8 +-- .../WaterSupplyPumpAccountingTest.java | 64 +++---------------- .../watersupply/water_supply_accounting.json | 22 +------ 3 files changed, 14 insertions(+), 80 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java index 27dc042aa..888fdc0a8 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java @@ -31,7 +31,7 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.data.dto.Location; +import cwms.cda.data.dto.CwmsId; import cwms.cda.data.dto.LookupType; import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; @@ -48,7 +48,7 @@ public class WaterSupplyPumpAccounting extends CwmsDTOBase { @JsonProperty(required = true) private String contractName; @JsonProperty(required = true) - private Location pumpLocation; + private CwmsId pumpLocation; @JsonProperty(required = true) private LookupType transferType; @JsonProperty(required = true) @@ -60,7 +60,7 @@ public class WaterSupplyPumpAccounting extends CwmsDTOBase { private WaterSupplyPumpAccounting() { } - public WaterSupplyPumpAccounting(WaterUser waterUser, String contractName, Location pumpLocation, + public WaterSupplyPumpAccounting(WaterUser waterUser, String contractName, CwmsId pumpLocation, LookupType transferType, Double flow, Date transferDate, String comment) { this.waterUser = waterUser; this.contractName = contractName; @@ -79,7 +79,7 @@ public String getContractName() { return this.contractName; } - public Location getPumpLocation() { + public CwmsId getPumpLocation() { return this.pumpLocation; } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java index b703d450b..21f4a3d4e 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java @@ -26,10 +26,10 @@ package cwms.cda.data.dto.watersupply; -import cwms.cda.api.enums.Nation; +import static org.junit.jupiter.api.Assertions.*; + import cwms.cda.api.errors.FieldException; import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.Location; import cwms.cda.data.dto.LookupType; import cwms.cda.formatters.Formats; import cwms.cda.helpers.DTOMatch; @@ -37,10 +37,8 @@ import org.testcontainers.shaded.org.apache.commons.io.IOUtils; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.time.ZoneId; import java.util.Date; -import static org.junit.jupiter.api.Assertions.*; class WaterSupplyPumpAccountingTest { private static final String OFFICE = "SPK"; @@ -54,9 +52,7 @@ void testWaterSupplyPumpAccountingSerializationRoundTrip() { "Test Water Right"); WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(user, "Test Contract", - new Location.Builder(OFFICE, "NAME").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("PUMP 1").withLatitude(56.8).withLongitude(31.9).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGSV84").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("NAME").build(), new LookupType.Builder().withActive(true).withTooltip("Test transfer Tip").withOfficeId(OFFICE) .withDisplayValue("Transfer").build(), 1.0, new Date(), "Test Comment"); String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyPumpAccounting.class), @@ -71,14 +67,7 @@ void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Except WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); InputStream resource = this.getClass().getResourceAsStream( @@ -98,14 +87,7 @@ void testValidate() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); @@ -114,14 +96,7 @@ void testValidate() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " @@ -141,14 +116,7 @@ void testValidate() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), null, 1.0, new Date(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer type"); @@ -157,14 +125,7 @@ void testValidate() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), null, new Date(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " @@ -174,14 +135,7 @@ void testValidate() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), null, - new Location.Builder(OFFICE, "Test Pump").withLocationType("PUMP").withNation(Nation.US) - .withPublicName("Test Public Name").withLatitude(45.0).withLongitude(-120.0).withDescription("PUMP") - .withTimeZoneName(ZoneId.of("UTC")).withLocationKind("PUMP").withHorizontalDatum("WGS84") - .withElevation(1000.0).withMapLabel("Test Map Label").withBoundingOfficeId("SPK") - .withElevationUnits("m").withActive(true).withTimeZoneName(ZoneId.of("UTC")) - .withVerticalDatum("NGVD29").withDescription("Test Description").withLocationKind("PUMP") - .withPublishedLatitude(45.0).withPublishedLongitude(-120.0).withLongName("Test Long Name") - .withStateInitial("OR").withCountyName("Test County").build(), + new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build(), 1.0, null, "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 94f0751a4..cd363dba9 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -9,28 +9,8 @@ }, "contract-name": "Test Contract", "pump-location": { - "name": "Test Pump", "office-id": "SPK", - "latitude": 45.0, - "longitude": -120.0, - "active": true, - "description": "Test Description", - "map-label": "Test Map Label", - "elevation": 1000.0, - "elevation-units": "m", - "vertical-datum": "NGVD29", - "horizontal-datum": "WGS84", - "published-latitude": 45.0, - "published-longitude": -120.0, - "state-initial": "OR", - "location-kind": "PUMP", - "location-type": "PUMP", - "nation": "US", - "county-name": "Test County", - "timezone-name": "UTC", - "long-name": "Test Long Name", - "public-name": "Test Public Name", - "bounding-office-id": "SPK" + "name": "Test Pump" }, "transfer-type": { "office-id": "SPK", From 4108154fbfd7005c2b7809656dc5e14f3bbcf484 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 22 Jul 2024 12:10:00 -0700 Subject: [PATCH 24/39] Updated JSON input, renamed Project Location Ref to Project ID --- .../cwms/cda/data/dto/watersupply/water_supply_accounting.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index cd363dba9..9a563fc6d 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -1,7 +1,7 @@ { "water-user": { "entity-name": "Test Entity", - "project-location-ref": { + "project-id": { "name": "Test Location", "office-id": "SPK" }, From 3b11d17f02e7239cef5d18ce3af0e1c29958b9f7 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Mon, 22 Jul 2024 16:40:08 -0700 Subject: [PATCH 25/39] Updated Dates to Instant --- .../watersupply/WaterSupplyAccounting.java | 157 ++++++------------ .../WaterSupplyPumpAccounting.java | 8 +- .../WaterSupplyPumpAccountingTest.java | 16 +- .../watersupply/water_supply_accounting.json | 2 +- 4 files changed, 66 insertions(+), 117 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index e88d99bcd..c7db098d5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -34,8 +34,9 @@ import hec.data.DataObjectException; import hec.data.TimeWindow; import hec.data.TimeWindowMap; + +import java.time.Instant; import java.util.Collection; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -47,16 +48,17 @@ import java.util.logging.Level; import java.util.logging.Logger; import rma.util.RMAConst; +import java.util.Date; @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) public class WaterSupplyAccounting extends CwmsDTOBase { private final String contractName; private final WaterUser waterUser; - private final Map> pumpLocationMap; + private final Map> pumpLocationMap; private final Map pumpTimeWindowMap; public WaterSupplyAccounting(String contractName, WaterUser waterUser, - Map> pumpLocationMap, + Map> pumpLocationMap, Map pumpTimeWindowMap) { this.contractName = contractName; this.waterUser = waterUser; @@ -72,7 +74,7 @@ public WaterUser getWaterUser() { return this.waterUser; } - public Map> getPumpLocationMap() { + public Map> getPumpLocationMap() { return this.pumpLocationMap; } @@ -80,10 +82,10 @@ public Map getPumpTimeWindowMap() { return this.pumpTimeWindowMap; } - public Map> getAllPumpAccounting() { - Map> output = new HashMap<>(); + public Map> getAllPumpAccounting() { + Map> output = new HashMap<>(); - for (Map.Entry> cwmsIdNavigableMapEntry : this.pumpLocationMap.entrySet()) { + for (Map.Entry> cwmsIdNavigableMapEntry : this.pumpLocationMap.entrySet()) { output.put(cwmsIdNavigableMapEntry.getKey(), new TreeMap<>(cwmsIdNavigableMapEntry.getValue())); } return output; @@ -91,48 +93,48 @@ public Map> getAllPumpAcco public int size() { int size = 0; - Collection> values = this.pumpLocationMap.values(); + Collection> values = this.pumpLocationMap.values(); - NavigableMap value; - for (Iterator> it = values.iterator(); it.hasNext(); size += value.size()) { + NavigableMap value; + for (Iterator> it = values.iterator(); it.hasNext(); size += value.size()) { value = it.next(); } return size; } - public Map> getAllPumpAccounting(Date startDate, - Date endDate) { - Map> output = new HashMap<>(); - Set>> entrySet + public Map> getAllPumpAccounting(Instant startInstant, + Instant endInstant) { + Map> output = new HashMap<>(); + Set>> entrySet = this.pumpLocationMap.entrySet(); - for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { - NavigableMap value = cwmsIdNavigableMapEntry.getValue(); - output.put(cwmsIdNavigableMapEntry.getKey(), value.subMap(startDate, true, endDate, true)); + for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { + NavigableMap value = cwmsIdNavigableMapEntry.getValue(); + output.put(cwmsIdNavigableMapEntry.getKey(), value.subMap(startInstant, true, endInstant, true)); } return output; } - public NavigableMap getPumpAccounting(CwmsId pumpId) { - NavigableMap map = this.pumpLocationMap.get(pumpId); + public NavigableMap getPumpAccounting(CwmsId pumpId) { + NavigableMap map = this.pumpLocationMap.get(pumpId); if (map == null) { map = this.buildPumpAccounting(pumpId); } return map; } - public NavigableMap getPumpAccounting(CwmsId pumpId, Date startDate, - Date endDate) { - NavigableMap map = this.pumpLocationMap.get(pumpId); + public NavigableMap getPumpAccounting(CwmsId pumpId, Instant startInstant, + Instant endInstant) { + NavigableMap map = this.pumpLocationMap.get(pumpId); if (map == null) { map = this.buildPumpAccounting(pumpId); return map; } - return map.subMap(startDate, true, endDate, true); + return map.subMap(startInstant, true, endInstant, true); } - public NavigableMap buildPumpAccounting(CwmsId pumpId) { - NavigableMap accountingMap = this.pumpLocationMap.get(pumpId); + public NavigableMap buildPumpAccounting(CwmsId pumpId) { + NavigableMap accountingMap = this.pumpLocationMap.get(pumpId); if (accountingMap != null) { return accountingMap; } else { @@ -142,10 +144,10 @@ public NavigableMap buildPumpAccounting(CwmsId } } - public void mergeAccounting(CwmsId pumpLocRef, NavigableMap accountingMap, + public void mergeAccounting(CwmsId pumpLocRef, NavigableMap accountingMap, boolean generateModifiedTimeWindow, boolean preserveModifiedData) { if (pumpLocRef != null && accountingMap != null && !accountingMap.isEmpty()) { - NavigableMap cacheMap + NavigableMap cacheMap = this.buildPumpAccounting(pumpLocRef); TimeWindowMap timeWindowMap; if (cacheMap != null) { @@ -154,8 +156,8 @@ public void mergeAccounting(CwmsId pumpLocRef, NavigableMap new TimeWindowMap()); if (!accountingMap.isEmpty()) { try { - timeWindowMap.addTimeWindow(accountingMap.firstKey(), true, - accountingMap.lastKey(), true); + timeWindowMap.addTimeWindow(new Date(accountingMap.firstKey().toEpochMilli()), true, + new Date(accountingMap.lastKey().toEpochMilli()), true); } catch (IllegalArgumentException ex) { Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, "Start time cannot be after end time", ex); @@ -163,36 +165,36 @@ public void mergeAccounting(CwmsId pumpLocRef, NavigableMap timeWindowSet = timeWindowMap.getTimeWindowSet(); for (TimeWindow timeWindow : timeWindowSet) { - Date timeWindowStartDate = timeWindow.getStartDate(); - key = timeWindow.getStartDate(); - SortedMap modSet - = accountingMap.subMap(timeWindowStartDate, true, key, true); + Instant timeWindowStartInstant = timeWindow.getStartDate().toInstant(); + key = timeWindow.getStartDate().toInstant(); + SortedMap modSet + = accountingMap.subMap(timeWindowStartInstant, true, key, true); if (modSet != null && !modSet.isEmpty()) { - Set modSetKeys = new HashSet<>(modSet.keySet()); + Set modSetKeys = new HashSet<>(modSet.keySet()); accountingMap.keySet().removeAll(modSetKeys); } } } } - NavigableMap tempCache = new TreeMap<>(accountingMap); + NavigableMap tempCache = new TreeMap<>(accountingMap); tempCache = tempCache.subMap(accountingMap.firstKey(), true, accountingMap.lastKey(), true); boolean valuesRemoved = tempCache.keySet().removeAll(accountingMap.keySet()); if (valuesRemoved) { - Set> entrySet = tempCache.entrySet(); - Iterator> it = entrySet.iterator(); + Set> entrySet = tempCache.entrySet(); + Iterator> it = entrySet.iterator(); breakLabel: while (true) { - Map.Entry entry; + Map.Entry entry; TimeWindowMap pumpTwMap; do { if (!it.hasNext()) { @@ -206,7 +208,7 @@ public void mergeAccounting(CwmsId pumpLocRef, NavigableMap> allPumpAccounting + Map> allPumpAccounting = waterSupplyAccounting.getAllPumpAccounting(); - Set>> entrySet + Set>> entrySet = allPumpAccounting.entrySet(); - for (Map.Entry> entry : entrySet) { + for (Map.Entry> entry : entrySet) { this.mergeAccounting(entry.getKey(), entry.getValue(), generateModifiedTimeWindow, preserveModifiedData); } @@ -251,15 +253,15 @@ public void mergeAccounting(WaterSupplyAccounting waterSupplyAccounting, boolean } public void removeUndefinedValues() { - Set>> entrySet + Set>> entrySet = this.pumpLocationMap.entrySet(); - for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { - NavigableMap pumpAccounting = cwmsIdNavigableMapEntry.getValue(); - Set> valueEntrySet = pumpAccounting.entrySet(); - Set removeKeys = new HashSet<>(); + for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { + NavigableMap pumpAccounting = cwmsIdNavigableMapEntry.getValue(); + Set> valueEntrySet = pumpAccounting.entrySet(); + Set removeKeys = new HashSet<>(); - for (Map.Entry valueEntry : valueEntrySet) { + for (Map.Entry valueEntry : valueEntrySet) { WaterSupplyPumpAccounting value = valueEntry.getValue(); if (!RMAConst.isValidValue(value.getFlow())) { @@ -282,57 +284,4 @@ public void clearPumpTimeWindowMaps() { public TimeWindowMap getTimeWindowMap(CwmsId pumpId) { return this.pumpTimeWindowMap.get(pumpId); } - - public WaterSupplyAccounting windowAndLimit(Date startTime, Date endTime, boolean headFlag, int rowLimit) { - WaterSupplyAccounting dst = new WaterSupplyAccounting(this.contractName, this.waterUser, new HashMap<>(), - new HashMap<>()); - Map> allPumpAccounting - = this.getAllPumpAccounting(startTime, endTime); - if (allPumpAccounting != null && !allPumpAccounting.isEmpty()) { - Set>> entrySet - = allPumpAccounting.entrySet(); - Iterator>> it = entrySet.iterator(); - - while (true) { - NavigableMap dstPumpAccounting; - NavigableMap srcPumpAccounting; - do { - if (!it.hasNext()) { - return dst; - } - - Map.Entry> entry = it.next(); - CwmsId pumpId = entry.getKey(); - dstPumpAccounting = dst.buildPumpAccounting(pumpId); - srcPumpAccounting = entry.getValue(); - } while (srcPumpAccounting.isEmpty()); - - Object keySet; - if (headFlag) { - keySet = srcPumpAccounting.keySet(); - } else { - keySet = srcPumpAccounting.descendingKeySet(); - } - - int num = 0; - - for (Iterator>> srcIt - = ((Set) keySet).iterator(); srcIt.hasNext(); ++num) { - Date key = (Date) srcIt.next(); - if (num >= rowLimit) { - break; - } - - WaterSupplyPumpAccounting srcValue = srcPumpAccounting.get(key); - WaterSupplyPumpAccounting srcClone = new WaterSupplyPumpAccounting(srcValue.getWaterUser(), - srcValue.getContractName(), srcValue.getPumpLocation(), srcValue.getTransferType(), - srcValue.getFlow(), srcValue.getTransferDate(), srcValue.getComment()); - dstPumpAccounting.put(key, srcClone); - } - - } - } else { - return dst; - } - } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java index 888fdc0a8..c25503b53 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java @@ -36,7 +36,7 @@ import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; -import java.util.Date; +import java.time.Instant; @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, aliases = {Formats.DEFAULT, Formats.JSON}) @@ -54,14 +54,14 @@ public class WaterSupplyPumpAccounting extends CwmsDTOBase { @JsonProperty(required = true) private Double flow; @JsonProperty(required = true) - private Date transferDate; + private Instant transferDate; private String comment; private WaterSupplyPumpAccounting() { } public WaterSupplyPumpAccounting(WaterUser waterUser, String contractName, CwmsId pumpLocation, - LookupType transferType, Double flow, Date transferDate, String comment) { + LookupType transferType, Double flow, Instant transferDate, String comment) { this.waterUser = waterUser; this.contractName = contractName; this.pumpLocation = pumpLocation; @@ -91,7 +91,7 @@ public Double getFlow() { return this.flow; } - public Date getTransferDate() { + public Instant getTransferDate() { return this.transferDate; } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java index 21f4a3d4e..6a591a1fe 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java @@ -37,7 +37,7 @@ import org.testcontainers.shaded.org.apache.commons.io.IOUtils; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.Date; +import java.time.Instant; class WaterSupplyPumpAccountingTest { @@ -54,7 +54,7 @@ void testWaterSupplyPumpAccountingSerializationRoundTrip() { WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(user, "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("NAME").build(), new LookupType.Builder().withActive(true).withTooltip("Test transfer Tip").withOfficeId(OFFICE) - .withDisplayValue("Transfer").build(), 1.0, new Date(), "Test Comment"); + .withDisplayValue("Transfer").build(), 1.0, Instant.now(), "Test Comment"); String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyPumpAccounting.class), waterSupplyPumpAccounting); WaterSupplyPumpAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, @@ -69,7 +69,7 @@ void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Except "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochMilli(10000012648000L), "Test Comment"); InputStream resource = this.getClass().getResourceAsStream( "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); assertNotNull(resource); @@ -89,7 +89,7 @@ void testValidate() { "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); }, () -> { @@ -98,7 +98,7 @@ void testValidate() { null, new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null contract name"); }, @@ -108,7 +108,7 @@ void testValidate() { "Test Contract", null, new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, new Date(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null location"); }, @@ -117,7 +117,7 @@ void testValidate() { new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - null, 1.0, new Date(10000012648112L), "Test Comment"); + null, 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer type"); }, @@ -127,7 +127,7 @@ void testValidate() { null, new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), null, new Date(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), null, Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null flow value"); }, diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 9a563fc6d..94e796540 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -19,6 +19,6 @@ "active": true }, "flow": 1.0, - "transfer-date": 10000012648112, + "transfer-date": 10000012648000, "comment": "Test Comment" } \ No newline at end of file From 376b9ec6e70010b510e8ac34f0cf618e5e8cfe63 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 24 Jul 2024 12:46:38 -0700 Subject: [PATCH 26/39] Incorporated changed Water Supply DTOs (changed constructors to builders) --- .../WaterSupplyPumpAccountingTest.java | 59 ++++++++++++------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java index 6a591a1fe..39094b816 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java @@ -45,11 +45,12 @@ class WaterSupplyPumpAccountingTest { @Test void testWaterSupplyPumpAccountingSerializationRoundTrip() { - WaterUser user = new WaterUser("Test Entity", new CwmsId.Builder() - .withOfficeId(OFFICE) - .withName("Test Location") - .build(), - "Test Water Right"); + WaterUser user = new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder() + .withOfficeId(OFFICE) + .withName("Test Location") + .build()) + .withWaterRight("Test Water Right").build(); WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(user, "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("NAME").build(), @@ -64,8 +65,10 @@ void testWaterSupplyPumpAccountingSerializationRoundTrip() { @Test void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Exception { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) @@ -84,8 +87,10 @@ void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Except void testValidate() { assertAll( () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) @@ -93,18 +98,23 @@ void testValidate() { assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), null, new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), 1.0, + Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null contract name"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), "Test Contract", null, new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) @@ -113,8 +123,10 @@ void testValidate() { + "fail due to null location"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), "Test Contract", new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), null, 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); @@ -122,18 +134,23 @@ void testValidate() { + "fail due to null transfer type"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), null, new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), null, Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withDisplayValue("Test Transfer Type").build(), null, + Instant.ofEpochSecond(10000012648112L), "Test Comment"); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null flow value"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser("Test Entity", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location").build(), "Test Water Right"), + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build(), null, new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) From 9cc67e319cc174ebe4d521497edcfde1130f71a2 Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Wed, 24 Jul 2024 15:08:56 -0700 Subject: [PATCH 27/39] Switched DTOs to Builder Constructors --- .../watersupply/WaterSupplyAccounting.java | 73 ++++++++--- .../WaterSupplyPumpAccounting.java | 83 ++++++++++--- .../WaterSupplyPumpAccountingTest.java | 114 ++++++++++-------- 3 files changed, 184 insertions(+), 86 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index c7db098d5..9e6db76bb 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -26,6 +26,7 @@ package cwms.cda.data.dto.watersupply; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import cwms.cda.data.dto.CwmsDTOBase; import cwms.cda.data.dto.CwmsId; import cwms.cda.formatters.Formats; @@ -34,9 +35,9 @@ import hec.data.DataObjectException; import hec.data.TimeWindow; import hec.data.TimeWindowMap; - import java.time.Instant; import java.util.Collection; +import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -48,22 +49,54 @@ import java.util.logging.Level; import java.util.logging.Logger; import rma.util.RMAConst; -import java.util.Date; + +@JsonDeserialize(builder = WaterSupplyAccounting.Builder.class) @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) -public class WaterSupplyAccounting extends CwmsDTOBase { +public final class WaterSupplyAccounting extends CwmsDTOBase { private final String contractName; private final WaterUser waterUser; private final Map> pumpLocationMap; private final Map pumpTimeWindowMap; - public WaterSupplyAccounting(String contractName, WaterUser waterUser, - Map> pumpLocationMap, - Map pumpTimeWindowMap) { - this.contractName = contractName; - this.waterUser = waterUser; - this.pumpLocationMap = pumpLocationMap; - this.pumpTimeWindowMap = pumpTimeWindowMap; + private WaterSupplyAccounting(Builder builder) { + this.contractName = builder.contractName; + this.waterUser = builder.waterUser; + this.pumpLocationMap = builder.pumpLocationMap; + this.pumpTimeWindowMap = builder.pumpTimeWindowMap; + } + + public static class Builder { + private String contractName; + private WaterUser waterUser; + private Map> pumpLocationMap; + private Map pumpTimeWindowMap; + + public Builder withContractName(String contractName) { + this.contractName = contractName; + return this; + } + + public Builder withWaterUser(WaterUser waterUser) { + this.waterUser = waterUser; + return this; + } + + public Builder withPumpLocationMap( + Map> pumpLocationMap) { + this.pumpLocationMap = pumpLocationMap; + return this; + } + + public Builder withPumpTimeWindowMap(Map pumpTimeWindowMap) { + this.pumpTimeWindowMap = pumpTimeWindowMap; + return this; + } + + public WaterSupplyAccounting build() { + return new WaterSupplyAccounting(this); + } + } public String getContractName() { @@ -85,7 +118,8 @@ public Map getPumpTimeWindowMap() { public Map> getAllPumpAccounting() { Map> output = new HashMap<>(); - for (Map.Entry> cwmsIdNavigableMapEntry : this.pumpLocationMap.entrySet()) { + for (Map.Entry> cwmsIdNavigableMapEntry + : this.pumpLocationMap.entrySet()) { output.put(cwmsIdNavigableMapEntry.getKey(), new TreeMap<>(cwmsIdNavigableMapEntry.getValue())); } return output; @@ -96,7 +130,8 @@ public int size() { Collection> values = this.pumpLocationMap.values(); NavigableMap value; - for (Iterator> it = values.iterator(); it.hasNext(); size += value.size()) { + for (Iterator> it = values.iterator(); + it.hasNext(); size += value.size()) { value = it.next(); } return size; @@ -110,7 +145,8 @@ public Map> getAllPumpA for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { NavigableMap value = cwmsIdNavigableMapEntry.getValue(); - output.put(cwmsIdNavigableMapEntry.getKey(), value.subMap(startInstant, true, endInstant, true)); + output.put(cwmsIdNavigableMapEntry.getKey(), + value.subMap(startInstant, true, endInstant, true)); } return output; } @@ -156,8 +192,8 @@ public void mergeAccounting(CwmsId pumpLocRef, NavigableMap new TimeWindowMap()); if (!accountingMap.isEmpty()) { try { - timeWindowMap.addTimeWindow(new Date(accountingMap.firstKey().toEpochMilli()), true, - new Date(accountingMap.lastKey().toEpochMilli()), true); + timeWindowMap.addTimeWindow(new Date(accountingMap.firstKey().toEpochMilli()), + true, new Date(accountingMap.lastKey().toEpochMilli()), true); } catch (IllegalArgumentException ex) { Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, "Start time cannot be after end time", ex); @@ -208,7 +244,8 @@ public void mergeAccounting(CwmsId pumpLocRef, NavigableMap { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - "Test Contract", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withWaterRight("Test Water Right").build()).withContractName("Test Contract") + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) + .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder() .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - null, - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, - Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withWaterRight("Test Water Right").build()) + .withContractName(null).withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true) + .withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) + .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null contract name"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder() .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - "Test Contract", - null, - new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withWaterRight("Test Water Right").build()) + .withContractName("Test Contract") + .withTransferType(null).withTransferType(new LookupType.Builder().withActive(true) + .withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()) + .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withComment("Test Comment").build(); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null location"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder() .withEntityName("Test Entity").withProjectId(new CwmsId.Builder() .withOfficeId(OFFICE).withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - "Test Contract", - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - null, 1.0, Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withWaterRight("Test Water Right").build()) + .withContractName("Test Contract").withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Pump").build()).withTransferType(null) + .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer type"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - null, - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), null, - Instant.ofEpochSecond(10000012648112L), "Test Comment"); + .withWaterRight("Test Water Right").build()) + .withContractName("Test Contract").withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip"). + withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()).withFlow(null) + .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null flow value"); }, () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() + .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) - .withWaterRight("Test Water Right").build(), - null, - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build(), - new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build(), 1.0, null, "Test Comment"); + .withWaterRight("Test Water Right").build()).withContractName("Test Contract") + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip") + .withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) + .withFlow(1.0).withTransferDate(null).withComment("Test Comment").build(); assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " + "fail due to null transfer date"); } From 6e21d9550d1eec7b769fa80f9065373b05f378ba Mon Sep 17 00:00:00 2001 From: Zachary Olson Date: Thu, 25 Jul 2024 11:01:18 -0700 Subject: [PATCH 28/39] Reworked DTO to clarify Structure for JSON --- ...umpAccounting.java => PumpAccounting.java} | 53 +--- .../watersupply/WaterSupplyAccounting.java | 285 ++---------------- .../dto/watersupply/PumpAccountingTest.java | 142 +++++++++ .../WaterSupplyPumpAccountingTest.java | 178 ----------- .../test/java/cwms/cda/helpers/DTOMatch.java | 31 +- .../watersupply/water_supply_accounting.json | 47 ++- 6 files changed, 232 insertions(+), 504 deletions(-) rename cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/{WaterSupplyPumpAccounting.java => PumpAccounting.java} (65%) create mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java similarity index 65% rename from cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java rename to cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java index 59808b542..4af9b4088 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java @@ -26,42 +26,27 @@ package cwms.cda.data.dto.watersupply; -import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsDTOBase; import cwms.cda.data.dto.CwmsId; import cwms.cda.data.dto.LookupType; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.annotations.FormattableWith; -import cwms.cda.formatters.json.JsonV1; import java.time.Instant; -@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, - aliases = {Formats.DEFAULT, Formats.JSON}) -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonDeserialize(builder = WaterSupplyPumpAccounting.Builder.class) -@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) -public class WaterSupplyPumpAccounting extends CwmsDTOBase { - @JsonProperty(required = true) - private final WaterUser waterUser; - @JsonProperty(required = true) - private final String contractName; + +@JsonDeserialize(builder = PumpAccounting.Builder.class) +public final class PumpAccounting extends CwmsDTOBase { @JsonProperty(required = true) private final CwmsId pumpLocation; @JsonProperty(required = true) private final LookupType transferType; @JsonProperty(required = true) - private Double flow; + private final Double flow; @JsonProperty(required = true) private final Instant transferDate; private final String comment; - private WaterSupplyPumpAccounting(Builder builder) { - this.waterUser = builder.waterUser; - this.contractName = builder.contractName; + private PumpAccounting(Builder builder) { this.pumpLocation = builder.pumpLocation; this.transferType = builder.transferType; this.flow = builder.flow; @@ -69,14 +54,6 @@ private WaterSupplyPumpAccounting(Builder builder) { this.comment = builder.comment; } - public WaterUser getWaterUser() { - return this.waterUser; - } - - public String getContractName() { - return this.contractName; - } - public CwmsId getPumpLocation() { return this.pumpLocation; } @@ -97,29 +74,13 @@ public String getComment() { return this.comment; } - public void setUndefined() { - this.flow = Double.NEGATIVE_INFINITY; - } - public static final class Builder { - private WaterUser waterUser; - private String contractName; private CwmsId pumpLocation; private LookupType transferType; private Double flow; private Instant transferDate; private String comment; - public Builder withWaterUser(WaterUser waterUser) { - this.waterUser = waterUser; - return this; - } - - public Builder withContractName(String contractName) { - this.contractName = contractName; - return this; - } - public Builder withPumpLocation(CwmsId pumpLocation) { this.pumpLocation = pumpLocation; return this; @@ -145,8 +106,8 @@ public Builder withComment(String comment) { return this; } - public WaterSupplyPumpAccounting build() { - return new WaterSupplyPumpAccounting(this); + public PumpAccounting build() { + return new PumpAccounting(this); } } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 9e6db76bb..9b43e8446 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -26,51 +26,49 @@ package cwms.cda.data.dto.watersupply; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsDTOBase; -import cwms.cda.data.dto.CwmsId; import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; -import hec.data.DataObjectException; -import hec.data.TimeWindow; -import hec.data.TimeWindowMap; -import java.time.Instant; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.NavigableMap; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import rma.util.RMAConst; - +import java.util.List; +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, + aliases = {Formats.DEFAULT, Formats.JSON}) +@JsonInclude(JsonInclude.Include.NON_NULL) @JsonDeserialize(builder = WaterSupplyAccounting.Builder.class) @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) +@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) public final class WaterSupplyAccounting extends CwmsDTOBase { private final String contractName; private final WaterUser waterUser; - private final Map> pumpLocationMap; - private final Map pumpTimeWindowMap; + private final List pumpAccounting; private WaterSupplyAccounting(Builder builder) { this.contractName = builder.contractName; this.waterUser = builder.waterUser; - this.pumpLocationMap = builder.pumpLocationMap; - this.pumpTimeWindowMap = builder.pumpTimeWindowMap; + this.pumpAccounting = builder.pumpAccounting; + } + + public String getContractName() { + return this.contractName; } - public static class Builder { + public WaterUser getWaterUser() { + return this.waterUser; + } + + public List getPumpAccounting() { + return this.pumpAccounting; + } + + public static final class Builder { private String contractName; private WaterUser waterUser; - private Map> pumpLocationMap; - private Map pumpTimeWindowMap; + private List pumpAccounting; public Builder withContractName(String contractName) { this.contractName = contractName; @@ -82,243 +80,14 @@ public Builder withWaterUser(WaterUser waterUser) { return this; } - public Builder withPumpLocationMap( - Map> pumpLocationMap) { - this.pumpLocationMap = pumpLocationMap; - return this; - } - - public Builder withPumpTimeWindowMap(Map pumpTimeWindowMap) { - this.pumpTimeWindowMap = pumpTimeWindowMap; + public Builder withPumpAccounting( + List pumpAccounting) { + this.pumpAccounting = pumpAccounting; return this; } public WaterSupplyAccounting build() { return new WaterSupplyAccounting(this); } - - } - - public String getContractName() { - return this.contractName; - } - - public WaterUser getWaterUser() { - return this.waterUser; - } - - public Map> getPumpLocationMap() { - return this.pumpLocationMap; - } - - public Map getPumpTimeWindowMap() { - return this.pumpTimeWindowMap; - } - - public Map> getAllPumpAccounting() { - Map> output = new HashMap<>(); - - for (Map.Entry> cwmsIdNavigableMapEntry - : this.pumpLocationMap.entrySet()) { - output.put(cwmsIdNavigableMapEntry.getKey(), new TreeMap<>(cwmsIdNavigableMapEntry.getValue())); - } - return output; - } - - public int size() { - int size = 0; - Collection> values = this.pumpLocationMap.values(); - - NavigableMap value; - for (Iterator> it = values.iterator(); - it.hasNext(); size += value.size()) { - value = it.next(); - } - return size; - } - - public Map> getAllPumpAccounting(Instant startInstant, - Instant endInstant) { - Map> output = new HashMap<>(); - Set>> entrySet - = this.pumpLocationMap.entrySet(); - - for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { - NavigableMap value = cwmsIdNavigableMapEntry.getValue(); - output.put(cwmsIdNavigableMapEntry.getKey(), - value.subMap(startInstant, true, endInstant, true)); - } - return output; - } - - public NavigableMap getPumpAccounting(CwmsId pumpId) { - NavigableMap map = this.pumpLocationMap.get(pumpId); - if (map == null) { - map = this.buildPumpAccounting(pumpId); - } - return map; - } - - public NavigableMap getPumpAccounting(CwmsId pumpId, Instant startInstant, - Instant endInstant) { - NavigableMap map = this.pumpLocationMap.get(pumpId); - if (map == null) { - map = this.buildPumpAccounting(pumpId); - return map; - } - return map.subMap(startInstant, true, endInstant, true); - } - - public NavigableMap buildPumpAccounting(CwmsId pumpId) { - NavigableMap accountingMap = this.pumpLocationMap.get(pumpId); - if (accountingMap != null) { - return accountingMap; - } else { - accountingMap = new TreeMap<>(); - this.pumpLocationMap.put(pumpId, accountingMap); - return accountingMap; - } - } - - public void mergeAccounting(CwmsId pumpLocRef, NavigableMap accountingMap, - boolean generateModifiedTimeWindow, boolean preserveModifiedData) { - if (pumpLocRef != null && accountingMap != null && !accountingMap.isEmpty()) { - NavigableMap cacheMap - = this.buildPumpAccounting(pumpLocRef); - TimeWindowMap timeWindowMap; - if (cacheMap != null) { - this.pumpLocationMap.put(pumpLocRef, new TreeMap<>(accountingMap)); - if (generateModifiedTimeWindow) { - timeWindowMap = this.pumpTimeWindowMap.computeIfAbsent(pumpLocRef, k -> new TimeWindowMap()); - if (!accountingMap.isEmpty()) { - try { - timeWindowMap.addTimeWindow(new Date(accountingMap.firstKey().toEpochMilli()), - true, new Date(accountingMap.lastKey().toEpochMilli()), true); - } catch (IllegalArgumentException ex) { - Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, - "Start time cannot be after end time", ex); - } - } - } - } else { - Instant key; - if (preserveModifiedData) { - timeWindowMap = this.getTimeWindowMap(pumpLocRef); - if (timeWindowMap != null && !timeWindowMap.isEmpty()) { - Set timeWindowSet = timeWindowMap.getTimeWindowSet(); - - for (TimeWindow timeWindow : timeWindowSet) { - Instant timeWindowStartInstant = timeWindow.getStartDate().toInstant(); - key = timeWindow.getStartDate().toInstant(); - SortedMap modSet - = accountingMap.subMap(timeWindowStartInstant, true, key, true); - if (modSet != null && !modSet.isEmpty()) { - Set modSetKeys = new HashSet<>(modSet.keySet()); - accountingMap.keySet().removeAll(modSetKeys); - } - } - } - } - - NavigableMap tempCache = new TreeMap<>(accountingMap); - tempCache = tempCache.subMap(accountingMap.firstKey(), true, - accountingMap.lastKey(), true); - boolean valuesRemoved = tempCache.keySet().removeAll(accountingMap.keySet()); - if (valuesRemoved) { - Set> entrySet = tempCache.entrySet(); - Iterator> it = entrySet.iterator(); - - breakLabel: - while (true) { - Map.Entry entry; - TimeWindowMap pumpTwMap; - do { - if (!it.hasNext()) { - break breakLabel; - } - - entry = it.next(); - key = entry.getKey(); - if (!preserveModifiedData) { - break; - } - - pumpTwMap = this.getTimeWindowMap(pumpLocRef); - } while (pumpTwMap != null - && pumpTwMap.containedInTimeWindow(new Date(key.toEpochMilli()), true)); - - WaterSupplyPumpAccounting value = entry.getValue(); - value.setUndefined(); - } - } - - cacheMap.putAll(accountingMap); - if (generateModifiedTimeWindow) { - TimeWindowMap timeWindowMap1 = this.pumpTimeWindowMap.get(pumpLocRef); - if (timeWindowMap1 == null) { - timeWindowMap1 = new TimeWindowMap(); - this.pumpTimeWindowMap.put(pumpLocRef, timeWindowMap1); - } - - try { - timeWindowMap1.addTimeWindow(new Date(accountingMap.firstKey().toEpochMilli()), - true, new Date(accountingMap.lastKey().toEpochMilli()), true); - } catch (IllegalArgumentException ex) { - Logger.getLogger(WaterSupplyAccounting.class.getName()).log(Level.SEVERE, - "Start time cannot be after end time", ex); - } - } - } - } - } - - public void mergeAccounting(WaterSupplyAccounting waterSupplyAccounting, boolean generateModifiedTimeWindow, - boolean preserveModifiedData) throws DataObjectException { - if (!this.getWaterUser().equals(waterSupplyAccounting.getWaterUser())) { - throw new DataObjectException("Cannot merge accountings for different contracts."); - } else { - Map> allPumpAccounting - = waterSupplyAccounting.getAllPumpAccounting(); - Set>> entrySet - = allPumpAccounting.entrySet(); - - for (Map.Entry> entry : entrySet) { - this.mergeAccounting(entry.getKey(), entry.getValue(), - generateModifiedTimeWindow, preserveModifiedData); - } - } - } - - public void removeUndefinedValues() { - Set>> entrySet - = this.pumpLocationMap.entrySet(); - - for (Map.Entry> cwmsIdNavigableMapEntry : entrySet) { - NavigableMap pumpAccounting = cwmsIdNavigableMapEntry.getValue(); - Set> valueEntrySet = pumpAccounting.entrySet(); - Set removeKeys = new HashSet<>(); - - for (Map.Entry valueEntry : valueEntrySet) { - WaterSupplyPumpAccounting value = valueEntry.getValue(); - - if (!RMAConst.isValidValue(value.getFlow())) { - removeKeys.add(valueEntry.getKey()); - } - } - - pumpAccounting.keySet().removeAll(removeKeys); - } - } - - public void clearPumpTimeWindowMaps() { - Set> entrySet = this.pumpTimeWindowMap.entrySet(); - - for (Map.Entry cwmsIdTimeWindowMapEntry : entrySet) { - (cwmsIdTimeWindowMapEntry.getValue()).clear(); - } - } - - public TimeWindowMap getTimeWindowMap(CwmsId pumpId) { - return this.pumpTimeWindowMap.get(pumpId); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java new file mode 100644 index 000000000..e4ac9763b --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java @@ -0,0 +1,142 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import static org.junit.jupiter.api.Assertions.*; + +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.Formats; +import cwms.cda.helpers.DTOMatch; +import org.junit.jupiter.api.Test; +import org.testcontainers.shaded.org.apache.commons.io.IOUtils; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + + +class PumpAccountingTest { + private static final String OFFICE = "SPK"; + + @Test + void testWaterSupplyPumpAccountingSerializationRoundTrip() { + WaterSupplyAccounting pumpAccounting = buildTestAccounting(); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), + pumpAccounting); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(pumpAccounting, deserialized); + } + + @Test + void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Exception { + WaterSupplyAccounting pumpAccounting = buildTestAccounting(); + InputStream resource = this.getClass().getResourceAsStream( + "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(pumpAccounting, deserialized); + } + + @Test + void testValidate() { + assertAll( + () -> { + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) + .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); + assertDoesNotThrow(pumpAccounting::validate, "Expected validation to pass"); + }, + () -> { + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(null).withTransferType(new LookupType.Builder().withActive(true) + .withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()) + .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withComment("Test Comment").build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null location"); + }, + () -> { + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Pump").build()).withTransferType(null) + .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withComment("Test Comment").build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null transfer type"); + }, + () -> { + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip"). + withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()).withFlow(null) + .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null flow value"); + }, + () -> { + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip") + .withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) + .withFlow(1.0).withTransferDate(null).withComment("Test Comment").build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null transfer date"); + } + ); + } + + private WaterSupplyAccounting buildTestAccounting() { + return new WaterSupplyAccounting.Builder().withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withWaterRight("Test Water Right").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()).build()) + .withContractName("Test Contract").withPumpAccounting(buildTestPumpAccountingList()) + .build(); + } + + private List buildTestPumpAccountingList() { + List retList = new ArrayList<>(); + retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Pump").build()).withTransferType(new LookupType.Builder().withActive(true) + .withTooltip("Test Tool Tip").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) + .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); + retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Pump 2").build()).withTransferType(new LookupType.Builder().withActive(true) + .withTooltip("Test Tool Tip 2").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type 2").build()) + .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build()); + return retList; + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java deleted file mode 100644 index f3bf9b8c2..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyPumpAccountingTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.data.dto.watersupply; - -import static org.junit.jupiter.api.Assertions.*; - -import cwms.cda.api.errors.FieldException; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.LookupType; -import cwms.cda.formatters.Formats; -import cwms.cda.helpers.DTOMatch; -import org.junit.jupiter.api.Test; -import org.testcontainers.shaded.org.apache.commons.io.IOUtils; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.Instant; - - -class WaterSupplyPumpAccountingTest { - private static final String OFFICE = "SPK"; - - @Test - void testWaterSupplyPumpAccountingSerializationRoundTrip() { - WaterUser user = new WaterUser.Builder().withEntityName("Test Entity") - .withProjectId(new CwmsId.Builder() - .withOfficeId(OFFICE) - .withName("Test Location") - .build()) - .withWaterRight("Test Water Right").build(); - - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(user).withContractName("Test Contract").withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("NAME").build()) - .withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test transfer Tip").withOfficeId(OFFICE).withDisplayValue("Transfer").build()) - .withFlow(1.0).withTransferDate(Instant.now()).withComment("Test Comment").build(); - String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyPumpAccounting.class), - waterSupplyPumpAccounting); - WaterSupplyPumpAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, - WaterSupplyPumpAccounting.class), serialized, WaterSupplyPumpAccounting.class); - DTOMatch.assertMatch(waterSupplyPumpAccounting, deserialized); - } - - @Test - void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Exception { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName("Test Contract").withPumpLocation( - new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip") - .withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) - .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)) - .withComment("Test Comment").build(); - InputStream resource = this.getClass().getResourceAsStream( - "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); - assertNotNull(resource); - String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); - WaterSupplyPumpAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, - WaterSupplyPumpAccounting.class), serialized, WaterSupplyPumpAccounting.class); - DTOMatch.assertMatch(waterSupplyPumpAccounting, deserialized); - } - - - @Test - void testValidate() { - assertAll( - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") - .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()).withContractName("Test Contract") - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) - .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); - assertDoesNotThrow(waterSupplyPumpAccounting::validate, "Expected validation to pass"); - }, - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName(null).withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) - .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); - assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " - + "fail due to null contract name"); - }, - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName("Test Contract") - .withTransferType(null).withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()) - .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withComment("Test Comment").build(); - assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " - + "fail due to null location"); - }, - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName("Test Contract").withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Pump").build()).withTransferType(null) - .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); - assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " - + "fail due to null transfer type"); - }, - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") - .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName("Test Contract").withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip"). - withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()).withFlow(null) - .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); - assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " - + "fail due to null flow value"); - }, - () -> { - WaterSupplyPumpAccounting waterSupplyPumpAccounting = new WaterSupplyPumpAccounting.Builder() - .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") - .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()).withContractName("Test Contract") - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip") - .withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) - .withFlow(1.0).withTransferDate(null).withComment("Test Comment").build(); - assertThrows(FieldException.class, waterSupplyPumpAccounting::validate, "Expected validation to " - + "fail due to null transfer date"); - } - ); - } - -} diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index 07ac0b7ff..db4385a95 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -47,11 +47,13 @@ import cwms.cda.data.dto.stream.StreamLocation; import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; -import cwms.cda.data.dto.watersupply.WaterSupplyPumpAccounting; +import cwms.cda.data.dto.watersupply.PumpAccounting; +import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; import cwms.cda.data.dto.watersupply.WaterSupplyPump; import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.IntStream; @@ -356,15 +358,28 @@ private static void assertMatch(Double first, Double second, String message) { assertMatch(first, second, DEFAULT_DELTA, message); } - public static void assertMatch(WaterSupplyPumpAccounting first, WaterSupplyPumpAccounting second) { + public static void assertMatch(List first, List second) { + + Iterator it1 = first.iterator(); + Iterator it2 = second.iterator(); + while (it1.hasNext() && it2.hasNext()) { + PumpAccounting pumpAccounting1 = it1.next(); + PumpAccounting pumpAccounting2 = it2.next(); + assertAll( + () -> assertMatch(pumpAccounting1.getPumpLocation(), pumpAccounting2.getPumpLocation()), + () -> assertMatch(pumpAccounting1.getTransferType(), pumpAccounting2.getTransferType()), + () -> assertEquals(pumpAccounting1.getFlow(), pumpAccounting2.getFlow()), + () -> assertEquals(pumpAccounting1.getTransferDate(), pumpAccounting2.getTransferDate()), + () -> assertEquals(pumpAccounting1.getComment(), pumpAccounting2.getComment()) + ); + } + } + + public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { assertAll( - () -> assertMatch(first.getWaterUser(), second.getWaterUser()), () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertMatch(first.getPumpLocation(), second.getPumpLocation()), - () -> assertMatch(first.getTransferType(), second.getTransferType()), - () -> assertEquals(first.getFlow(), second.getFlow()), - () -> assertEquals(first.getTransferDate(), second.getTransferDate()), - () -> assertEquals(first.getComment(), second.getComment()) + () -> assertMatch(first.getWaterUser(), second.getWaterUser()), + () -> assertMatch(first.getPumpAccounting(), second.getPumpAccounting()) ); } diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 94e796540..41d3ef61b 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -1,4 +1,5 @@ { + "contract-name": "Test Contract", "water-user": { "entity-name": "Test Entity", "project-id": { @@ -7,18 +8,36 @@ }, "water-right": "Test Water Right" }, - "contract-name": "Test Contract", - "pump-location": { - "office-id": "SPK", - "name": "Test Pump" - }, - "transfer-type": { - "office-id": "SPK", - "display-value": "Test Transfer Type", - "tooltip": "Test Tool Tip", - "active": true - }, - "flow": 1.0, - "transfer-date": 10000012648000, - "comment": "Test Comment" + "pump-accounting": [ + { + "pump-location": { + "office-id": "SPK", + "name": "Test Pump" + }, + "transfer-type": { + "office-id": "SPK", + "display-value": "Test Transfer Type", + "tooltip": "Test Tool Tip", + "active": true + }, + "flow": 1, + "transfer-date": 10000012648000, + "comment": "Test Comment" + }, + { + "pump-location": { + "office-id": "SPK", + "name": "Test Pump 2" + }, + "transfer-type": { + "office-id": "SPK", + "display-value": "Test Transfer Type 2", + "tooltip": "Test Tool Tip 2", + "active": true + }, + "flow": 2.0, + "transfer-date": 10000012648000, + "comment": "Test Comment 2" + } + ] } \ No newline at end of file From e55e9cdc624ce2bf045e3c3a0f803d3ea3bc4963 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Mon, 12 Aug 2024 11:43:48 -0700 Subject: [PATCH 29/39] Removed deprecated water pump controller --- .../WaterPumpDeleteController.java | 162 ------- .../api/WaterPumpDeleteControllerTestIT.java | 451 ------------------ 2 files changed, 613 deletions(-) delete mode 100644 cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java delete mode 100644 cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java deleted file mode 100644 index 9f0f8a83b..000000000 --- a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/WaterPumpDeleteController.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api.watersupply; - -import static cwms.cda.api.Controllers.*; -import static cwms.cda.data.dao.JooqDao.getDslContext; - -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; -import cwms.cda.api.Controllers; -import cwms.cda.api.errors.CdaError; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import io.javalin.http.Context; -import io.javalin.http.Handler; -import io.javalin.plugin.openapi.annotations.HttpMethod; -import io.javalin.plugin.openapi.annotations.OpenApi; -import io.javalin.plugin.openapi.annotations.OpenApiParam; -import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.http.HttpServletResponse; -import org.jetbrains.annotations.NotNull; -import org.jooq.DSLContext; - - -public class WaterPumpDeleteController implements Handler { - private static final Logger LOGGER = Logger.getLogger(WaterPumpDeleteController.class.getName()); - public static final String TAG = "Water Contracts"; - private static final String CONTRACT_ID = "contract-id"; - private static final String PUMP_TYPE = "pump-type"; - private final MetricRegistry metrics; - - private Timer.Context markAndTime(String subject) { - return Controllers.markAndTime(metrics, getClass().getName(), subject); - } - - public WaterPumpDeleteController(MetricRegistry metrics) { - this.metrics = metrics; - } - - @NotNull - protected WaterContractDao getContractDao(DSLContext dsl) { - return new WaterContractDao(dsl); - } - - @OpenApi( - queryParams = { - @OpenApiParam(name = PUMP_TYPE, required = true, - description = "The type of pump to be removed from the contract." - + " Expected values: IN, OUT, OUT BELOW"), - @OpenApiParam(name = DELETE, type = boolean.class, required = true, - description = "Whether to delete the associated accounting data.") - }, - pathParams = { - @OpenApiParam(name = NAME, description = "The name of the pump to be " - + "removed from the specified contract.", required = true), - @OpenApiParam(name = OFFICE, description = "The office the project is associated with.", required = true), - @OpenApiParam(name = PROJECT_ID, description = "The name of the project.", required = true), - @OpenApiParam(name = CONTRACT_ID, description = "The name of the contract the pump is associated with.", - required = true), - @OpenApiParam(name = WATER_USER, description = "The name of the water user the contract " - + "is associated with.", required = true) - }, - responses = { - @OpenApiResponse(status = "404", description = "The provided combination of parameters" - + " did not find any contracts."), - @OpenApiResponse(status = "501", description = "Requested format is not implemented.") - }, - description = "Delete a pump from a contract", - path = "/projects/{office}/{project-id}/water-user/{water-user}/contracts/{contract-id}/pumps/{name}", - method = HttpMethod.DELETE, - tags = {TAG} - ) - - @Override - public void handle(@NotNull Context ctx) { - try (Timer.Context ignored = markAndTime(DELETE)) { - DSLContext dsl = getDslContext(ctx); - boolean deleteAccounting = Boolean.parseBoolean(ctx.queryParam(DELETE)); - String officeId = ctx.pathParam(OFFICE); - String projectName = ctx.pathParam(PROJECT_ID); - String entityName = ctx.pathParam(WATER_USER); - String pumpType = ctx.queryParam(PUMP_TYPE); - String contractName = ctx.pathParam(CONTRACT_ID); - assert pumpType != null; - WaterContractDao contractDao = getContractDao(dsl); - CwmsId projectLocation = new CwmsId.Builder().withName(projectName).withOfficeId(officeId).build(); - List contract = contractDao.getAllWaterContracts(projectLocation, entityName); - - if (contract.isEmpty()) { - CdaError error = new CdaError("No contract found for the provided name."); - LOGGER.log(Level.SEVERE, "No matching contract found."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - for (WaterUserContract waterUserContract : contract) { - if (waterUserContract.getContractId().getName().equals(contractName)) { - switch (pumpType) { - case "IN": - contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpInLocation().getPumpLocation().getName(), - pumpType, deleteAccounting); - ctx.status(HttpServletResponse.SC_NO_CONTENT); - return; - case "OUT": - contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutLocation().getPumpLocation().getName(), - pumpType, deleteAccounting); - ctx.status(HttpServletResponse.SC_NO_CONTENT); - return; - case "BELOW": - contractDao.removePumpFromContract(waterUserContract, - waterUserContract.getPumpOutBelowLocation().getPumpLocation().getName(), - pumpType, deleteAccounting); - ctx.status(HttpServletResponse.SC_NO_CONTENT); - return; - default: - CdaError error = new CdaError("Invalid pump type provided."); - LOGGER.log(Level.SEVERE, "Invalid pump type provided."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - return; - } - - } - } - CdaError error = new CdaError("No contract found for the provided name."); - LOGGER.log(Level.SEVERE, "No matching contract found."); - ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); - } - } - - - -} diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java deleted file mode 100644 index ccb733e0b..000000000 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterPumpDeleteControllerTestIT.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * - * MIT License - * - * Copyright (c) 2024 Hydrologic Engineering Center - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE - * SOFTWARE. - */ - -package cwms.cda.api; - -import cwms.cda.api.enums.Nation; -import cwms.cda.api.watersupply.WaterContractController; -import cwms.cda.data.dao.DeleteRule; -import cwms.cda.data.dao.JooqDao.DeleteMethod; -import cwms.cda.data.dao.LocationsDaoImpl; -import cwms.cda.data.dao.project.ProjectDao; -import cwms.cda.data.dao.watersupply.WaterContractDao; -import cwms.cda.data.dto.Location; -import cwms.cda.data.dto.project.Project; -import cwms.cda.data.dto.watersupply.PumpType; -import cwms.cda.data.dto.watersupply.WaterUser; -import cwms.cda.data.dto.watersupply.WaterUserContract; -import cwms.cda.formatters.ContentType; -import cwms.cda.formatters.Formats; -import cwms.cda.formatters.json.JsonV1; -import fixtures.CwmsDataApiSetupCallback; -import fixtures.TestAccounts; -import io.restassured.filter.log.LogDetail; -import mil.army.usace.hec.test.database.CwmsDatabaseContainer; -import org.apache.commons.io.IOUtils; -import org.jooq.DSLContext; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -import java.time.ZoneId; -import java.util.Collections; - -import static cwms.cda.api.Controllers.DELETE; -import static cwms.cda.api.Controllers.DELETE_MODE; -import static cwms.cda.data.dao.DaoTest.getDslContext; -import static cwms.cda.security.KeyAccessManager.AUTH_HEADER; -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - - -@Tag("integration") -class WaterPumpDeleteControllerTestIT extends DataApiTestIT { - private static final String USAGE_ID = "usage-id"; - private static final String OFFICE_ID = "SWT"; - private static final WaterUserContract CONTRACT; - private static final WaterUserContract CONTRACT_NO_PUMP; - static { - try ( - InputStream contractStream = WaterContractController.class - .getResourceAsStream("/cwms/cda/api/waterusercontract.json"); - InputStream contractStreamNoPump = WaterContractController.class - .getResourceAsStream("/cwms/cda/api/waterusercontract_no_pump.json") - ) { - assert contractStream != null; - assert contractStreamNoPump != null; - String contractJson = IOUtils.toString(contractStream, StandardCharsets.UTF_8); - String contractJsonNoPump = IOUtils.toString(contractStreamNoPump, StandardCharsets.UTF_8); - CONTRACT = Formats.parseContent(new ContentType(Formats.JSONV1), contractJson, WaterUserContract.class); - CONTRACT_NO_PUMP = Formats.parseContent(new ContentType(Formats.JSONV1), contractJsonNoPump, - WaterUserContract.class); - } catch(Exception ex) { - throw new RuntimeException(ex); - } - } - - @BeforeAll - static void setUp() throws Exception { - Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), - CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) - .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).withVerticalDatum("WGS84") - .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) - .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) - .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectId().getOfficeId(), - CONTRACT.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") - .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") - .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") - .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) - .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) - .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectId().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") - .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") - .withLongitude(38.0).withLatitude(56.5).withVerticalDatum("WGS84") - .withLongName("TEST CONTRACT LOCATION").withActive(true).withMapLabel("LABEL").withNation(Nation.US) - .withElevation(456.7).withElevationUnits("m").withPublishedLongitude(78.9).withPublishedLatitude(45.3) - .withLocationType("PROJECT").withDescription("TEST PROJECT").build(); - Project project = new Project.Builder().withLocation(parentLocation).withFederalCost(BigDecimal.valueOf(123456789)) - .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT.getWaterUser().getEntityName()) - .build(); - Project project1 = new Project.Builder().withLocation(parentLocation2).withFederalCost(BigDecimal.valueOf(123456789)) - .withAuthorizingLaw("NEW LAW").withCostUnit("$").withProjectOwner(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) - .build(); - WaterUser waterUser = new WaterUser.Builder().withEntityName(CONTRACT.getWaterUser().getEntityName()) - .withProjectId(CONTRACT.getWaterUser().getProjectId()) - .withWaterRight(CONTRACT.getWaterUser().getWaterRight()).build(); - WaterUser waterUserNoPump = new WaterUser.Builder().withEntityName(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) - .withProjectId(CONTRACT_NO_PUMP.getWaterUser().getProjectId()) - .withWaterRight(CONTRACT_NO_PUMP.getWaterUser().getWaterRight()).build(); - - CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); - databaseLink.connection(c -> { - DSLContext ctx = getDslContext(c, OFFICE_ID); - LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); - ProjectDao projectDao = new ProjectDao(ctx); - WaterContractDao waterContractDao = new WaterContractDao(ctx); - try { - locationsDao.storeLocation(contractLocation); - locationsDao.storeLocation(parentLocation); - locationsDao.storeLocation(parentLocation2); - projectDao.store(project, true); - projectDao.store(project1, true); - waterContractDao.storeWaterUser(waterUser, true); - waterContractDao.storeWaterContractTypes(Collections.singletonList(CONTRACT.getContractType()), false); - waterContractDao.storeWaterUser(waterUserNoPump, true); - } catch (IOException e) { - throw new RuntimeException(e); - } - }, CwmsDataApiSetupCallback.getWebUser()); - } - - @AfterAll - static void tearDown() throws Exception { - Location contractLocation = new Location.Builder(CONTRACT.getContractId().getOfficeId(), - CONTRACT.getContractId().getName()).withLocationKind("PROJECT").withTimeZoneName(ZoneId.of("UTC")) - .withHorizontalDatum("WGS84").withLongitude(78.0).withLatitude(67.9).build(); - Location parentLocation = new Location.Builder(CONTRACT.getWaterUser().getProjectId().getOfficeId(), - CONTRACT.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") - .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") - .withLongitude(38.0).withLatitude(56.5).build(); - Location parentLocation2 = new Location.Builder(CONTRACT_NO_PUMP.getWaterUser().getProjectId().getOfficeId(), - CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName()).withLocationKind("PROJECT") - .withTimeZoneName(ZoneId.of("UTC")).withHorizontalDatum("WGS84") - .withLongitude(38.0).withLatitude(56.5).build(); - WaterUser waterUser = new WaterUser.Builder().withEntityName(CONTRACT.getWaterUser().getEntityName()) - .withProjectId(CONTRACT.getWaterUser().getProjectId()) - .withWaterRight(CONTRACT.getWaterUser().getWaterRight()).build(); - WaterUser waterUserNoPump = new WaterUser.Builder().withEntityName(CONTRACT_NO_PUMP.getWaterUser().getEntityName()) - .withProjectId(CONTRACT_NO_PUMP.getWaterUser().getProjectId()) - .withWaterRight(CONTRACT_NO_PUMP.getWaterUser().getWaterRight()).build(); - - CwmsDatabaseContainer databaseLink = CwmsDataApiSetupCallback.getDatabaseLink(); - databaseLink.connection(c -> { - DSLContext ctx = getDslContext(c, OFFICE_ID); - LocationsDaoImpl locationsDao = new LocationsDaoImpl(ctx); - WaterContractDao waterContractDao = new WaterContractDao(ctx); - ProjectDao projectDao = new ProjectDao(ctx); - waterContractDao.deleteWaterUser(waterUser.getProjectId(), waterUser.getEntityName(), - DeleteRule.DELETE_ALL.toString()); - waterContractDao.deleteWaterUser(waterUserNoPump.getProjectId(), waterUserNoPump.getEntityName(), - DeleteRule.DELETE_ALL.toString()); - projectDao.delete(CONTRACT.getOfficeId(), CONTRACT.getWaterUser().getProjectId().getName(), - DeleteRule.DELETE_ALL); - projectDao.delete(CONTRACT_NO_PUMP.getOfficeId(), CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName(), - DeleteRule.DELETE_ALL); - locationsDao.deleteLocation(contractLocation.getName(), contractLocation.getOfficeId(), true); - locationsDao.deleteLocation(parentLocation.getName(), parentLocation.getOfficeId(), true); - locationsDao.deleteLocation(parentLocation2.getName(), parentLocation2.getOfficeId(), true); - }, CwmsDataApiSetupCallback.getWebUser()); - } - - @Test - void test_remove_from_contract() throws Exception { - final String PUMP_TYPE = "pump-type"; - // Structure of test: - // 1) Create contract with pump - // 2) Remove the pump from the contract - // 3) Retrieve the contract and assert it does not contain the pump - // 4) Delete the contract - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SWT_NORMAL; - String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT); - - // Create contract with pump - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .accept(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .body(json) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_CREATED)) - ; - - // Remove pump and assert it is removed - given() - .queryParam(DELETE, false) - .queryParam(PUMP_TYPE, PumpType.IN.getName()) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName() + "/pumps/" - + CONTRACT.getPumpInLocation().getPumpLocation().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) - ; - - // Retrieve contract and assert pump is removed - given() - .log().ifValidationFails(LogDetail.ALL, true) - .accept(Formats.JSONV1) - .when() - .redirects().follow(true) - .redirects().max(3) - .get("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_OK)) - .body("[0].office-id", equalTo(CONTRACT.getOfficeId())) - .body("[0].water-user.entity-name", equalTo(CONTRACT.getWaterUser().getEntityName())) - .body("[0].water-user.project-id.office-id", equalTo(CONTRACT.getWaterUser() - .getProjectId().getOfficeId())) - .body("[0].water-user.project-id.name", equalTo(CONTRACT.getWaterUser().getProjectId() - .getName())) - .body("[0].water-user.water-right", equalTo(CONTRACT.getWaterUser().getWaterRight())) - .body("[0].contract-type.office-id", equalTo(CONTRACT.getContractType().getOfficeId())) - .body("[0].contract-type.display-value", equalTo(CONTRACT.getContractType().getDisplayValue())) - .body("[0].contract-type.tooltip", equalTo(CONTRACT.getContractType().getTooltip())) - .body("[0].contract-type.active", equalTo(CONTRACT.getContractType().getActive())) - .body("[0].contract-effective-date", hasToString(String.valueOf(CONTRACT.getContractEffectiveDate().getTime()))) - .body("[0].contract-expiration-date", hasToString(String.valueOf(CONTRACT.getContractExpirationDate().getTime()))) - .body("[0].contracted-storage", hasToString(String.valueOf(CONTRACT.getContractedStorage()))) - .body("[0].initial-use-allocation", hasToString(String.valueOf(CONTRACT.getInitialUseAllocation()))) - .body("[0].future-use-allocation", hasToString(String.valueOf(CONTRACT.getFutureUseAllocation()))) - .body("[0].storage-units-id", hasToString(String.valueOf(CONTRACT.getStorageUnitsId()))) - .body("[0].future-use-percent-activated", hasToString(String.valueOf(CONTRACT.getFutureUsePercentActivated()))) - .body("[0].total-alloc-percent-activated", hasToString(String.valueOf(CONTRACT.getTotalAllocPercentActivated()))) - .body("[0].pump-out-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getOfficeId())) - .body("[0].pump-out-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutLocation().getPumpLocation() - .getName()))) - .body("[0].pump-out-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLatitude()))) - .body("[0].pump-out-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLongitude()))) - .body("[0].pump-out-location.pump-location.active", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getActive())) - .body("[0].pump-out-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublicName())) - .body("[0].pump-out-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLongName())) - .body("[0].pump-out-location.pump-location.description", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getDescription())) - .body("[0].pump-out-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getTimezoneName())) - .body("[0].pump-out-location.pump-location.location-type", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLocationType()))) - .body("[0].pump-out-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getLocationKind())) - .body("[0].pump-out-location.pump-location.nation", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getNation().toString())) - .body("[0].pump-out-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getStateInitial())) - .body("[0].pump-out-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getCountyName())) - .body("[0].pump-out-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getNearestCity())) - .body("[0].pump-out-location.pump-location.horizontal-datum", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getHorizontalDatum())) - .body("[0].pump-out-location.pump-location.published-latitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLatitude()))) - .body("[0].pump-out-location.pump-location.published-longitude", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getPublishedLongitude()))) - .body("[0].pump-out-location.pump-location.vertical-datum", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getVerticalDatum())) - .body("[0].pump-out-location.pump-location.elevation", hasToString(String.valueOf(CONTRACT.getPumpOutLocation() - .getPumpLocation().getElevation()))) - .body("[0].pump-out-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getMapLabel())) - .body("[0].pump-out-location.pump-location.bounding-office-id", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getBoundingOfficeId())) - .body("[0].pump-out-location.pump-location.elevation-units", equalTo(CONTRACT.getPumpOutLocation() - .getPumpLocation().getElevationUnits())) - .body("[0].pump-out-below-location.pump-location.office-id", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getOfficeId())) - .body("[0].pump-out-below-location.pump-location.name", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getName()))) - .body("[0].pump-out-below-location.pump-location.latitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLatitude()))) - .body("[0].pump-out-below-location.pump-location.longitude", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLongitude()))) - .body("[0].pump-out-below-location.pump-location.active", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getActive())) - .body("[0].pump-out-below-location.pump-location.public-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getPublicName())) - .body("[0].pump-out-below-location.pump-location.long-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLongName())) - .body("[0].pump-out-below-location.pump-location.description", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getDescription())) - .body("[0].pump-out-below-location.pump-location.timezone-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getTimezoneName())) - .body("[0].pump-out-below-location.pump-location.location-type", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLocationType()))) - .body("[0].pump-out-below-location.pump-location.location-kind", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getLocationKind())) - .body("[0].pump-out-below-location.pump-location.nation", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getNation().toString())) - .body("[0].pump-out-below-location.pump-location.state-initial", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getStateInitial())) - .body("[0].pump-out-below-location.pump-location.county-name", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getCountyName())) - .body("[0].pump-out-below-location.pump-location.nearest-city", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getNearestCity())) - .body("[0].pump-out-below-location.pump-location.horizontal-datum", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getHorizontalDatum())) - .body("[0].pump-out-below-location.pump-location.published-latitude", hasToString(String.valueOf(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLatitude()))) - .body("[0].pump-out-below-location.pump-location.published-longitude", hasToString(String.valueOf(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getPublishedLongitude()))) - .body("[0].pump-out-below-location.pump-location.vertical-datum", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getVerticalDatum())) - .body("[0].pump-out-below-location.pump-location.elevation", hasToString(String.valueOf(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getElevation()))) - .body("[0].pump-out-below-location.pump-location.map-label", equalTo(CONTRACT.getPumpOutBelowLocation() - .getPumpLocation().getMapLabel())) - .body("[0].pump-out-below-location.pump-location.bounding-office-id", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getBoundingOfficeId())) - .body("[0].pump-out-below-location.pump-location.elevation-units", equalTo(CONTRACT - .getPumpOutBelowLocation().getPumpLocation().getElevationUnits())) - .body("[0].pump-in-location", equalTo(null)) - ; - - // Delete contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(DELETE_MODE, "DELETE ALL") - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT.getWaterUser().getEntityName() + "/contracts/" + CONTRACT.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) - ; - } - - @Test - void test_remove_does_not_exist() throws Exception { - // Structure of test: - // 1) Create contract with no pump - // 2) Try to remove the pump from contract and assert that an error is thrown - // 3) Delete the contract - - TestAccounts.KeyUser user = TestAccounts.KeyUser.SWT_NORMAL; - String json = JsonV1.buildObjectMapper().writeValueAsString(CONTRACT_NO_PUMP); - - // Create contract with no pump - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .accept(Formats.JSONV1) - .body(json) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .post("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts") - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_CREATED)) - ; - - // Remove pump - given() - .log().ifValidationFails(LogDetail.ALL, true) - .queryParam(USAGE_ID, "PUMP1") - .queryParam(DELETE, DeleteMethod.DELETE_ALL.toString()) - .header(AUTH_HEADER, user.toHeaderValue()) - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getContractId().getName() + "/water-user/" - + CONTRACT_NO_PUMP.getWaterUser().getEntityName() + "/contracts/" - + CONTRACT_NO_PUMP.getContractId().getName()+ "/pumps/" - + null) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)) - ; - - // Delete contract - given() - .log().ifValidationFails(LogDetail.ALL, true) - .contentType(Formats.JSONV1) - .header(AUTH_HEADER, user.toHeaderValue()) - .queryParam(DELETE_MODE, "DELETE ALL") - .when() - .redirects().follow(true) - .redirects().max(3) - .delete("/projects/" + OFFICE_ID + "/" + CONTRACT_NO_PUMP.getWaterUser().getProjectId().getName() - + "/water-user/" + CONTRACT_NO_PUMP.getWaterUser().getEntityName() - + "/contracts/" + CONTRACT_NO_PUMP.getContractId().getName()) - .then() - .log().ifValidationFails(LogDetail.ALL, true) - .assertThat() - .statusCode(is(HttpServletResponse.SC_NO_CONTENT)) - ; - } -} From 3208e5ae90203b94c0ceb86e3885af335c3897a0 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Mon, 12 Aug 2024 13:59:02 -0700 Subject: [PATCH 30/39] Updated Accounting DTO and tests --- .../watersupply/WaterSupplyAccounting.java | 3 + .../WaterSupplyAccountingTest.java | 134 ++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 9b43e8446..554f1a531 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -27,6 +27,7 @@ package cwms.cda.data.dto.watersupply; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonNaming; @@ -43,7 +44,9 @@ @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) public final class WaterSupplyAccounting extends CwmsDTOBase { + @JsonProperty(required = true) private final String contractName; + @JsonProperty(required = true) private final WaterUser waterUser; private final List pumpAccounting; diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java new file mode 100644 index 000000000..716c20d9f --- /dev/null +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -0,0 +1,134 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import static org.junit.jupiter.api.Assertions.*; + +import cwms.cda.api.errors.FieldException; +import cwms.cda.data.dto.CwmsId; +import cwms.cda.data.dto.LookupType; +import cwms.cda.formatters.Formats; +import cwms.cda.helpers.DTOMatch; +import org.junit.jupiter.api.Test; +import org.testcontainers.shaded.org.apache.commons.io.IOUtils; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + + +class WaterSupplyAccountingTest { + private static final String OFFICE = "SPK"; + + @Test + void testWaterSupplyAccountingSerializationRoundTrip() { + WaterUser user = new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder() + .withOfficeId(OFFICE) + .withName("Test Location") + .build()) + .withWaterRight("Test Water Right").build(); + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(user).withContractName("Test Contract").withPumpAccounting(buildPumpAccounting()).build(); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), + waterSupplyAccounting); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + } + + @Test + void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception { + WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build()) + .withContractName("Test Contract") + .withPumpAccounting(buildPumpAccounting()).build(); + InputStream resource = this.getClass().getResourceAsStream( + "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); + DTOMatch.assertMatch(WaterSupplyAccounting, deserialized); + } + + + @Test + void testValidate() { + assertAll( + () -> { + WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build()).withContractName("Test Contract") + .build(); + assertDoesNotThrow(WaterSupplyAccounting::validate, "Expected validation to pass"); + }, + () -> { + WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(new WaterUser.Builder() + .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Test Location").build()) + .withWaterRight("Test Water Right").build()) + .withContractName(null) + .build(); + assertThrows(FieldException.class, WaterSupplyAccounting::validate, "Expected validation to " + + "fail due to null contract name"); + }, + () -> { + WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withContractName("Test Contract") + .build(); + assertThrows(FieldException.class, WaterSupplyAccounting::validate, "Expected validation to " + + "fail due to null water user"); + } + ); + } + + + private static List buildPumpAccounting() { + List pumpList = new ArrayList<>(); + PumpAccounting pumpAccounting = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) + .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build(); + pumpList.add(pumpAccounting); + PumpAccounting pumpAccounting2 = new PumpAccounting.Builder() + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump 2").build()) + .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip 2").withOfficeId(OFFICE) + .withDisplayValue("Test Transfer Type 2").build()).withFlow(2.0) + .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build(); + pumpList.add(pumpAccounting2); + return pumpList; + } +} From f612350f709dbb07634e81ba300b385779f64d58 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Wed, 14 Aug 2024 08:59:15 -0700 Subject: [PATCH 31/39] Added base location to pump names --- .../WaterSupplyAccountingTest.java | 20 +++++++++---------- .../watersupply/water_supply_accounting.json | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index 716c20d9f..a020a46b8 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -64,7 +64,7 @@ void testWaterSupplyAccountingSerializationRoundTrip() { @Test void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception { - WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withWaterUser(new WaterUser.Builder() .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) @@ -77,7 +77,7 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); - DTOMatch.assertMatch(WaterSupplyAccounting, deserialized); + DTOMatch.assertMatch(waterSupplyAccounting, deserialized); } @@ -85,30 +85,30 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception void testValidate() { assertAll( () -> { - WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) .withWaterRight("Test Water Right").build()).withContractName("Test Contract") .build(); - assertDoesNotThrow(WaterSupplyAccounting::validate, "Expected validation to pass"); + assertDoesNotThrow(waterSupplyAccounting::validate, "Expected validation to pass"); }, () -> { - WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withWaterUser(new WaterUser.Builder() .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()) .withWaterRight("Test Water Right").build()) .withContractName(null) .build(); - assertThrows(FieldException.class, WaterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + "fail due to null contract name"); }, () -> { - WaterSupplyAccounting WaterSupplyAccounting = new WaterSupplyAccounting.Builder() + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withContractName("Test Contract") .build(); - assertThrows(FieldException.class, WaterSupplyAccounting::validate, "Expected validation to " + assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + "fail due to null water user"); } ); @@ -118,13 +118,13 @@ void testValidate() { private static List buildPumpAccounting() { List pumpList = new ArrayList<>(); PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump").build()) .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build(); pumpList.add(pumpAccounting); PumpAccounting pumpAccounting2 = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump 2").build()) + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump 2").build()) .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip 2").withOfficeId(OFFICE) .withDisplayValue("Test Transfer Type 2").build()).withFlow(2.0) .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build(); diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 41d3ef61b..068050f82 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -12,7 +12,7 @@ { "pump-location": { "office-id": "SPK", - "name": "Test Pump" + "name": "Test Location-Test Pump" }, "transfer-type": { "office-id": "SPK", @@ -27,7 +27,7 @@ { "pump-location": { "office-id": "SPK", - "name": "Test Pump 2" + "name": "Test Location-Test Pump 2" }, "transfer-type": { "office-id": "SPK", From 950e7916335af832683be5c6a3e6a76cc0619178 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Wed, 14 Aug 2024 09:44:57 -0700 Subject: [PATCH 32/39] Added sublocations to tests --- .../cwms/cda/data/dto/watersupply/PumpAccountingTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java index e4ac9763b..efa8f1c50 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java @@ -130,11 +130,11 @@ private WaterSupplyAccounting buildTestAccounting() { private List buildTestPumpAccountingList() { List retList = new ArrayList<>(); retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Pump").build()).withTransferType(new LookupType.Builder().withActive(true) + .withName("Test Location-Test Pump").build()).withTransferType(new LookupType.Builder().withActive(true) .withTooltip("Test Tool Tip").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Pump 2").build()).withTransferType(new LookupType.Builder().withActive(true) + .withName("Test Location-Test Pump 2").build()).withTransferType(new LookupType.Builder().withActive(true) .withTooltip("Test Tool Tip 2").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type 2").build()) .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build()); return retList; From 40a3c41d0ebab2cb25c6df7435e92b10946354b8 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Mon, 26 Aug 2024 09:36:07 -0700 Subject: [PATCH 33/39] Rewrote Water Pump Accounting DTO for more concise JSON files --- .../data/dto/watersupply/PumpAccounting.java | 54 ++-------- .../data/dto/watersupply/PumpTransfer.java | 98 +++++++++++++++++++ .../watersupply/WaterSupplyAccounting.java | 44 +++++++-- .../dto/watersupply/PumpAccountingTest.java | 92 +++++++++-------- .../WaterSupplyAccountingTest.java | 48 +++++---- .../test/java/cwms/cda/helpers/DTOMatch.java | 58 ++++++++--- .../watersupply/water_supply_accounting.json | 96 +++++++++++++----- 7 files changed, 338 insertions(+), 152 deletions(-) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java index 4af9b4088..51c61efab 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java @@ -30,8 +30,8 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import cwms.cda.data.dto.CwmsDTOBase; import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.LookupType; import java.time.Instant; +import java.util.Map; @JsonDeserialize(builder = PumpAccounting.Builder.class) @@ -39,70 +39,32 @@ public final class PumpAccounting extends CwmsDTOBase { @JsonProperty(required = true) private final CwmsId pumpLocation; @JsonProperty(required = true) - private final LookupType transferType; - @JsonProperty(required = true) - private final Double flow; - @JsonProperty(required = true) - private final Instant transferDate; - private final String comment; + private final Map pumpTransfers; private PumpAccounting(Builder builder) { this.pumpLocation = builder.pumpLocation; - this.transferType = builder.transferType; - this.flow = builder.flow; - this.transferDate = builder.transferDate; - this.comment = builder.comment; + this.pumpTransfers = builder.pumpTransfers; } public CwmsId getPumpLocation() { return this.pumpLocation; } - public LookupType getTransferType() { - return this.transferType; - } - - public Double getFlow() { - return this.flow; - } - - public Instant getTransferDate() { - return this.transferDate; - } - - public String getComment() { - return this.comment; + public Map getPumpTransfers() { + return this.pumpTransfers; } public static final class Builder { private CwmsId pumpLocation; - private LookupType transferType; - private Double flow; - private Instant transferDate; - private String comment; + private Map pumpTransfers; public Builder withPumpLocation(CwmsId pumpLocation) { this.pumpLocation = pumpLocation; return this; } - public Builder withTransferType(LookupType transferType) { - this.transferType = transferType; - return this; - } - - public Builder withFlow(Double flow) { - this.flow = flow; - return this; - } - - public Builder withTransferDate(Instant transferDate) { - this.transferDate = transferDate; - return this; - } - - public Builder withComment(String comment) { - this.comment = comment; + public Builder withPumpTransfers(Map pumpTransfers) { + this.pumpTransfers = pumpTransfers; return this; } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java new file mode 100644 index 000000000..4c08fcefd --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java @@ -0,0 +1,98 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.data.dto.CwmsDTOBase; + +import java.time.Instant; + +@JsonDeserialize(builder = PumpTransfer.Builder.class) +public class PumpTransfer extends CwmsDTOBase { + @JsonProperty(required = true) + private final String transferTypeDisplay; + @JsonProperty(required = true) + private final Double flow; + @JsonProperty(required = true) + private final Instant transferDate; + private final String comment; + + private PumpTransfer(Builder builder) { + this.transferTypeDisplay = builder.transferTypeDisplay; + this.flow = builder.flow; + this.transferDate = builder.transferDate; + this.comment = builder.comment; + } + + public String getTransferTypeDisplay() { + return this.transferTypeDisplay; + } + + public Double getFlow() { + return this.flow; + } + + public Instant getTransferDate() { + return this.transferDate; + } + + public String getComment() { + return this.comment; + } + + public static final class Builder { + private String transferTypeDisplay; + private Double flow; + private Instant transferDate; + private String comment; + + public Builder withTransferTypeDisplay(String transferTypeDisplay) { + this.transferTypeDisplay = transferTypeDisplay; + return this; + } + + public Builder withFlow(Double flow) { + this.flow = flow; + return this; + } + + public Builder withTransferDate(Instant transferDate) { + this.transferDate = transferDate; + return this; + } + + public Builder withComment(String comment) { + this.comment = comment; + return this; + } + + public PumpTransfer build() { + return new PumpTransfer(this); + } + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 554f1a531..615fdefc4 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -35,7 +35,7 @@ import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; -import java.util.List; +import java.util.Map; @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, aliases = {Formats.DEFAULT, Formats.JSON}) @@ -48,12 +48,16 @@ public final class WaterSupplyAccounting extends CwmsDTOBase { private final String contractName; @JsonProperty(required = true) private final WaterUser waterUser; - private final List pumpAccounting; + private final Map pumpInAccounting; + private final Map pumpOutAccounting; + private final Map pumpBelowAccounting; private WaterSupplyAccounting(Builder builder) { this.contractName = builder.contractName; this.waterUser = builder.waterUser; - this.pumpAccounting = builder.pumpAccounting; + this.pumpBelowAccounting = builder.pumpBelowAccounting; + this.pumpInAccounting = builder.pumpInAccounting; + this.pumpOutAccounting = builder.pumpOutAccounting; } public String getContractName() { @@ -64,14 +68,24 @@ public WaterUser getWaterUser() { return this.waterUser; } - public List getPumpAccounting() { - return this.pumpAccounting; + public Map getPumpInAccounting() { + return this.pumpInAccounting; + } + + public Map getPumpOutAccounting() { + return this.pumpOutAccounting; + } + + public Map getPumpBelowAccounting() { + return this.pumpBelowAccounting; } public static final class Builder { private String contractName; private WaterUser waterUser; - private List pumpAccounting; + private Map pumpInAccounting; + private Map pumpOutAccounting; + private Map pumpBelowAccounting; public Builder withContractName(String contractName) { this.contractName = contractName; @@ -83,9 +97,21 @@ public Builder withWaterUser(WaterUser waterUser) { return this; } - public Builder withPumpAccounting( - List pumpAccounting) { - this.pumpAccounting = pumpAccounting; + public Builder withPumpInAccounting( + Map pumpInAccounting) { + this.pumpInAccounting = pumpInAccounting; + return this; + } + + public Builder withPumpOutAccounting( + Map pumpOutAccounting) { + this.pumpOutAccounting = pumpOutAccounting; + return this; + } + + public Builder withPumpBelowAccounting( + Map pumpBelowAccounting) { + this.pumpBelowAccounting = pumpBelowAccounting; return this; } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java index efa8f1c50..e5d8e2510 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java @@ -30,7 +30,6 @@ import cwms.cda.api.errors.FieldException; import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.LookupType; import cwms.cda.formatters.Formats; import cwms.cda.helpers.DTOMatch; import org.junit.jupiter.api.Test; @@ -38,8 +37,8 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; -import java.util.ArrayList; -import java.util.List; +import java.util.Map; +import java.util.TreeMap; class PumpAccountingTest { @@ -71,50 +70,50 @@ void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Except void testValidate() { assertAll( () -> { + Map pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochSecond(10000012648112L), new PumpTransfer.Builder() + .withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) + .withComment("Test Comment").build()); PumpAccounting pumpAccounting = new PumpAccounting.Builder() .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) - .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); + .withPumpTransfers(pumpMap).build(); assertDoesNotThrow(pumpAccounting::validate, "Expected validation to pass"); }, () -> { + Map pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochSecond(10000012648112L), new PumpTransfer.Builder() + .withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) + .withComment("Test Comment").build()); PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(null).withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()) - .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withComment("Test Comment").build(); + .withPumpLocation(null).withPumpTransfers(pumpMap).build(); assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + "fail due to null location"); }, () -> { - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Pump").build()).withTransferType(null) - .withFlow(1.0).withTransferDate(Instant.ofEpochSecond(10000012648112L)) + PumpTransfer pumpTransfer = new PumpTransfer.Builder() + .withTransferDate(null) + .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) .withComment("Test Comment").build(); - assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " - + "fail due to null transfer type"); + assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " + + "fail due to null transfer date"); }, () -> { - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip"). - withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()).withFlow(null) - .withTransferDate(Instant.ofEpochSecond(10000012648112L)).withComment("Test Comment").build(); - assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + PumpTransfer pumpTransfer = new PumpTransfer.Builder() + .withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withTransferTypeDisplay("Test Transfer Type").withFlow(null) + .withComment("Test Comment").build(); + assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " + "fail due to null flow value"); }, () -> { - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip") - .withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) - .withFlow(1.0).withTransferDate(null).withComment("Test Comment").build(); - assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " - + "fail due to null transfer date"); + PumpTransfer pumpTransfer = new PumpTransfer.Builder() + .withTransferDate(Instant.ofEpochSecond(10000012648112L)) + .withTransferTypeDisplay(null).withFlow(1.0) + .withComment(null).build(); + assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " + + "fail due to null transfer type display value"); } ); } @@ -123,20 +122,29 @@ private WaterSupplyAccounting buildTestAccounting() { return new WaterSupplyAccounting.Builder().withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") .withWaterRight("Test Water Right").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) .withName("Test Location").build()).build()) - .withContractName("Test Contract").withPumpAccounting(buildTestPumpAccountingList()) + .withContractName("Test Contract").withPumpInAccounting(buildTestPumpInAccountingList()) + .withPumpBelowAccounting(buildTestPumpInAccountingList()) .build(); } - private List buildTestPumpAccountingList() { - List retList = new ArrayList<>(); - retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location-Test Pump").build()).withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test Tool Tip").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type").build()) + private Map buildTestPumpInAccountingList() { + Map retMap = new TreeMap<>(); + Map pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochMilli(10000012648000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); - retList.add(new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location-Test Pump 2").build()).withTransferType(new LookupType.Builder().withActive(true) - .withTooltip("Test Tool Tip 2").withOfficeId(OFFICE).withDisplayValue("Test Transfer Type 2").build()) - .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build()); - return retList; + pumpMap.put(Instant.ofEpochMilli(10000012649000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") + .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012649000L)).withComment("Test Comment 2").build()); + PumpAccounting pumpAccounting = new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Location-Test Pump").build()).withPumpTransfers(pumpMap).build(); + retMap.put("Test Pump", pumpAccounting); + pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochMilli(10000012699000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") + .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012699000L)).withComment("Test Comment").build()); + pumpMap.put(Instant.ofEpochMilli(10000012710000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") + .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012710000L)).withComment("Test Comment 2").build()); + pumpAccounting = new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder() + .withOfficeId(OFFICE).withName("Test Location-Test Pump2").build()).withPumpTransfers(pumpMap).build(); + retMap.put("Test Pump2", pumpAccounting); + return retMap; } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index a020a46b8..1a5a7730e 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -30,7 +30,6 @@ import cwms.cda.api.errors.FieldException; import cwms.cda.data.dto.CwmsId; -import cwms.cda.data.dto.LookupType; import cwms.cda.formatters.Formats; import cwms.cda.helpers.DTOMatch; import org.junit.jupiter.api.Test; @@ -38,8 +37,10 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; -import java.util.ArrayList; -import java.util.List; +import java.util.HashMap; +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; class WaterSupplyAccountingTest { @@ -54,7 +55,7 @@ void testWaterSupplyAccountingSerializationRoundTrip() { .build()) .withWaterRight("Test Water Right").build(); WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() - .withWaterUser(user).withContractName("Test Contract").withPumpAccounting(buildPumpAccounting()).build(); + .withWaterUser(user).withContractName("Test Contract").withPumpInAccounting(buildTestPumpInAccountingList()).build(); String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), waterSupplyAccounting); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, @@ -70,7 +71,9 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception .withName("Test Location").build()) .withWaterRight("Test Water Right").build()) .withContractName("Test Contract") - .withPumpAccounting(buildPumpAccounting()).build(); + .withPumpInAccounting(buildTestPumpInAccountingList()) + .withPumpBelowAccounting(buildTestPumpInAccountingList()) + .build(); InputStream resource = this.getClass().getResourceAsStream( "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); assertNotNull(resource); @@ -115,20 +118,25 @@ void testValidate() { } - private static List buildPumpAccounting() { - List pumpList = new ArrayList<>(); - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type").build()).withFlow(1.0) - .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build(); - pumpList.add(pumpAccounting); - PumpAccounting pumpAccounting2 = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump 2").build()) - .withTransferType(new LookupType.Builder().withActive(true).withTooltip("Test Tool Tip 2").withOfficeId(OFFICE) - .withDisplayValue("Test Transfer Type 2").build()).withFlow(2.0) - .withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment 2").build(); - pumpList.add(pumpAccounting2); - return pumpList; + private Map buildTestPumpInAccountingList() { + Map retList = new HashMap<>(); + + NavigableMap pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochMilli(10000012648000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") + .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); + pumpMap.put(Instant.ofEpochMilli(10000012649000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") + .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012649000L)).withComment("Test Comment 2").build()); + PumpAccounting accounting = new PumpAccounting.Builder().withPumpTransfers(pumpMap) + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump").build()).build(); + retList.put("Test Pump", accounting); + pumpMap = new TreeMap<>(); + pumpMap.put(Instant.ofEpochMilli(10000012699000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") + .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012699000L)).withComment("Test Comment").build()); + pumpMap.put(Instant.ofEpochMilli(10000012710000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") + .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012710000L)).withComment("Test Comment 2").build()); + accounting = new PumpAccounting.Builder().withPumpTransfers(pumpMap) + .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump2").build()).build(); + retList.put("Test Pump2", accounting); + return retList; } } diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index db4385a95..5d37896f5 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -48,13 +48,16 @@ import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; import cwms.cda.data.dto.watersupply.PumpAccounting; +import cwms.cda.data.dto.watersupply.PumpTransfer; import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; import cwms.cda.data.dto.watersupply.WaterSupplyPump; import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; + +import java.time.Instant; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; @@ -358,28 +361,57 @@ private static void assertMatch(Double first, Double second, String message) { assertMatch(first, second, DEFAULT_DELTA, message); } - public static void assertMatch(List first, List second) { + public static void assertMatch(Map first, Map second) { + + if (first == null && second == null) { + return; + } + + if ((first == null && second != null) || (first != null && second == null)) { + fail("One map is null, the other is not"); + } + + if (first.size() != second.size()) { + fail("First map size " + first.size() + " does not match second map size " + second.size()); + } - Iterator it1 = first.iterator(); - Iterator it2 = second.iterator(); - while (it1.hasNext() && it2.hasNext()) { - PumpAccounting pumpAccounting1 = it1.next(); - PumpAccounting pumpAccounting2 = it2.next(); + for (Map.Entry entry : first.entrySet()) { + PumpAccounting firstMap = entry.getValue(); + PumpAccounting secondMap = second.get(entry.getKey()); + if (secondMap == null) { + fail("Second map does not contain key " + entry.getKey()); + } + assertMatch(firstMap, secondMap); + } + } + + public static void assertMatch(PumpAccounting first, PumpAccounting second) { + + assertMatch(first.getPumpLocation(), second.getPumpLocation()); + + for (Map.Entry entry : first.getPumpTransfers().entrySet()) { + PumpTransfer firstPumpTransfer = entry.getValue(); + PumpTransfer secondPumpTransfer = second.getPumpTransfers().get(entry.getKey()); + if (secondPumpTransfer == null) { + fail("Second map does not contain key " + entry.getKey()); + } assertAll( - () -> assertMatch(pumpAccounting1.getPumpLocation(), pumpAccounting2.getPumpLocation()), - () -> assertMatch(pumpAccounting1.getTransferType(), pumpAccounting2.getTransferType()), - () -> assertEquals(pumpAccounting1.getFlow(), pumpAccounting2.getFlow()), - () -> assertEquals(pumpAccounting1.getTransferDate(), pumpAccounting2.getTransferDate()), - () -> assertEquals(pumpAccounting1.getComment(), pumpAccounting2.getComment()) + () -> assertEquals(firstPumpTransfer.getTransferTypeDisplay(), secondPumpTransfer.getTransferTypeDisplay()), + () -> assertEquals(firstPumpTransfer.getFlow(), secondPumpTransfer.getFlow()), + () -> assertEquals(firstPumpTransfer.getTransferDate(), secondPumpTransfer.getTransferDate()), + () -> assertEquals(firstPumpTransfer.getComment(), secondPumpTransfer.getComment()) ); } + } public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { assertAll( () -> assertEquals(first.getContractName(), second.getContractName()), () -> assertMatch(first.getWaterUser(), second.getWaterUser()), - () -> assertMatch(first.getPumpAccounting(), second.getPumpAccounting()) + () -> assertMatch(first.getPumpInAccounting(), second.getPumpInAccounting()), + () -> assertMatch(first.getPumpOutAccounting(), second.getPumpOutAccounting()), + () -> assertMatch(first.getPumpBelowAccounting(), second.getPumpBelowAccounting()) ); } diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 068050f82..c5fe3e596 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -3,41 +3,93 @@ "water-user": { "entity-name": "Test Entity", "project-id": { - "name": "Test Location", - "office-id": "SPK" + "office-id": "SPK", + "name": "Test Location" }, "water-right": "Test Water Right" }, - "pump-accounting": [ - { + "pump-in-accounting": { + "Test Pump": { "pump-location": { "office-id": "SPK", "name": "Test Location-Test Pump" }, - "transfer-type": { + "pump-transfers": { + "2286-11-20T21:17:28Z": { + "transfer-type-display": "Test Transfer Type", + "flow": 1, + "transfer-date": 10000012648000, + "comment": "Test Comment" + }, + "2286-11-20T21:17:29Z": { + "transfer-type-display": "Test Transfer Type", + "flow": 2, + "transfer-date": 10000012649000, + "comment": "Test Comment 2" + } + } + }, + "Test Pump2": { + "pump-location": { "office-id": "SPK", - "display-value": "Test Transfer Type", - "tooltip": "Test Tool Tip", - "active": true + "name": "Test Location-Test Pump2" }, - "flow": 1, - "transfer-date": 10000012648000, - "comment": "Test Comment" - }, - { + "pump-transfers": { + "2286-11-20T21:18:19Z": { + "transfer-type-display": "Test Transfer Type2", + "flow": 1, + "transfer-date": 10000012699000, + "comment": "Test Comment" + }, + "2286-11-20T21:18:30Z": { + "transfer-type-display": "Test Transfer Type2", + "flow": 2, + "transfer-date": 10000012710000, + "comment": "Test Comment 2" + } + } + } + }, + "pump-below-accounting": { + "Test Pump": { "pump-location": { "office-id": "SPK", - "name": "Test Location-Test Pump 2" + "name": "Test Location-Test Pump" }, - "transfer-type": { + "pump-transfers": { + "2286-11-20T21:17:28Z": { + "transfer-type-display": "Test Transfer Type", + "flow": 1, + "transfer-date": 10000012648000, + "comment": "Test Comment" + }, + "2286-11-20T21:17:29Z": { + "transfer-type-display": "Test Transfer Type", + "flow": 2, + "transfer-date": 10000012649000, + "comment": "Test Comment 2" + } + } + }, + "Test Pump2": { + "pump-location": { "office-id": "SPK", - "display-value": "Test Transfer Type 2", - "tooltip": "Test Tool Tip 2", - "active": true + "name": "Test Location-Test Pump2" }, - "flow": 2.0, - "transfer-date": 10000012648000, - "comment": "Test Comment 2" + "pump-transfers": { + "2286-11-20T21:18:19Z": { + "transfer-type-display": "Test Transfer Type2", + "flow": 1, + "transfer-date": 10000012699000, + "comment": "Test Comment" + }, + "2286-11-20T21:18:30Z": { + "transfer-type-display": "Test Transfer Type2", + "flow": 2, + "transfer-date": 10000012710000, + "comment": "Test Comment 2" + } + } } - ] + } } \ No newline at end of file From 1a86b94706fba4a45bd8af0b85ab9732efeb65bb Mon Sep 17 00:00:00 2001 From: zack-rma Date: Tue, 27 Aug 2024 08:45:45 -0700 Subject: [PATCH 34/39] Finalized pump transfer dto --- .../main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java index 4c08fcefd..75c9851c7 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java @@ -33,7 +33,7 @@ import java.time.Instant; @JsonDeserialize(builder = PumpTransfer.Builder.class) -public class PumpTransfer extends CwmsDTOBase { +public final class PumpTransfer extends CwmsDTOBase { @JsonProperty(required = true) private final String transferTypeDisplay; @JsonProperty(required = true) From f834f819bb10b43afddfde7b50405e9428b6aec2 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Mon, 14 Oct 2024 12:23:18 -0700 Subject: [PATCH 35/39] CTO-97 - Water Pump Accounting DTO update with TS-style JSON --- .../cda/data/dto/watersupply/PumpColumn.java | 67 ++++++++++ ...{PumpAccounting.java => PumpLocation.java} | 58 ++++---- .../data/dto/watersupply/PumpTransfer.java | 66 +++------ .../watersupply/WaterSupplyAccounting.java | 106 +++++++++++---- .../dto/watersupply/PumpAccountingTest.java | 114 ++++++++-------- .../WaterSupplyAccountingTest.java | 92 +++++++------ .../test/java/cwms/cda/helpers/DTOMatch.java | 98 ++++++++------ .../watersupply/water_supply_accounting.json | 126 ++++++------------ 8 files changed, 409 insertions(+), 318 deletions(-) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java rename cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/{PumpAccounting.java => PumpLocation.java} (54%) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java new file mode 100644 index 000000000..7379f7aca --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java @@ -0,0 +1,67 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.annotation.JsonIncludeProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonIncludeProperties("data-columns") +@JsonPropertyOrder({"0", "1", "2", "3"}) +public final class PumpColumn { + @JsonProperty(index = 0, value = "0") + private final String pumpType; + @JsonProperty(index = 1, value = "1") + private final String transferTypeDisplay; + @JsonProperty(index = 2, value = "2") + private final String flow; + @JsonProperty(index = 3, value = "3") + private final String comment; + + public String getPumpType() { + return pumpType; + } + + public String getTransferTypeDisplay() { + return transferTypeDisplay; + } + + public String getFlow() { + return flow; + } + + public String getComment() { + return comment; + } + + public PumpColumn() { + this.pumpType = "pump-type"; + this.transferTypeDisplay = "transfer-type-display"; + this.flow = "flow"; + this.comment = "comment"; + } +} diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpLocation.java similarity index 54% rename from cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java rename to cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpLocation.java index 51c61efab..72d06680d 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpLocation.java @@ -26,50 +26,58 @@ package cwms.cda.data.dto.watersupply; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import cwms.cda.data.dto.CwmsDTOBase; +import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsId; -import java.time.Instant; -import java.util.Map; +@JsonDeserialize(builder = PumpLocation.Builder.class) +@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) +public final class PumpLocation { + private final CwmsId pumpIn; + private final CwmsId pumpOut; + private final CwmsId pumpBelow; -@JsonDeserialize(builder = PumpAccounting.Builder.class) -public final class PumpAccounting extends CwmsDTOBase { - @JsonProperty(required = true) - private final CwmsId pumpLocation; - @JsonProperty(required = true) - private final Map pumpTransfers; + private PumpLocation(Builder builder) { + this.pumpIn = builder.pumpIn; + this.pumpOut = builder.pumpOut; + this.pumpBelow = builder.pumpBelow; + } - private PumpAccounting(Builder builder) { - this.pumpLocation = builder.pumpLocation; - this.pumpTransfers = builder.pumpTransfers; + public CwmsId getPumpIn() { + return this.pumpIn; } - public CwmsId getPumpLocation() { - return this.pumpLocation; + public CwmsId getPumpOut() { + return this.pumpOut; } - public Map getPumpTransfers() { - return this.pumpTransfers; + public CwmsId getPumpBelow() { + return this.pumpBelow; } public static final class Builder { - private CwmsId pumpLocation; - private Map pumpTransfers; + private CwmsId pumpIn; + private CwmsId pumpOut; + private CwmsId pumpBelow; + + public Builder withPumpIn(CwmsId pumpIn) { + this.pumpIn = pumpIn; + return this; + } - public Builder withPumpLocation(CwmsId pumpLocation) { - this.pumpLocation = pumpLocation; + public Builder withPumpOut(CwmsId pumpOut) { + this.pumpOut = pumpOut; return this; } - public Builder withPumpTransfers(Map pumpTransfers) { - this.pumpTransfers = pumpTransfers; + public Builder withPumpBelow(CwmsId pumpBelow) { + this.pumpBelow = pumpBelow; return this; } - public PumpAccounting build() { - return new PumpAccounting(this); + public PumpLocation build() { + return new PumpLocation(this); } } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java index 75c9851c7..4eaed2a36 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpTransfer.java @@ -26,27 +26,33 @@ package cwms.cda.data.dto.watersupply; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; import cwms.cda.data.dto.CwmsDTOBase; -import java.time.Instant; - -@JsonDeserialize(builder = PumpTransfer.Builder.class) +@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) +@JsonFormat(shape = JsonFormat.Shape.ARRAY) public final class PumpTransfer extends CwmsDTOBase { - @JsonProperty(required = true) + @JsonProperty(required = true, index = 0) + private final PumpType pumpType; + @JsonProperty(required = true, index = 1) private final String transferTypeDisplay; - @JsonProperty(required = true) + @JsonProperty(required = true, index = 2) private final Double flow; - @JsonProperty(required = true) - private final Instant transferDate; + @JsonProperty(required = true, index = 3) private final String comment; - private PumpTransfer(Builder builder) { - this.transferTypeDisplay = builder.transferTypeDisplay; - this.flow = builder.flow; - this.transferDate = builder.transferDate; - this.comment = builder.comment; + @JsonCreator + public PumpTransfer(@JsonProperty("pump-type") PumpType pumpType, + @JsonProperty("transfer-type-display") String transferTypeDisplay, + @JsonProperty("flow") Double flow, @JsonProperty("comment") String comment) { + this.transferTypeDisplay = transferTypeDisplay; + this.flow = flow; + this.comment = comment; + this.pumpType = pumpType; } public String getTransferTypeDisplay() { @@ -57,42 +63,12 @@ public Double getFlow() { return this.flow; } - public Instant getTransferDate() { - return this.transferDate; + public PumpType getPumpType() { + return this.pumpType; } public String getComment() { return this.comment; } - public static final class Builder { - private String transferTypeDisplay; - private Double flow; - private Instant transferDate; - private String comment; - - public Builder withTransferTypeDisplay(String transferTypeDisplay) { - this.transferTypeDisplay = transferTypeDisplay; - return this; - } - - public Builder withFlow(Double flow) { - this.flow = flow; - return this; - } - - public Builder withTransferDate(Instant transferDate) { - this.transferDate = transferDate; - return this; - } - - public Builder withComment(String comment) { - this.comment = comment; - return this; - } - - public PumpTransfer build() { - return new PumpTransfer(this); - } - } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 615fdefc4..95c23844a 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -26,38 +26,49 @@ package cwms.cda.data.dto.watersupply; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonNaming; -import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.data.dto.CwmsDTOPaginated; import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; +import io.swagger.v3.oas.annotations.media.Schema; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Map; @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, aliases = {Formats.DEFAULT, Formats.JSON}) @JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) @JsonDeserialize(builder = WaterSupplyAccounting.Builder.class) @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) -public final class WaterSupplyAccounting extends CwmsDTOBase { +public final class WaterSupplyAccounting extends CwmsDTOPaginated { @JsonProperty(required = true) private final String contractName; @JsonProperty(required = true) private final WaterUser waterUser; - private final Map pumpInAccounting; - private final Map pumpOutAccounting; - private final Map pumpBelowAccounting; + @JsonProperty(required = true) + private final PumpLocation pumpLocations; + @JsonProperty(value = "data-columns") + @Schema(name = "data-columns") + private final PumpColumn pumpColumn; + private final Map> pumpAccounting; private WaterSupplyAccounting(Builder builder) { + super(builder.page, builder.pageSize, builder.total); this.contractName = builder.contractName; this.waterUser = builder.waterUser; - this.pumpBelowAccounting = builder.pumpBelowAccounting; - this.pumpInAccounting = builder.pumpInAccounting; - this.pumpOutAccounting = builder.pumpOutAccounting; + this.pumpLocations = builder.pumpLocations; + this.pumpAccounting = builder.pumpAccounting; + this.pumpColumn = new PumpColumn(); } public String getContractName() { @@ -68,24 +79,28 @@ public WaterUser getWaterUser() { return this.waterUser; } - public Map getPumpInAccounting() { - return this.pumpInAccounting; + public PumpColumn getPumpColumn() { + return this.pumpColumn; } - public Map getPumpOutAccounting() { - return this.pumpOutAccounting; + public Map> getPumpAccounting() { + return this.pumpAccounting; } - public Map getPumpBelowAccounting() { - return this.pumpBelowAccounting; + public PumpLocation getPumpLocations() { + return this.pumpLocations; } public static final class Builder { private String contractName; private WaterUser waterUser; - private Map pumpInAccounting; - private Map pumpOutAccounting; - private Map pumpBelowAccounting; + private Map> pumpAccounting; + private PumpLocation pumpLocations; + @JsonProperty(value = "data-columns") + private PumpColumn pumpColumn; + private String page; + private int pageSize; + private int total; public Builder withContractName(String contractName) { this.contractName = contractName; @@ -97,21 +112,30 @@ public Builder withWaterUser(WaterUser waterUser) { return this; } - public Builder withPumpInAccounting( - Map pumpInAccounting) { - this.pumpInAccounting = pumpInAccounting; + public Builder withPumpAccounting( + Map> pumpAccounting) { + this.pumpAccounting = pumpAccounting; return this; } - public Builder withPumpOutAccounting( - Map pumpOutAccounting) { - this.pumpOutAccounting = pumpOutAccounting; + public Builder withPumpLocations( + PumpLocation pumpLocations) { + this.pumpLocations = pumpLocations; return this; } - public Builder withPumpBelowAccounting( - Map pumpBelowAccounting) { - this.pumpBelowAccounting = pumpBelowAccounting; + public Builder withPage(String page) { + this.page = page; + return this; + } + + public Builder withPageSize(int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Builder withTotal(int total) { + this.total = total; return this; } @@ -119,4 +143,34 @@ public WaterSupplyAccounting build() { return new WaterSupplyAccounting(this); } } + + public void addTransfer(Timestamp dateTime, double flowValue, String transferTypeDisplay, String comment, + PumpType pumpType, Timestamp previousDateTime) { + if ((page == null || page.isEmpty()) && (pumpAccounting == null || pumpAccounting.isEmpty())) { + page = encodeCursor(delimiter, String.format("%d", dateTime.getTime()), total); + } + if (pageSize > 0 && mapSize(pumpAccounting) == pageSize) { + nextPage = encodeCursor(delimiter, String.format("%d", previousDateTime.getTime()), total); + } else { + assert pumpAccounting != null; + pumpAccounting.computeIfAbsent(dateTime.toInstant(), k -> new ArrayList<>()); + pumpAccounting.get(dateTime.toInstant()).add(new PumpTransfer(pumpType, transferTypeDisplay, + flowValue, comment)); + } + } + + public void addNullValue(Timestamp dateTime, int index) { + pumpAccounting.get(dateTime.toInstant()).add(index, null); + } + + private static int mapSize(Map> map) { + int size = 0; + if (map == null) { + return size; + } + for (List list : map.values()) { + size += list.size(); + } + return size; + } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java index e5d8e2510..779209193 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java @@ -37,6 +37,8 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -70,81 +72,83 @@ void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Except void testValidate() { assertAll( () -> { - Map pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochSecond(10000012648112L), new PumpTransfer.Builder() - .withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) - .withComment("Test Comment").build()); - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Pump").build()) - .withPumpTransfers(pumpMap).build(); + WaterSupplyAccounting pumpAccounting = buildTestAccounting(); assertDoesNotThrow(pumpAccounting::validate, "Expected validation to pass"); }, () -> { - Map pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochSecond(10000012648112L), new PumpTransfer.Builder() - .withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) - .withComment("Test Comment").build()); - PumpAccounting pumpAccounting = new PumpAccounting.Builder() - .withPumpLocation(null).withPumpTransfers(pumpMap).build(); - assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " - + "fail due to null location"); - }, - () -> { - PumpTransfer pumpTransfer = new PumpTransfer.Builder() - .withTransferDate(null) - .withTransferTypeDisplay("Test Transfer Type").withFlow(1.0) - .withComment("Test Comment").build(); + PumpTransfer pumpTransfer = new PumpTransfer(null, "Test Transfer Type", 1.0, "Test Comment"); assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " - + "fail due to null transfer date"); + + "fail due to null pump type"); }, () -> { - PumpTransfer pumpTransfer = new PumpTransfer.Builder() - .withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withTransferTypeDisplay("Test Transfer Type").withFlow(null) - .withComment("Test Comment").build(); + PumpTransfer pumpTransfer = new PumpTransfer(PumpType.OUT, "Test Transfer Type 3", null, "Test Comment 3"); assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " + "fail due to null flow value"); }, () -> { - PumpTransfer pumpTransfer = new PumpTransfer.Builder() - .withTransferDate(Instant.ofEpochSecond(10000012648112L)) - .withTransferTypeDisplay(null).withFlow(1.0) - .withComment(null).build(); + PumpTransfer pumpTransfer = new PumpTransfer(PumpType.BELOW, null, 4.0, "Test Comment 4"); assertThrows(FieldException.class, pumpTransfer::validate, "Expected validation to " + "fail due to null transfer type display value"); + }, + () -> { + WaterSupplyAccounting pumpAccounting = new WaterSupplyAccounting.Builder().withPumpAccounting(buildTestPumpInAccountingList()) + .withPumpLocations(null).withContractName("Sacramento River Water Contract") + .withWaterUser(new WaterUser.Builder().withWaterRight("State of California Water Rights Permit #12345") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta") + .build()).withEntityName("California Department of Water Resources").build()).build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null pump locations"); + }, + () -> { + WaterSupplyAccounting pumpAccounting = new WaterSupplyAccounting.Builder().withPumpAccounting(buildTestPumpInAccountingList()) + .withPumpLocations(buildTestPumpLocation()).withContractName(null) + .withWaterUser(new WaterUser.Builder().withWaterRight("State of California Water Rights Permit #12345") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta") + .build()).withEntityName("California Department of Water Resources").build()).build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null contract name"); + }, + () -> { + WaterSupplyAccounting pumpAccounting = new WaterSupplyAccounting.Builder().withPumpAccounting(buildTestPumpInAccountingList()) + .withPumpLocations(buildTestPumpLocation()).withContractName("Sacramento River Water Contract") + .withWaterUser(null).build(); + assertThrows(FieldException.class, pumpAccounting::validate, "Expected validation to " + + "fail due to null water user"); } ); } private WaterSupplyAccounting buildTestAccounting() { - return new WaterSupplyAccounting.Builder().withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") - .withWaterRight("Test Water Right").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()).build()) - .withContractName("Test Contract").withPumpInAccounting(buildTestPumpInAccountingList()) - .withPumpBelowAccounting(buildTestPumpInAccountingList()) + return new WaterSupplyAccounting.Builder().withWaterUser(new WaterUser.Builder().withEntityName("California Department of Water Resources") + .withWaterRight("State of California Water Rights Permit #12345").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Sacramento River Delta").build()).build()).withPumpLocations(buildTestPumpLocation()) + .withContractName("Sacramento River Water Contract").withPumpAccounting(buildTestPumpInAccountingList()) .build(); } - private Map buildTestPumpInAccountingList() { - Map retMap = new TreeMap<>(); - Map pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochMilli(10000012648000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") - .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); - pumpMap.put(Instant.ofEpochMilli(10000012649000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") - .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012649000L)).withComment("Test Comment 2").build()); - PumpAccounting pumpAccounting = new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Location-Test Pump").build()).withPumpTransfers(pumpMap).build(); - retMap.put("Test Pump", pumpAccounting); - pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochMilli(10000012699000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") - .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012699000L)).withComment("Test Comment").build()); - pumpMap.put(Instant.ofEpochMilli(10000012710000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") - .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012710000L)).withComment("Test Comment 2").build()); - pumpAccounting = new PumpAccounting.Builder().withPumpLocation(new CwmsId.Builder() - .withOfficeId(OFFICE).withName("Test Location-Test Pump2").build()).withPumpTransfers(pumpMap).build(); - retMap.put("Test Pump2", pumpAccounting); + private Map> buildTestPumpInAccountingList() { + Map> retMap = new TreeMap<>(); + List pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN, "Pipeline", 1.0, "Added water to the system")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 2.0, "Removed excess water")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 3.0, "Daily water release")); + retMap.put(Instant.ofEpochMilli(1668979048000L), pumpMap); + pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN, "Pipeline", 4.0, "Pump transfer for the day")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 5.0, "Excess water transfer")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 6.0, "Water returned to the river")); + retMap.put(Instant.ofEpochMilli(1669065448000L), pumpMap); + pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN,"Pipeline", 7.0, "Pump transfer for the day")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 8.0, "Excess water transfer")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 9.0, "Water returned to the river")); + retMap.put(Instant.ofEpochMilli(1669151848000L), pumpMap); return retMap; } + + private PumpLocation buildTestPumpLocation() { + return new PumpLocation.Builder().withPumpIn(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 1").build()) + .withPumpOut(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 2").build()) + .withPumpBelow(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 3").build()).build(); + } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index 1a5a7730e..e8398badf 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -37,9 +37,9 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; -import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; import java.util.Map; -import java.util.NavigableMap; import java.util.TreeMap; @@ -48,14 +48,20 @@ class WaterSupplyAccountingTest { @Test void testWaterSupplyAccountingSerializationRoundTrip() { - WaterUser user = new WaterUser.Builder().withEntityName("Test Entity") + WaterUser user = new WaterUser.Builder().withEntityName("California Department of Water Resources") .withProjectId(new CwmsId.Builder() .withOfficeId(OFFICE) - .withName("Test Location") + .withName("Sacramento River Delta") .build()) - .withWaterRight("Test Water Right").build(); + .withWaterRight("State of California Water Rights Permit #12345").build(); WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() - .withWaterUser(user).withContractName("Test Contract").withPumpInAccounting(buildTestPumpInAccountingList()).build(); + .withWaterUser(user).withContractName("Sacramento River Water Contract").withPumpLocations( + new PumpLocation.Builder() + .withPumpIn(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 1").build()) + .withPumpOut(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 2").build()) + .withPumpBelow(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 3").build()) + .build()) + .withPumpAccounting(buildTestPumpAccountingList()).build(); String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), waterSupplyAccounting); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, @@ -67,12 +73,13 @@ void testWaterSupplyAccountingSerializationRoundTrip() { void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception { WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) - .withContractName("Test Contract") - .withPumpInAccounting(buildTestPumpInAccountingList()) - .withPumpBelowAccounting(buildTestPumpInAccountingList()) + .withEntityName("California Department of Water Resources") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Sacramento River Delta").build()) + .withWaterRight("State of California Water Rights Permit #12345").build()) + .withContractName("Sacramento River Water Contract") + .withPumpLocations(buildTestPumpLocation()) + .withPumpAccounting(buildTestPumpAccountingList()) .build(); InputStream resource = this.getClass().getResourceAsStream( "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); @@ -89,19 +96,24 @@ void testValidate() { assertAll( () -> { WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() - .withWaterUser(new WaterUser.Builder().withEntityName("Test Entity") + .withWaterUser(new WaterUser.Builder() + .withEntityName("California Department of Water Resources") .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()).withContractName("Test Contract") + .withName("Sacramento River Delta").build()) + .withWaterRight("State of California Water Rights Permit #12345").build()) + .withContractName("Sacramento River Water Contract") + .withPumpAccounting(buildTestPumpAccountingList()) + .withPumpLocations(buildTestPumpLocation()) .build(); assertDoesNotThrow(waterSupplyAccounting::validate, "Expected validation to pass"); }, () -> { WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() .withWaterUser(new WaterUser.Builder() - .withEntityName("Test Entity").withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) - .withName("Test Location").build()) - .withWaterRight("Test Water Right").build()) + .withEntityName("California Department of Water Resources") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Sacramento River Delta").build()) + .withWaterRight("State of California Water Rights Permit #12345").build()) .withContractName(null) .build(); assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " @@ -109,7 +121,7 @@ void testValidate() { }, () -> { WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() - .withContractName("Test Contract") + .withContractName("Sacramento River Water Contract") .build(); assertThrows(FieldException.class, waterSupplyAccounting::validate, "Expected validation to " + "fail due to null water user"); @@ -118,25 +130,29 @@ void testValidate() { } - private Map buildTestPumpInAccountingList() { - Map retList = new HashMap<>(); + private Map> buildTestPumpAccountingList() { + Map> retMap = new TreeMap<>(); + List pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN, "Pipeline", 1.0, "Added water to the system")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 2.0, "Removed excess water")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 3.0, "Daily water release")); + retMap.put(Instant.ofEpochMilli(1668979048000L), pumpMap); + pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN, "Pipeline", 4.0, "Pump transfer for the day")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 5.0, "Excess water transfer")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 6.0, "Water returned to the river")); + retMap.put(Instant.ofEpochMilli(1669065448000L), pumpMap); + pumpMap = new ArrayList<>(); + pumpMap.add(new PumpTransfer(PumpType.IN,"Pipeline", 7.0, "Pump transfer for the day")); + pumpMap.add(new PumpTransfer(PumpType.OUT, "Pipeline", 8.0, "Excess water transfer")); + pumpMap.add(new PumpTransfer(PumpType.BELOW, "River", 9.0, "Water returned to the river")); + retMap.put(Instant.ofEpochMilli(1669151848000L), pumpMap); + return retMap; + } - NavigableMap pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochMilli(10000012648000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") - .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012648000L)).withComment("Test Comment").build()); - pumpMap.put(Instant.ofEpochMilli(10000012649000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type") - .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012649000L)).withComment("Test Comment 2").build()); - PumpAccounting accounting = new PumpAccounting.Builder().withPumpTransfers(pumpMap) - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump").build()).build(); - retList.put("Test Pump", accounting); - pumpMap = new TreeMap<>(); - pumpMap.put(Instant.ofEpochMilli(10000012699000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") - .withFlow(1.0).withTransferDate(Instant.ofEpochMilli(10000012699000L)).withComment("Test Comment").build()); - pumpMap.put(Instant.ofEpochMilli(10000012710000L), new PumpTransfer.Builder().withTransferTypeDisplay("Test Transfer Type2") - .withFlow(2.0).withTransferDate(Instant.ofEpochMilli(10000012710000L)).withComment("Test Comment 2").build()); - accounting = new PumpAccounting.Builder().withPumpTransfers(pumpMap) - .withPumpLocation(new CwmsId.Builder().withOfficeId(OFFICE).withName("Test Location-Test Pump2").build()).build(); - retList.put("Test Pump2", accounting); - return retList; + private PumpLocation buildTestPumpLocation() { + return new PumpLocation.Builder().withPumpIn(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 1").build()) + .withPumpOut(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 2").build()) + .withPumpBelow(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 3").build()).build(); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index 5d37896f5..282c35d60 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -47,7 +47,7 @@ import cwms.cda.data.dto.stream.StreamLocation; import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; -import cwms.cda.data.dto.watersupply.PumpAccounting; +import cwms.cda.data.dto.watersupply.PumpLocation; import cwms.cda.data.dto.watersupply.PumpTransfer; import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; import cwms.cda.data.dto.watersupply.WaterSupplyPump; @@ -361,57 +361,67 @@ private static void assertMatch(Double first, Double second, String message) { assertMatch(first, second, DEFAULT_DELTA, message); } - public static void assertMatch(Map first, Map second) { - - if (first == null && second == null) { - return; - } - - if ((first == null && second != null) || (first != null && second == null)) { - fail("One map is null, the other is not"); - } - - if (first.size() != second.size()) { - fail("First map size " + first.size() + " does not match second map size " + second.size()); - } - - for (Map.Entry entry : first.entrySet()) { - PumpAccounting firstMap = entry.getValue(); - PumpAccounting secondMap = second.get(entry.getKey()); - if (secondMap == null) { - fail("Second map does not contain key " + entry.getKey()); - } - assertMatch(firstMap, secondMap); - } + public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { + assertAll( + () -> assertEquals(first.getContractName(), second.getContractName()), + () -> assertMatch(first.getWaterUser(), second.getWaterUser()), + () -> assertMatch(first.getPumpAccounting(), second.getPumpAccounting()), + () -> assertMatch(first.getPumpLocations(), second.getPumpLocations()) + ); } - public static void assertMatch(PumpAccounting first, PumpAccounting second) { - - assertMatch(first.getPumpLocation(), second.getPumpLocation()); + private static void assertMatch(Map> first, Map> second) { + assertAll( + () -> assertEquals(first.size(), second.size(), "Pump accounting sizes do not match"), + () -> first.forEach((key, value) -> { + List secondValue = second.get(key); + if (secondValue == null) { + fail("Pump accounting key not found: " + key); + } + assertMatch(value, secondValue); + }) + ); + } - for (Map.Entry entry : first.getPumpTransfers().entrySet()) { - PumpTransfer firstPumpTransfer = entry.getValue(); - PumpTransfer secondPumpTransfer = second.getPumpTransfers().get(entry.getKey()); - if (secondPumpTransfer == null) { - fail("Second map does not contain key " + entry.getKey()); + private static void assertMatch(PumpLocation first, PumpLocation second) { + assertAll( + () -> { + if (first != null && second != null) { + assertMatch(first.getPumpOut(), second.getPumpOut()); + } else if (!(first == null && second == null)) { + fail("Pump out locations do not match"); + } + }, + () -> { + if (first != null && second != null) { + assertMatch(first.getPumpIn(), second.getPumpIn()); + } else if (!(first == null && second == null)) { + fail("Pump in locations do not match"); + } + }, + () -> { + if (first != null && second != null) { + assertMatch(first.getPumpBelow(), second.getPumpBelow()); + } else if (!(first == null && second == null)) { + fail("Pump below locations do not match"); + } } - assertAll( - () -> assertEquals(firstPumpTransfer.getTransferTypeDisplay(), secondPumpTransfer.getTransferTypeDisplay()), - () -> assertEquals(firstPumpTransfer.getFlow(), secondPumpTransfer.getFlow()), - () -> assertEquals(firstPumpTransfer.getTransferDate(), secondPumpTransfer.getTransferDate()), - () -> assertEquals(firstPumpTransfer.getComment(), secondPumpTransfer.getComment()) - ); - } + ); + } + private static void assertMatch(List first, List second) { + assertAll( + () -> assertEquals(first.size(), second.size(), "Pump transfer sizes do not match"), + () -> IntStream.range(0, first.size()).forEach(i -> assertMatch(first.get(i), second.get(i))) + ); } - public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccounting second) { + private static void assertMatch(PumpTransfer first, PumpTransfer second) { assertAll( - () -> assertEquals(first.getContractName(), second.getContractName()), - () -> assertMatch(first.getWaterUser(), second.getWaterUser()), - () -> assertMatch(first.getPumpInAccounting(), second.getPumpInAccounting()), - () -> assertMatch(first.getPumpOutAccounting(), second.getPumpOutAccounting()), - () -> assertMatch(first.getPumpBelowAccounting(), second.getPumpBelowAccounting()) + () -> assertEquals(first.getTransferTypeDisplay(), second.getTransferTypeDisplay()), + () -> assertEquals(first.getFlow(), second.getFlow()), + () -> assertEquals(first.getComment(), second.getComment()), + () -> assertEquals(first.getPumpType(), second.getPumpType()) ); } diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index c5fe3e596..33b0c391d 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -1,95 +1,51 @@ { - "contract-name": "Test Contract", + "contract-name": "Sacramento River Water Contract", "water-user": { - "entity-name": "Test Entity", + "entity-name": "California Department of Water Resources", "project-id": { "office-id": "SPK", - "name": "Test Location" + "name": "Sacramento River Delta" }, - "water-right": "Test Water Right" + "water-right": "State of California Water Rights Permit #12345" }, - "pump-in-accounting": { - "Test Pump": { - "pump-location": { - "office-id": "SPK", - "name": "Test Location-Test Pump" - }, - "pump-transfers": { - "2286-11-20T21:17:28Z": { - "transfer-type-display": "Test Transfer Type", - "flow": 1, - "transfer-date": 10000012648000, - "comment": "Test Comment" - }, - "2286-11-20T21:17:29Z": { - "transfer-type-display": "Test Transfer Type", - "flow": 2, - "transfer-date": 10000012649000, - "comment": "Test Comment 2" - } - } + "pump-locations": { + "pump-in": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 1" }, - "Test Pump2": { - "pump-location": { - "office-id": "SPK", - "name": "Test Location-Test Pump2" - }, - "pump-transfers": { - "2286-11-20T21:18:19Z": { - "transfer-type-display": "Test Transfer Type2", - "flow": 1, - "transfer-date": 10000012699000, - "comment": "Test Comment" - }, - "2286-11-20T21:18:30Z": { - "transfer-type-display": "Test Transfer Type2", - "flow": 2, - "transfer-date": 10000012710000, - "comment": "Test Comment 2" - } - } - } - }, - "pump-below-accounting": { - "Test Pump": { - "pump-location": { - "office-id": "SPK", - "name": "Test Location-Test Pump" - }, - "pump-transfers": { - "2286-11-20T21:17:28Z": { - "transfer-type-display": "Test Transfer Type", - "flow": 1, - "transfer-date": 10000012648000, - "comment": "Test Comment" - }, - "2286-11-20T21:17:29Z": { - "transfer-type-display": "Test Transfer Type", - "flow": 2, - "transfer-date": 10000012649000, - "comment": "Test Comment 2" - } - } + "pump-out": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 2" }, - "Test Pump2": { - "pump-location": { - "office-id": "SPK", - "name": "Test Location-Test Pump2" - }, - "pump-transfers": { - "2286-11-20T21:18:19Z": { - "transfer-type-display": "Test Transfer Type2", - "flow": 1, - "transfer-date": 10000012699000, - "comment": "Test Comment" - }, - "2286-11-20T21:18:30Z": { - "transfer-type-display": "Test Transfer Type2", - "flow": 2, - "transfer-date": 10000012710000, - "comment": "Test Comment 2" - } - } + "pump-below": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 3" } - } + }, + "data-columns": { + "0": "pump-type", + "1": "transfer-type-display", + "2": "flow", + "3": "comment" + }, + "pump-accounting": { + "2022-11-20T21:17:28Z": [ + ["IN", "Pipeline", 1.0, "Added water to the system"], + ["OUT", "Pipeline", 2.0, "Removed excess water"], + ["BELOW", "River", 3.0, "Daily water release"] + ], + "2022-11-21T21:17:28Z": [ + ["IN", "Pipeline", 4.0, "Pump transfer for the day"], + ["OUT", "Pipeline", 5.0, "Excess water transfer"], + ["BELOW", "River", 6.0, "Water returned to the river"] + ], + "2022-11-22T21:17:28Z": [ + ["IN", "Pipeline", 7.0, "Pump transfer for the day"], + ["OUT", "Pipeline", 8.0, "Excess water transfer"], + ["BELOW", "River", 9.0, "Water returned to the river"] + ] + }, + "page": "", + "page-size": 500, + "total": 6 } \ No newline at end of file From 49af9c382895cb4d64b4089a37ddf278e7e74582 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Mon, 28 Oct 2024 17:25:37 -0700 Subject: [PATCH 36/39] Updated format to match TimeSeries format, added tests --- .../cda/data/dto/watersupply/PumpColumn.java | 77 ++++++++++++------- .../watersupply/WaterSupplyAccounting.java | 50 +++--------- .../WaterSupplyAccountingTest.java | 30 ++++++++ .../test/java/cwms/cda/helpers/DTOMatch.java | 21 ++--- .../watersupply/water_supply_accounting.json | 28 +++++-- 5 files changed, 127 insertions(+), 79 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java index 7379f7aca..0b4955fc5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/PumpColumn.java @@ -26,42 +26,67 @@ package cwms.cda.data.dto.watersupply; -import com.fasterxml.jackson.annotation.JsonIncludeProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; -@JsonIncludeProperties("data-columns") -@JsonPropertyOrder({"0", "1", "2", "3"}) -public final class PumpColumn { - @JsonProperty(index = 0, value = "0") - private final String pumpType; - @JsonProperty(index = 1, value = "1") - private final String transferTypeDisplay; - @JsonProperty(index = 2, value = "2") - private final String flow; - @JsonProperty(index = 3, value = "3") - private final String comment; +@JsonDeserialize(builder = PumpColumn.Builder.class) +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, + aliases = {Formats.DEFAULT, Formats.JSON}) +public final class PumpColumn extends CwmsDTOBase { + @JsonProperty(value = "name", required = true) + private final String name; + @JsonProperty(value = "ordinal", required = true) + private final int ordinal; + @JsonProperty(value = "datatype", required = true) + private final String dataType; - public String getPumpType() { - return pumpType; + private PumpColumn(Builder builder) { + name = builder.name; + ordinal = builder.ordinal; + dataType = builder.dataType; } - public String getTransferTypeDisplay() { - return transferTypeDisplay; + public String getName() { + return name; } - public String getFlow() { - return flow; + public int getOrdinal() { + return ordinal; } - public String getComment() { - return comment; + public String getDataType() { + return dataType; } - public PumpColumn() { - this.pumpType = "pump-type"; - this.transferTypeDisplay = "transfer-type-display"; - this.flow = "flow"; - this.comment = "comment"; + public static class Builder { + @JsonProperty("name") + private String name; + @JsonProperty("ordinal") + private int ordinal; + @JsonProperty("datatype") + private String dataType; + + public Builder withName(String name) { + this.name = name; + return this; + } + + public Builder withOrdinal(int ordinal) { + this.ordinal = ordinal; + return this; + } + + public Builder withDataType(String dataType) { + this.dataType = dataType; + return this; + } + + public PumpColumn build() { + return new PumpColumn(this); + } } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 95c23844a..32ecdeb84 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -27,7 +27,6 @@ package cwms.cda.data.dto.watersupply; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @@ -37,7 +36,6 @@ import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; import io.swagger.v3.oas.annotations.media.Schema; -import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -45,8 +43,6 @@ @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, aliases = {Formats.DEFAULT, Formats.JSON}) -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) @JsonDeserialize(builder = WaterSupplyAccounting.Builder.class) @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) @@ -57,9 +53,9 @@ public final class WaterSupplyAccounting extends CwmsDTOPaginated { private final WaterUser waterUser; @JsonProperty(required = true) private final PumpLocation pumpLocations; - @JsonProperty(value = "data-columns") @Schema(name = "data-columns") - private final PumpColumn pumpColumn; + @JsonProperty(required = true, value = "data-columns") + private final List pumpColumn; private final Map> pumpAccounting; private WaterSupplyAccounting(Builder builder) { @@ -68,7 +64,7 @@ private WaterSupplyAccounting(Builder builder) { this.waterUser = builder.waterUser; this.pumpLocations = builder.pumpLocations; this.pumpAccounting = builder.pumpAccounting; - this.pumpColumn = new PumpColumn(); + this.pumpColumn = buildPumpColumns(); } public String getContractName() { @@ -79,7 +75,7 @@ public WaterUser getWaterUser() { return this.waterUser; } - public PumpColumn getPumpColumn() { + public List getPumpColumn() { return this.pumpColumn; } @@ -91,13 +87,12 @@ public PumpLocation getPumpLocations() { return this.pumpLocations; } + @JsonIgnoreProperties("data-columns") public static final class Builder { private String contractName; private WaterUser waterUser; private Map> pumpAccounting; private PumpLocation pumpLocations; - @JsonProperty(value = "data-columns") - private PumpColumn pumpColumn; private String page; private int pageSize; private int total; @@ -144,33 +139,12 @@ public WaterSupplyAccounting build() { } } - public void addTransfer(Timestamp dateTime, double flowValue, String transferTypeDisplay, String comment, - PumpType pumpType, Timestamp previousDateTime) { - if ((page == null || page.isEmpty()) && (pumpAccounting == null || pumpAccounting.isEmpty())) { - page = encodeCursor(delimiter, String.format("%d", dateTime.getTime()), total); - } - if (pageSize > 0 && mapSize(pumpAccounting) == pageSize) { - nextPage = encodeCursor(delimiter, String.format("%d", previousDateTime.getTime()), total); - } else { - assert pumpAccounting != null; - pumpAccounting.computeIfAbsent(dateTime.toInstant(), k -> new ArrayList<>()); - pumpAccounting.get(dateTime.toInstant()).add(new PumpTransfer(pumpType, transferTypeDisplay, - flowValue, comment)); - } - } - - public void addNullValue(Timestamp dateTime, int index) { - pumpAccounting.get(dateTime.toInstant()).add(index, null); - } - - private static int mapSize(Map> map) { - int size = 0; - if (map == null) { - return size; - } - for (List list : map.values()) { - size += list.size(); - } - return size; + private List buildPumpColumns() { + List retVal = new ArrayList<>(); + retVal.add(new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(PumpType.class.getTypeName()).build()); + retVal.add(new PumpColumn.Builder().withName("transfer-type-display").withOrdinal(2).withDataType(String.class.getTypeName()).build()); + retVal.add(new PumpColumn.Builder().withName("flow").withOrdinal(3).withDataType(Double.class.getTypeName()).build()); + retVal.add(new PumpColumn.Builder().withName("comment").withOrdinal(4).withDataType(String.class.getTypeName()).build()); + return retVal; } } diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index e8398badf..caf235c51 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -90,6 +90,36 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception DTOMatch.assertMatch(waterSupplyAccounting, deserialized); } + @Test + void testPumpColumn() { + PumpColumn pumpColumn = new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(PumpType.class.getTypeName()).build(); + assertAll( + () -> assertEquals("pump-type", pumpColumn.getName(), "Expected name to be 'pump-type'"), + () -> assertEquals(1, pumpColumn.getOrdinal(), "Expected ordinal to be 1"), + () -> assertEquals(PumpType.class.getTypeName(), pumpColumn.getDataType(), "Expected data type to be PumpType") + ); + } + + @Test + void testPumpColumnValidate() { + assertAll( + () -> { + PumpColumn testColumn = new PumpColumn.Builder() + .withName(null) + .withOrdinal(1) + .withDataType(PumpType.class.getTypeName()).build(); + assertThrows(FieldException.class, testColumn::validate); + }, + () -> { + PumpColumn testColumn = new PumpColumn.Builder() + .withName("pump-type") + .withOrdinal(1) + .withDataType(null).build(); + assertThrows(FieldException.class, testColumn::validate); + } + ); + } + @Test void testValidate() { diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index 282c35d60..aa62d58da 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -47,6 +47,7 @@ import cwms.cda.data.dto.stream.StreamLocation; import cwms.cda.data.dto.stream.StreamNode; import cwms.cda.data.dto.stream.StreamReach; +import cwms.cda.data.dto.watersupply.PumpColumn; import cwms.cda.data.dto.watersupply.PumpLocation; import cwms.cda.data.dto.watersupply.PumpTransfer; import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; @@ -366,7 +367,8 @@ public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccountin () -> assertEquals(first.getContractName(), second.getContractName()), () -> assertMatch(first.getWaterUser(), second.getWaterUser()), () -> assertMatch(first.getPumpAccounting(), second.getPumpAccounting()), - () -> assertMatch(first.getPumpLocations(), second.getPumpLocations()) + () -> assertMatch(first.getPumpLocations(), second.getPumpLocations()), + () -> assertMatch(first.getPumpColumn(), second.getPumpColumn(), DTOMatch::assertMatch) ); } @@ -378,11 +380,19 @@ private static void assertMatch(Map> first, Map assertEquals(first.getName(), second.getName(), "Pump column names do not match"), + () -> assertEquals(first.getOrdinal(), second.getOrdinal(), "Pump column ordinals do not match"), + () -> assertEquals(first.getDataType(), second.getDataType(), "Pump column data types do not match") + ); + } + private static void assertMatch(PumpLocation first, PumpLocation second) { assertAll( () -> { @@ -409,13 +419,6 @@ private static void assertMatch(PumpLocation first, PumpLocation second) { ); } - private static void assertMatch(List first, List second) { - assertAll( - () -> assertEquals(first.size(), second.size(), "Pump transfer sizes do not match"), - () -> IntStream.range(0, first.size()).forEach(i -> assertMatch(first.get(i), second.get(i))) - ); - } - private static void assertMatch(PumpTransfer first, PumpTransfer second) { assertAll( () -> assertEquals(first.getTransferTypeDisplay(), second.getTransferTypeDisplay()), diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 33b0c391d..6ba819d01 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -22,12 +22,28 @@ "name": "Sacramento River Delta-Dam Water Pump 3" } }, - "data-columns": { - "0": "pump-type", - "1": "transfer-type-display", - "2": "flow", - "3": "comment" - }, + "data-columns": [ + { + "name": "pump-type", + "ordinal": 1, + "datatype": "cwms.cda.data.dto.watersupply.PumpType" + }, + { + "name": "transfer-type-display", + "ordinal": 2, + "datatype": "java.lang.String" + }, + { + "name": "flow", + "ordinal": 3, + "datatype": "java.lang.Double" + }, + { + "name": "comment", + "ordinal": 4, + "datatype": "java.lang.String" + } + ], "pump-accounting": { "2022-11-20T21:17:28Z": [ ["IN", "Pipeline", 1.0, "Added water to the system"], From 6baeaf0f5b24797edfc3bf79631588b865feae0e Mon Sep 17 00:00:00 2001 From: zack-rma Date: Tue, 29 Oct 2024 08:53:22 -0700 Subject: [PATCH 37/39] Added test --- .../watersupply/WaterSupplyAccounting.java | 2 +- .../WaterSupplyAccountingTest.java | 35 +++++++++++++++++-- .../test/java/cwms/cda/helpers/DTOMatch.java | 4 +-- .../watersupply/water_supply_accounting.json | 2 +- 4 files changed, 36 insertions(+), 7 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index 32ecdeb84..d912e87f6 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -141,7 +141,7 @@ public WaterSupplyAccounting build() { private List buildPumpColumns() { List retVal = new ArrayList<>(); - retVal.add(new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(PumpType.class.getTypeName()).build()); + retVal.add(new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(String.class.getTypeName()).build()); retVal.add(new PumpColumn.Builder().withName("transfer-type-display").withOrdinal(2).withDataType(String.class.getTypeName()).build()); retVal.add(new PumpColumn.Builder().withName("flow").withOrdinal(3).withDataType(Double.class.getTypeName()).build()); retVal.add(new PumpColumn.Builder().withName("comment").withOrdinal(4).withDataType(String.class.getTypeName()).build()); diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index caf235c51..b32eaf78b 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -26,12 +26,12 @@ package cwms.cda.data.dto.watersupply; +import static cwms.cda.helpers.DTOMatch.assertMatch; import static org.junit.jupiter.api.Assertions.*; import cwms.cda.api.errors.FieldException; import cwms.cda.data.dto.CwmsId; import cwms.cda.formatters.Formats; -import cwms.cda.helpers.DTOMatch; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.org.apache.commons.io.IOUtils; import java.io.InputStream; @@ -66,7 +66,7 @@ void testWaterSupplyAccountingSerializationRoundTrip() { waterSupplyAccounting); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); - DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + assertMatch(waterSupplyAccounting, deserialized); } @Test @@ -87,7 +87,7 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccounting.class), serialized, WaterSupplyAccounting.class); - DTOMatch.assertMatch(waterSupplyAccounting, deserialized); + assertMatch(waterSupplyAccounting, deserialized); } @Test @@ -120,6 +120,35 @@ void testPumpColumnValidate() { ); } + @Test + void testBuildWSA() { + WaterUser user = new WaterUser.Builder().withEntityName("California Department of Water Resources") + .withProjectId(new CwmsId.Builder() + .withOfficeId(OFFICE) + .withName("Sacramento River Delta") + .build()) + .withWaterRight("State of California Water Rights Permit #12345").build(); + + WaterSupplyAccounting wsa = new WaterSupplyAccounting.Builder() + .withPage("YWJjZHx8MTAwfHwxMA==") + .withPageSize(10) + .withTotal(100) + .withPumpLocations(buildTestPumpLocation()) + .withContractName("Sacramento River Water Contract") + .withPumpAccounting(buildTestPumpAccountingList()) + .withWaterUser(user) + .build(); + assertAll( + () -> assertEquals("WVdKalpIeDhNVEF3Zkh3eE1BPT18fDEwMHx8MTA=", wsa.getPage(), "Expected page to be 'abcd'"), + () -> assertEquals(10, wsa.getPageSize(), "Expected page size to be 10"), + () -> assertEquals(100, wsa.getTotal(), "Expected total to be 100"), + () -> assertMatch(buildTestPumpLocation(), wsa.getPumpLocations()), + () -> assertMatch(buildTestPumpAccountingList(), wsa.getPumpAccounting()), + () -> assertMatch(user, wsa.getWaterUser()) + ); + assertDoesNotThrow(wsa::validate, "Expected validation to pass"); + } + @Test void testValidate() { diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index aa62d58da..e4ec8b6e5 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -372,7 +372,7 @@ public static void assertMatch(WaterSupplyAccounting first, WaterSupplyAccountin ); } - private static void assertMatch(Map> first, Map> second) { + public static void assertMatch(Map> first, Map> second) { assertAll( () -> assertEquals(first.size(), second.size(), "Pump accounting sizes do not match"), () -> first.forEach((key, value) -> { @@ -393,7 +393,7 @@ private static void assertMatch(PumpColumn first, PumpColumn second) { ); } - private static void assertMatch(PumpLocation first, PumpLocation second) { + public static void assertMatch(PumpLocation first, PumpLocation second) { assertAll( () -> { if (first != null && second != null) { diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json index 6ba819d01..e8194f8b2 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json @@ -26,7 +26,7 @@ { "name": "pump-type", "ordinal": 1, - "datatype": "cwms.cda.data.dto.watersupply.PumpType" + "datatype": "java.lang.String" }, { "name": "transfer-type-display", From 21f1cd31016eb1ab6ddd7ea233bcad97cda792c5 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Thu, 31 Oct 2024 16:32:08 -0700 Subject: [PATCH 38/39] Updated DTO paging structure --- .../watersupply/WaterSupplyAccounting.java | 46 ++++--- .../WaterSupplyAccountingList.java | 77 ++++++++++++ .../dto/watersupply/PumpAccountingTest.java | 2 +- .../WaterSupplyAccountingTest.java | 76 ++++++++++-- .../test/java/cwms/cda/helpers/DTOMatch.java | 9 ++ ...unting.json => water_pump_accounting.json} | 5 +- .../water_pump_accounting_list.json | 114 ++++++++++++++++++ 7 files changed, 288 insertions(+), 41 deletions(-) create mode 100644 cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java rename cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/{water_supply_accounting.json => water_pump_accounting.json} (97%) create mode 100644 cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting_list.json diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java index d912e87f6..22f01c38c 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccounting.java @@ -31,7 +31,7 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonNaming; -import cwms.cda.data.dto.CwmsDTOPaginated; +import cwms.cda.data.dto.CwmsDTOBase; import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; @@ -46,7 +46,7 @@ @JsonDeserialize(builder = WaterSupplyAccounting.Builder.class) @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class) @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) -public final class WaterSupplyAccounting extends CwmsDTOPaginated { +public final class WaterSupplyAccounting extends CwmsDTOBase { @JsonProperty(required = true) private final String contractName; @JsonProperty(required = true) @@ -59,7 +59,6 @@ public final class WaterSupplyAccounting extends CwmsDTOPaginated { private final Map> pumpAccounting; private WaterSupplyAccounting(Builder builder) { - super(builder.page, builder.pageSize, builder.total); this.contractName = builder.contractName; this.waterUser = builder.waterUser; this.pumpLocations = builder.pumpLocations; @@ -93,9 +92,6 @@ public static final class Builder { private WaterUser waterUser; private Map> pumpAccounting; private PumpLocation pumpLocations; - private String page; - private int pageSize; - private int total; public Builder withContractName(String contractName) { this.contractName = contractName; @@ -119,21 +115,6 @@ public Builder withPumpLocations( return this; } - public Builder withPage(String page) { - this.page = page; - return this; - } - - public Builder withPageSize(int pageSize) { - this.pageSize = pageSize; - return this; - } - - public Builder withTotal(int total) { - this.total = total; - return this; - } - public WaterSupplyAccounting build() { return new WaterSupplyAccounting(this); } @@ -141,10 +122,25 @@ public WaterSupplyAccounting build() { private List buildPumpColumns() { List retVal = new ArrayList<>(); - retVal.add(new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(String.class.getTypeName()).build()); - retVal.add(new PumpColumn.Builder().withName("transfer-type-display").withOrdinal(2).withDataType(String.class.getTypeName()).build()); - retVal.add(new PumpColumn.Builder().withName("flow").withOrdinal(3).withDataType(Double.class.getTypeName()).build()); - retVal.add(new PumpColumn.Builder().withName("comment").withOrdinal(4).withDataType(String.class.getTypeName()).build()); + retVal.add(new PumpColumn.Builder() + .withName("pump-type") + .withOrdinal(1) + .withDataType(String.class.getTypeName()) + .build()); + retVal.add(new PumpColumn.Builder() + .withName("transfer-type-display") + .withOrdinal(2) + .withDataType(String.class.getTypeName()) + .build()); + retVal.add(new PumpColumn.Builder() + .withName("flow").withOrdinal(3) + .withDataType(Double.class.getTypeName()) + .build()); + retVal.add(new PumpColumn.Builder() + .withName("comment") + .withOrdinal(4) + .withDataType(String.class.getTypeName()) + .build()); return retVal; } } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java new file mode 100644 index 000000000..96117a4b4 --- /dev/null +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java @@ -0,0 +1,77 @@ +/* + * + * MIT License + * + * Copyright (c) 2024 Hydrologic Engineering Center + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE + * SOFTWARE. + */ + +package cwms.cda.data.dto.watersupply; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import cwms.cda.data.dto.CwmsDTOBase; +import cwms.cda.formatters.Formats; +import cwms.cda.formatters.annotations.FormattableWith; +import cwms.cda.formatters.json.JsonV1; +import java.util.List; + +@FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, + aliases = {Formats.DEFAULT, Formats.JSON}) +@JsonDeserialize(builder = WaterSupplyAccountingList.Builder.class) +public class WaterSupplyAccountingList extends CwmsDTOBase { + @JsonProperty(required = true) + private final List waterSupplyAccounting; + @JsonProperty(required = true) + private final int pageSize; + + private WaterSupplyAccountingList(Builder builder) { + this.pageSize = builder.pageSize; + this.waterSupplyAccounting = builder.waterSupplyAccounting; + } + + public List getWaterSupplyAccounting() { + return this.waterSupplyAccounting; + } + + public int getPageSize() { + return this.pageSize; + } + + public static final class Builder { + private List waterSupplyAccounting; + private int pageSize; + + public Builder withWaterSupplyAccounting(List waterSupplyAccounting) { + this.waterSupplyAccounting = waterSupplyAccounting; + return this; + } + + public Builder withPageSize(int pageSize) { + this.pageSize = pageSize; + return this; + } + + public WaterSupplyAccountingList build() { + return new WaterSupplyAccountingList(this); + } + } +} diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java index 779209193..e35499829 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/PumpAccountingTest.java @@ -60,7 +60,7 @@ void testWaterSupplyPumpAccountingSerializationRoundTrip() { void testWaterSupplyPumpAccountingSerializationRoundTripFromFile() throws Exception { WaterSupplyAccounting pumpAccounting = buildTestAccounting(); InputStream resource = this.getClass().getResourceAsStream( - "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); + "/cwms/cda/data/dto/watersupply/water_pump_accounting.json"); assertNotNull(resource); String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java index b32eaf78b..cd60a500b 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingTest.java @@ -38,6 +38,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -82,7 +83,7 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception .withPumpAccounting(buildTestPumpAccountingList()) .build(); InputStream resource = this.getClass().getResourceAsStream( - "/cwms/cda/data/dto/watersupply/water_supply_accounting.json"); + "/cwms/cda/data/dto/watersupply/water_pump_accounting.json"); assertNotNull(resource); String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); WaterSupplyAccounting deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, @@ -90,6 +91,58 @@ void testWaterSupplyAccountingSerializationRoundTripFromFile() throws Exception assertMatch(waterSupplyAccounting, deserialized); } + @Test + void testWaterSupplyAccountingListSerializationRoundTrip() { + WaterUser user = new WaterUser.Builder().withEntityName("California Department of Water Resources") + .withProjectId(new CwmsId.Builder() + .withOfficeId(OFFICE) + .withName("Sacramento River Delta") + .build()) + .withWaterRight("State of California Water Rights Permit #12345").build(); + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(user).withContractName("Sacramento River Water Contract").withPumpLocations( + new PumpLocation.Builder() + .withPumpIn(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 1").build()) + .withPumpOut(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 2").build()) + .withPumpBelow(new CwmsId.Builder().withOfficeId(OFFICE).withName("Sacramento River Delta-Dam Water Pump 3").build()) + .build()) + .withPumpAccounting(buildTestPumpAccountingList()).build(); + WaterSupplyAccountingList waterSupplyAccountingList = new WaterSupplyAccountingList.Builder() + .withPageSize(10) + .withWaterSupplyAccounting(Collections.singletonList(waterSupplyAccounting)) + .build(); + String serialized = Formats.format(Formats.parseHeader(Formats.JSONV1, WaterSupplyAccountingList.class), + waterSupplyAccountingList); + WaterSupplyAccountingList deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccountingList.class), serialized, WaterSupplyAccountingList.class); + assertMatch(waterSupplyAccountingList, deserialized); + } + + @Test + void testWaterSupplyAccountingListSerializationRoundTripFromFile() throws Exception { + WaterSupplyAccounting waterSupplyAccounting = new WaterSupplyAccounting.Builder() + .withWaterUser(new WaterUser.Builder() + .withEntityName("California Department of Water Resources") + .withProjectId(new CwmsId.Builder().withOfficeId(OFFICE) + .withName("Sacramento River Delta").build()) + .withWaterRight("State of California Water Rights Permit #12345").build()) + .withContractName("Sacramento River Water Contract") + .withPumpLocations(buildTestPumpLocation()) + .withPumpAccounting(buildTestPumpAccountingList()) + .build(); + WaterSupplyAccountingList waterSupplyAccountingList = new WaterSupplyAccountingList.Builder() + .withPageSize(20) + .withWaterSupplyAccounting(Collections.singletonList(waterSupplyAccounting)) + .build(); + InputStream resource = this.getClass().getResourceAsStream( + "/cwms/cda/data/dto/watersupply/water_pump_accounting_list.json"); + assertNotNull(resource); + String serialized = IOUtils.toString(resource, StandardCharsets.UTF_8); + WaterSupplyAccountingList deserialized = Formats.parseContent(Formats.parseHeader(Formats.JSONV1, + WaterSupplyAccountingList.class), serialized, WaterSupplyAccountingList.class); + assertMatch(waterSupplyAccountingList, deserialized); + } + @Test void testPumpColumn() { PumpColumn pumpColumn = new PumpColumn.Builder().withName("pump-type").withOrdinal(1).withDataType(PumpType.class.getTypeName()).build(); @@ -130,23 +183,24 @@ void testBuildWSA() { .withWaterRight("State of California Water Rights Permit #12345").build(); WaterSupplyAccounting wsa = new WaterSupplyAccounting.Builder() - .withPage("YWJjZHx8MTAwfHwxMA==") - .withPageSize(10) - .withTotal(100) .withPumpLocations(buildTestPumpLocation()) .withContractName("Sacramento River Water Contract") .withPumpAccounting(buildTestPumpAccountingList()) .withWaterUser(user) .build(); + + WaterSupplyAccountingList wsaList = new WaterSupplyAccountingList.Builder() + .withPageSize(10) + .withWaterSupplyAccounting(Collections.singletonList(wsa)) + .build(); + assertAll( - () -> assertEquals("WVdKalpIeDhNVEF3Zkh3eE1BPT18fDEwMHx8MTA=", wsa.getPage(), "Expected page to be 'abcd'"), - () -> assertEquals(10, wsa.getPageSize(), "Expected page size to be 10"), - () -> assertEquals(100, wsa.getTotal(), "Expected total to be 100"), - () -> assertMatch(buildTestPumpLocation(), wsa.getPumpLocations()), - () -> assertMatch(buildTestPumpAccountingList(), wsa.getPumpAccounting()), - () -> assertMatch(user, wsa.getWaterUser()) + () -> assertEquals(10, wsaList.getPageSize(), "Expected page size to be 10"), + () -> assertMatch(buildTestPumpLocation(), wsaList.getWaterSupplyAccounting().get(0).getPumpLocations()), + () -> assertMatch(buildTestPumpAccountingList(), wsaList.getWaterSupplyAccounting().get(0).getPumpAccounting()), + () -> assertMatch(user, wsaList.getWaterSupplyAccounting().get(0).getWaterUser()) ); - assertDoesNotThrow(wsa::validate, "Expected validation to pass"); + assertDoesNotThrow(wsaList::validate, "Expected validation to pass"); } diff --git a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java index e4ec8b6e5..cdd982060 100644 --- a/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java +++ b/cwms-data-api/src/test/java/cwms/cda/helpers/DTOMatch.java @@ -51,6 +51,7 @@ import cwms.cda.data.dto.watersupply.PumpLocation; import cwms.cda.data.dto.watersupply.PumpTransfer; import cwms.cda.data.dto.watersupply.WaterSupplyAccounting; +import cwms.cda.data.dto.watersupply.WaterSupplyAccountingList; import cwms.cda.data.dto.watersupply.WaterSupplyPump; import cwms.cda.data.dto.watersupply.WaterUser; import cwms.cda.data.dto.watersupply.WaterUserContract; @@ -385,6 +386,14 @@ public static void assertMatch(Map> first, Map assertEquals(first.getPageSize(), second.getPageSize()), + () -> assertEquals(first.getWaterSupplyAccounting().size(), second.getWaterSupplyAccounting().size()), + () -> assertMatch(first.getWaterSupplyAccounting(), second.getWaterSupplyAccounting(), DTOMatch::assertMatch) + ); + } + private static void assertMatch(PumpColumn first, PumpColumn second) { assertAll( () -> assertEquals(first.getName(), second.getName(), "Pump column names do not match"), diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting.json similarity index 97% rename from cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json rename to cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting.json index e8194f8b2..32f3e19f9 100644 --- a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_supply_accounting.json +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting.json @@ -60,8 +60,5 @@ ["OUT", "Pipeline", 8.0, "Excess water transfer"], ["BELOW", "River", 9.0, "Water returned to the river"] ] - }, - "page": "", - "page-size": 500, - "total": 6 + } } \ No newline at end of file diff --git a/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting_list.json b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting_list.json new file mode 100644 index 000000000..c5cf28c12 --- /dev/null +++ b/cwms-data-api/src/test/resources/cwms/cda/data/dto/watersupply/water_pump_accounting_list.json @@ -0,0 +1,114 @@ +{ + "water-supply-accounting": [ + { + "contract-name": "Sacramento River Water Contract", + "water-user": { + "entity-name": "California Department of Water Resources", + "project-id": { + "office-id": "SPK", + "name": "Sacramento River Delta" + }, + "water-right": "State of California Water Rights Permit #12345" + }, + "pump-locations": { + "pump-in": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 1" + }, + "pump-out": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 2" + }, + "pump-below": { + "office-id": "SPK", + "name": "Sacramento River Delta-Dam Water Pump 3" + } + }, + "data-columns": [ + { + "name": "pump-type", + "ordinal": 1, + "datatype": "java.lang.String" + }, + { + "name": "transfer-type-display", + "ordinal": 2, + "datatype": "java.lang.String" + }, + { + "name": "flow", + "ordinal": 3, + "datatype": "java.lang.Double" + }, + { + "name": "comment", + "ordinal": 4, + "datatype": "java.lang.String" + } + ], + "pump-accounting": { + "2022-11-20T21:17:28Z": [ + [ + "IN", + "Pipeline", + 1.0, + "Added water to the system" + ], + [ + "OUT", + "Pipeline", + 2.0, + "Removed excess water" + ], + [ + "BELOW", + "River", + 3.0, + "Daily water release" + ] + ], + "2022-11-21T21:17:28Z": [ + [ + "IN", + "Pipeline", + 4.0, + "Pump transfer for the day" + ], + [ + "OUT", + "Pipeline", + 5.0, + "Excess water transfer" + ], + [ + "BELOW", + "River", + 6.0, + "Water returned to the river" + ] + ], + "2022-11-22T21:17:28Z": [ + [ + "IN", + "Pipeline", + 7.0, + "Pump transfer for the day" + ], + [ + "OUT", + "Pipeline", + 8.0, + "Excess water transfer" + ], + [ + "BELOW", + "River", + 9.0, + "Water returned to the river" + ] + ] + } + } + ], + "page-size": 20 +} \ No newline at end of file From 7d5210b8d3e21c0967f0eda64cd667727adade93 Mon Sep 17 00:00:00 2001 From: zack-rma Date: Fri, 1 Nov 2024 10:49:52 -0700 Subject: [PATCH 39/39] Updated DTO to initialize list --- .../data/dto/watersupply/WaterSupplyAccountingList.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java index 96117a4b4..f8577aa77 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/watersupply/WaterSupplyAccountingList.java @@ -32,7 +32,9 @@ import cwms.cda.formatters.Formats; import cwms.cda.formatters.annotations.FormattableWith; import cwms.cda.formatters.json.JsonV1; +import java.util.ArrayList; import java.util.List; +import org.jetbrains.annotations.NotNull; @FormattableWith(contentType = Formats.JSONV1, formatter = JsonV1.class, aliases = {Formats.DEFAULT, Formats.JSON}) @@ -57,11 +59,11 @@ public int getPageSize() { } public static final class Builder { - private List waterSupplyAccounting; + private List waterSupplyAccounting = new ArrayList<>(); private int pageSize; - public Builder withWaterSupplyAccounting(List waterSupplyAccounting) { - this.waterSupplyAccounting = waterSupplyAccounting; + public Builder withWaterSupplyAccounting(@NotNull List waterSupplyAccounting) { + this.waterSupplyAccounting.addAll(waterSupplyAccounting); return this; }