commit 7131f0f8202edd03b1e681e1b8cb12267952a08c Author: CloudOps Lab Bot Date: Tue Nov 24 11:58:54 2026 +0800 feat: initial starter state for campus-ops-java diff --git a/.mvn/maven.config b/.mvn/maven.config new file mode 100644 index 0000000..bd6030a --- /dev/null +++ b/.mvn/maven.config @@ -0,0 +1 @@ +# Ensures maven.multiModuleProjectDirectory resolves to campus-ops-java even inside -pl runs diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..c1db482 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,24 @@ +pipeline { + agent any + + stages { + stage('Checkout') { + steps { + checkout scm + } + } + + stage('Build & Test') { + steps { + sh 'mvn -B test' + } + } + } + + post { + always { + junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml,**/target/failsafe-reports/*.xml' + deleteDir() + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..4321646 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# campus-ops-java + +Multi-module Spring Boot 3.3 / Java 21 / Maven 3.9 clean-room workspace (`io.cloudops.*`) sharing one parent `pom.xml`: + +- `library-service/` — Ex 3.1 (Unit Testing & Mockito Doubles) +- `order-cart/` — Ex 3.2 & Challenge Lab 4 (API Integration Testing & Multibranch Pipeline) +- `math-microservices/` — Challenge Lab 2 (3-Microservice Full-Pyramid Testing) +- `freight-calculator/` — Ex 4.1, Ex 4.2 & Challenge Lab 3 (TDD & Checkstyle/PMD/CPD/JaCoCo Quality Gates) +- `overlays/` — Branch overlays (`quality-smells`, `lab3-starter`) pushed as separate Git branches by `seed-gitea.sh` diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 0000000..56b8c2e --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freight-calculator/pom.xml b/freight-calculator/pom.xml new file mode 100644 index 0000000..351aa2f --- /dev/null +++ b/freight-calculator/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + + io.cloudops + campus-ops-parent + 1.0.0-SNAPSHOT + + + freight-calculator + Freight Calculator + + + 0.85 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/freight-calculator/src/main/java/io/cloudops/freight/FreightCalculator.java b/freight-calculator/src/main/java/io/cloudops/freight/FreightCalculator.java new file mode 100644 index 0000000..f6a20e1 --- /dev/null +++ b/freight-calculator/src/main/java/io/cloudops/freight/FreightCalculator.java @@ -0,0 +1,52 @@ +package io.cloudops.freight; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.EnumMap; +import java.util.Map; + +/** Calculates parcel freight charges using weight brackets, region multipliers, and express surcharges. */ +public class FreightCalculator { + + private static final BigDecimal BASE_HANDLING_FEE = new BigDecimal("5.00"); + private static final BigDecimal EXPRESS_SURCHARGE = new BigDecimal("12.50"); + private static final double BULK_DISCOUNT_THRESHOLD_KG = 20.0d; + private static final BigDecimal BULK_DISCOUNT_FACTOR = new BigDecimal("0.90"); + + private static final Map RATE_PER_KG = new EnumMap<>(Region.class); + + static { + RATE_PER_KG.put(Region.DOMESTIC, new BigDecimal("2.25")); + RATE_PER_KG.put(Region.REGIONAL, new BigDecimal("4.50")); + RATE_PER_KG.put(Region.INTERNATIONAL, new BigDecimal("8.75")); + } + + /** + * Computes a freight quote rounded to two decimal places. + * + * @param weightKg shipment weight in kilograms (must be strictly positive) + * @param region destination shipping zone + * @param express true when priority air dispatch is requested + * @return calculated shipping total + */ + public BigDecimal calculateQuote(final double weightKg, final Region region, final boolean express) { + if (weightKg <= 0.0d || Double.isNaN(weightKg) || Double.isInfinite(weightKg)) { + throw new IllegalArgumentException("Weight must be a finite positive value: " + weightKg); + } + if (region == null) { + throw new UnsupportedRegionException("Destination region must not be null"); + } + + BigDecimal perKgRate = RATE_PER_KG.get(region); + BigDecimal variableCharge = perKgRate.multiply(BigDecimal.valueOf(weightKg)); + BigDecimal subtotal = BASE_HANDLING_FEE.add(variableCharge); + + if (weightKg >= BULK_DISCOUNT_THRESHOLD_KG) { + subtotal = subtotal.multiply(BULK_DISCOUNT_FACTOR); + } + if (express) { + subtotal = subtotal.add(EXPRESS_SURCHARGE); + } + return subtotal.setScale(2, RoundingMode.HALF_UP); + } +} diff --git a/freight-calculator/src/main/java/io/cloudops/freight/Region.java b/freight-calculator/src/main/java/io/cloudops/freight/Region.java new file mode 100644 index 0000000..415f62a --- /dev/null +++ b/freight-calculator/src/main/java/io/cloudops/freight/Region.java @@ -0,0 +1,8 @@ +package io.cloudops.freight; + +/** Supported shipping destination zones for Campus Ops freight quotes. */ +public enum Region { + DOMESTIC, + REGIONAL, + INTERNATIONAL +} diff --git a/freight-calculator/src/main/java/io/cloudops/freight/UnsupportedRegionException.java b/freight-calculator/src/main/java/io/cloudops/freight/UnsupportedRegionException.java new file mode 100644 index 0000000..fcef7a0 --- /dev/null +++ b/freight-calculator/src/main/java/io/cloudops/freight/UnsupportedRegionException.java @@ -0,0 +1,14 @@ +package io.cloudops.freight; + +/** Raised when a quote request specifies a missing or unsupported region. */ +public class UnsupportedRegionException extends RuntimeException { + + /** + * Constructs an UnsupportedRegionException. + * + * @param message descriptive error text + */ + public UnsupportedRegionException(final String message) { + super(message); + } +} diff --git a/freight-calculator/src/test/java/io/cloudops/freight/FreightCalculatorTest.java b/freight-calculator/src/test/java/io/cloudops/freight/FreightCalculatorTest.java new file mode 100644 index 0000000..c86a89a --- /dev/null +++ b/freight-calculator/src/test/java/io/cloudops/freight/FreightCalculatorTest.java @@ -0,0 +1,49 @@ +package io.cloudops.freight; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigDecimal; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class FreightCalculatorTest { + + private FreightCalculator calculator; + + @BeforeEach + void setUp() { + calculator = new FreightCalculator(); + } + + @ParameterizedTest + @CsvSource({ + "2.0, DOMESTIC, false, 9.50", + "4.0, REGIONAL, false, 23.00", + "2.0, INTERNATIONAL, true, 35.00" + }) + void calculatesStandardAndExpressRates( + final double weightKg, + final Region region, + final boolean express, + final String expected) { + assertEquals(new BigDecimal(expected), calculator.calculateQuote(weightKg, region, express)); + } + + @Test + void appliesBulkDiscountBeforeExpressSurchargeAtTwentyKgOrMore() { + // (5.00 + 20 * 2.25) * 0.90 + 12.50 = 50.00 * 0.90 + 12.50 = 57.50 + BigDecimal quote = calculator.calculateQuote(20.0d, Region.DOMESTIC, true); + assertEquals(new BigDecimal("57.50"), quote); + } + + @Test + void rejectsNonPositiveWeightAndNullRegion() { + assertThrows(IllegalArgumentException.class, () -> calculator.calculateQuote(0.0d, Region.DOMESTIC, false)); + assertThrows(IllegalArgumentException.class, () -> calculator.calculateQuote(-3.5d, Region.REGIONAL, true)); + assertThrows(IllegalArgumentException.class, () -> calculator.calculateQuote(Double.NaN, Region.DOMESTIC, false)); + assertThrows(UnsupportedRegionException.class, () -> calculator.calculateQuote(5.0d, null, false)); + } +} diff --git a/library-service/pom.xml b/library-service/pom.xml new file mode 100644 index 0000000..d1b3027 --- /dev/null +++ b/library-service/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + + io.cloudops + campus-ops-parent + 1.0.0-SNAPSHOT + + + library-service + Library Service + + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/library-service/src/main/java/io/cloudops/library/BookSummary.java b/library-service/src/main/java/io/cloudops/library/BookSummary.java new file mode 100644 index 0000000..52e75ae --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/BookSummary.java @@ -0,0 +1,5 @@ +package io.cloudops.library; + +/** Immutable catalog summary returned for a library title. */ +public record BookSummary(String isbn, String title, boolean available) { +} diff --git a/library-service/src/main/java/io/cloudops/library/CatalogClient.java b/library-service/src/main/java/io/cloudops/library/CatalogClient.java new file mode 100644 index 0000000..f379282 --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/CatalogClient.java @@ -0,0 +1,21 @@ +package io.cloudops.library; + +/** Port for looking up and updating book inventory state. */ +public interface CatalogClient { + + /** + * Retrieves catalog details for an ISBN. + * + * @param isbn normalized ISBN digits + * @return book summary, or null when not present + */ + BookSummary findByIsbn(String isbn); + + /** + * Marks a copy checked out to the specified member. + * + * @param isbn normalized ISBN digits + * @param memberId borrower identifier + */ + void markCheckedOut(String isbn, String memberId); +} diff --git a/library-service/src/main/java/io/cloudops/library/InvalidIsbnException.java b/library-service/src/main/java/io/cloudops/library/InvalidIsbnException.java new file mode 100644 index 0000000..15bd7a0 --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/InvalidIsbnException.java @@ -0,0 +1,14 @@ +package io.cloudops.library; + +/** Raised when a supplied ISBN does not match basic structural validation. */ +public class InvalidIsbnException extends RuntimeException { + + /** + * Creates a new InvalidIsbnException. + * + * @param message descriptive error message + */ + public InvalidIsbnException(final String message) { + super(message); + } +} diff --git a/library-service/src/main/java/io/cloudops/library/LoanReceipt.java b/library-service/src/main/java/io/cloudops/library/LoanReceipt.java new file mode 100644 index 0000000..79165c2 --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/LoanReceipt.java @@ -0,0 +1,5 @@ +package io.cloudops.library; + +/** Receipt issued after a successful book checkout. */ +public record LoanReceipt(String isbn, String memberId, String confirmationCode) { +} diff --git a/library-service/src/main/java/io/cloudops/library/LoanService.java b/library-service/src/main/java/io/cloudops/library/LoanService.java new file mode 100644 index 0000000..31482e3 --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/LoanService.java @@ -0,0 +1,63 @@ +package io.cloudops.library; + +import java.util.Objects; + +/** Coordinates campus book checkouts using catalog and notification collaborators. */ +public class LoanService { + + private final CatalogClient catalogClient; + private final NotificationSender notificationSender; + + /** + * Constructs a LoanService with its required ports. + * + * @param catalogClient catalog lookup and update client + * @param notificationSender member notification dispatcher + */ + public LoanService(final CatalogClient catalogClient, final NotificationSender notificationSender) { + this.catalogClient = Objects.requireNonNull(catalogClient, "catalogClient must not be null"); + this.notificationSender = Objects.requireNonNull( + notificationSender, "notificationSender must not be null"); + } + + /** + * Checks out a book for a member when the ISBN is valid and available. + * + * @param rawIsbn raw ISBN input (hyphens allowed) + * @param memberId non-blank borrower identifier + * @return loan receipt with confirmation code + */ + public LoanReceipt checkout(final String rawIsbn, final String memberId) { + String isbn = normalizeAndValidateIsbn(rawIsbn); + if (memberId == null || memberId.isBlank()) { + throw new IllegalArgumentException("Member ID must not be blank"); + } + + BookSummary book = catalogClient.findByIsbn(isbn); + if (book == null) { + throw new IllegalStateException("Book not found for ISBN: " + isbn); + } + if (!book.available()) { + throw new IllegalStateException("Book currently checked out: " + isbn); + } + + catalogClient.markCheckedOut(isbn, memberId.trim()); + String code = "LN-" + isbn.substring(isbn.length() - 4) + "-" + memberId.trim().toUpperCase(); + notificationSender.sendLoanConfirmation(memberId.trim(), isbn, code); + return new LoanReceipt(isbn, memberId.trim(), code); + } + + private String normalizeAndValidateIsbn(final String rawIsbn) { + if (rawIsbn == null || rawIsbn.isBlank()) { + throw new InvalidIsbnException("ISBN must not be blank"); + } + String compact = rawIsbn.replace("-", "").trim(); + if (compact.length() != 10 && compact.length() != 13) { + throw new InvalidIsbnException("ISBN must contain 10 or 13 characters: " + rawIsbn); + } + if (!compact.chars().allMatch(Character::isDigit)) { + throw new InvalidIsbnException("ISBN must contain digits only: " + rawIsbn); + } + return compact; + } +} diff --git a/library-service/src/main/java/io/cloudops/library/NotificationSender.java b/library-service/src/main/java/io/cloudops/library/NotificationSender.java new file mode 100644 index 0000000..fb714ff --- /dev/null +++ b/library-service/src/main/java/io/cloudops/library/NotificationSender.java @@ -0,0 +1,14 @@ +package io.cloudops.library; + +/** Outbound notification port for borrower receipts. */ +public interface NotificationSender { + + /** + * Sends a confirmation alert to a borrower. + * + * @param memberId borrower identifier + * @param isbn checked-out ISBN + * @param confirmationCode generated loan confirmation token + */ + void sendLoanConfirmation(String memberId, String isbn, String confirmationCode); +} diff --git a/library-service/src/test/java/io/cloudops/library/LoanServiceTest.java b/library-service/src/test/java/io/cloudops/library/LoanServiceTest.java new file mode 100644 index 0000000..d1e07a2 --- /dev/null +++ b/library-service/src/test/java/io/cloudops/library/LoanServiceTest.java @@ -0,0 +1,64 @@ +package io.cloudops.library; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class LoanServiceTest { + + @Mock + private CatalogClient catalogClient; + + @Mock + private NotificationSender notificationSender; + + private LoanService loanService; + + @BeforeEach + void setUp() { + loanService = new LoanService(catalogClient, notificationSender); + } + + @Test + void checkoutSucceedsAndSendsNotification() { + when(catalogClient.findByIsbn("9780134685991")) + .thenReturn(new BookSummary("9780134685991", "Effective Engineering", true)); + + LoanReceipt receipt = loanService.checkout("978-0134685991", "stu01"); + + assertEquals("9780134685991", receipt.isbn()); + assertEquals("stu01", receipt.memberId()); + assertEquals("LN-5991-STU01", receipt.confirmationCode()); + verify(catalogClient).markCheckedOut("9780134685991", "stu01"); + verify(notificationSender).sendLoanConfirmation("stu01", "9780134685991", "LN-5991-STU01"); + } + + @Test + void checkoutRejectsUnavailableBookWithoutMutatingCatalog() { + when(catalogClient.findByIsbn("0134685997")) + .thenReturn(new BookSummary("0134685997", "Busy Book", false)); + + assertThrows(IllegalStateException.class, () -> loanService.checkout("0134685997", "stu01")); + + verify(catalogClient, never()).markCheckedOut(anyString(), anyString()); + verifyNoInteractions(notificationSender); + } + + @Test + void checkoutRejectsMalformedIsbnBeforeCallingCollaborators() { + assertThrows(InvalidIsbnException.class, () -> loanService.checkout("bad-isbn", "stu01")); + assertThrows(InvalidIsbnException.class, () -> loanService.checkout(" ", "stu01")); + verifyNoInteractions(catalogClient, notificationSender); + } +} diff --git a/math-microservices/pom.xml b/math-microservices/pom.xml new file mode 100644 index 0000000..520d672 --- /dev/null +++ b/math-microservices/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + + io.cloudops + campus-ops-parent + 1.0.0-SNAPSHOT + + + math-microservices + Math Microservices Lab + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/math-microservices/src/main/java/io/cloudops/math/AdderController.java b/math-microservices/src/main/java/io/cloudops/math/AdderController.java new file mode 100644 index 0000000..ef35535 --- /dev/null +++ b/math-microservices/src/main/java/io/cloudops/math/AdderController.java @@ -0,0 +1,28 @@ +package io.cloudops.math; + +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +/** Microservice #1: sums two integers cleanly over JSON HTTP. */ +@RestController +@RequestMapping("/api/add") +public class AdderController { + + /** Request payload for integer addition. */ + public record AddRequest(Integer left, Integer right) { + } + + /** Adds two integer operands. */ + @PostMapping + public Map add(@RequestBody final AddRequest request) { + if (request == null || request.left() == null || request.right() == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "left and right are required"); + } + return Map.of("result", request.left() + request.right()); + } +} diff --git a/math-microservices/src/main/java/io/cloudops/math/GatewaySolverService.java b/math-microservices/src/main/java/io/cloudops/math/GatewaySolverService.java new file mode 100644 index 0000000..8e31e1e --- /dev/null +++ b/math-microservices/src/main/java/io/cloudops/math/GatewaySolverService.java @@ -0,0 +1,59 @@ +package io.cloudops.math; + +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +/** + * Orchestrates linear evaluation (a * x + b) across Multiplier and Adder services. + * + *

Starter bug for Challenge Lab 2: calls Multiplier with legacy keys {@code factorA}/{@code factorB} + * instead of the canonical {@code operandA}/{@code operandB} contract. + */ +@Service +public class GatewaySolverService { + + private final RestTemplate restTemplate; + private final String adderBaseUrl; + private final String multiplierBaseUrl; + + /** Spring-injected constructor configurable via math.adder.url and math.multiplier.url. */ + @Autowired + public GatewaySolverService( + final RestTemplate restTemplate, + @Value("${math.adder.url:http://localhost:8080}") final String adderBaseUrl, + @Value("${math.multiplier.url:http://localhost:8080}") final String multiplierBaseUrl) { + this.restTemplate = restTemplate; + this.adderBaseUrl = adderBaseUrl; + this.multiplierBaseUrl = multiplierBaseUrl; + } + + /** + * Evaluates a * x + b by chaining /api/mul followed by /api/add. + * + * @param a linear slope + * @param x input variable + * @param b y-intercept offset + * @return computed result + */ + public int solveLinear(final int a, final int x, final int b) { + Map mulPayload = Map.of("factorA", a, "factorB", x); + Map mulResponse = restTemplate.postForObject( + multiplierBaseUrl + "/api/mul", mulPayload, Map.class); + int product = extractResult(mulResponse, "multiplier"); + + Map addPayload = Map.of("left", product, "right", b); + Map addResponse = restTemplate.postForObject( + adderBaseUrl + "/api/add", addPayload, Map.class); + return extractResult(addResponse, "adder"); + } + + private int extractResult(final Map response, final String serviceName) { + if (response == null || !(response.get("result") instanceof Number number)) { + throw new IllegalStateException("Missing numeric result from " + serviceName); + } + return number.intValue(); + } +} diff --git a/math-microservices/src/main/java/io/cloudops/math/MathMicroservicesApplication.java b/math-microservices/src/main/java/io/cloudops/math/MathMicroservicesApplication.java new file mode 100644 index 0000000..e685390 --- /dev/null +++ b/math-microservices/src/main/java/io/cloudops/math/MathMicroservicesApplication.java @@ -0,0 +1,26 @@ +package io.cloudops.math; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; + +/** Consolidated Spring Boot host for the 3-endpoint Math Microservices lab. */ +@SpringBootApplication +public class MathMicroservicesApplication { + + /** + * Entry point for running Adder, Multiplier, and Gateway Solver services. + * + * @param args CLI flags + */ + public static void main(final String[] args) { + SpringApplication.run(MathMicroservicesApplication.class, args); + } + + /** Shared RestTemplate bean used by GatewaySolverService. */ + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/math-microservices/src/main/java/io/cloudops/math/MultiplierController.java b/math-microservices/src/main/java/io/cloudops/math/MultiplierController.java new file mode 100644 index 0000000..08c5b6d --- /dev/null +++ b/math-microservices/src/main/java/io/cloudops/math/MultiplierController.java @@ -0,0 +1,28 @@ +package io.cloudops.math; + +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +/** Microservice #2: multiplies operandA and operandB over JSON HTTP. */ +@RestController +@RequestMapping("/api/mul") +public class MultiplierController { + + /** Canonical request contract expected by MultiplierController. */ + public record MultiplyRequest(Integer operandA, Integer operandB) { + } + + /** Multiplies operandA by operandB; rejects payloads missing canonical keys. */ + @PostMapping + public Map multiply(@RequestBody final MultiplyRequest request) { + if (request == null || request.operandA() == null || request.operandB() == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "operandA and operandB are required"); + } + return Map.of("result", request.operandA() * request.operandB()); + } +} diff --git a/math-microservices/src/main/java/io/cloudops/math/SolverController.java b/math-microservices/src/main/java/io/cloudops/math/SolverController.java new file mode 100644 index 0000000..10b982c --- /dev/null +++ b/math-microservices/src/main/java/io/cloudops/math/SolverController.java @@ -0,0 +1,30 @@ +package io.cloudops.math; + +import java.util.Map; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** Microservice #3: exposes /api/solve to orchestrate linear equation calls. */ +@RestController +@RequestMapping("/api/solve") +public class SolverController { + + private final GatewaySolverService solverService; + + /** Request payload representing a * x + b. */ + public record SolveRequest(int a, int x, int b) { + } + + /** Constructs SolverController with the orchestrating GatewaySolverService. */ + public SolverController(final GatewaySolverService solverService) { + this.solverService = solverService; + } + + /** Evaluates a * x + b via downstream Multiplier and Adder calls. */ + @PostMapping + public Map solve(@RequestBody final SolveRequest request) { + return Map.of("result", solverService.solveLinear(request.a(), request.x(), request.b())); + } +} diff --git a/math-microservices/src/test/java/io/cloudops/math/GatewaySolverUnitTest.java b/math-microservices/src/test/java/io/cloudops/math/GatewaySolverUnitTest.java new file mode 100644 index 0000000..7657485 --- /dev/null +++ b/math-microservices/src/test/java/io/cloudops/math/GatewaySolverUnitTest.java @@ -0,0 +1,47 @@ +package io.cloudops.math; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +/** + * Isolated unit test for GatewaySolverService. + * + *

Deliberately mocks only the downstream HTTP URLs and responses so this unit suite passes + * even while the integration field-name bug exists between GatewaySolverService and MultiplierController. + */ +class GatewaySolverUnitTest { + + private MockRestServiceServer mockServer; + private GatewaySolverService solverService; + + @BeforeEach + void setUp() { + RestTemplate restTemplate = new RestTemplate(); + mockServer = MockRestServiceServer.createServer(restTemplate); + solverService = new GatewaySolverService(restTemplate, "http://adder.local", "http://mul.local"); + } + + @Test + void solveLinearChainsMultiplyThenAdd() { + mockServer.expect(requestTo("http://mul.local/api/mul")) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess("{\"result\":12}", MediaType.APPLICATION_JSON)); + + mockServer.expect(requestTo("http://adder.local/api/add")) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess("{\"result\":17}", MediaType.APPLICATION_JSON)); + + int solved = solverService.solveLinear(3, 4, 5); + assertEquals(17, solved); + mockServer.verify(); + } +} diff --git a/order-cart/pom.xml b/order-cart/pom.xml new file mode 100644 index 0000000..3e49db1 --- /dev/null +++ b/order-cart/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + + io.cloudops + campus-ops-parent + 1.0.0-SNAPSHOT + + + order-cart + Order Cart Service + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/order-cart/src/main/java/io/cloudops/ordercart/Cart.java b/order-cart/src/main/java/io/cloudops/ordercart/Cart.java new file mode 100644 index 0000000..bcaed2a --- /dev/null +++ b/order-cart/src/main/java/io/cloudops/ordercart/Cart.java @@ -0,0 +1,17 @@ +package io.cloudops.ordercart; + +import java.math.BigDecimal; +import java.util.List; + +/** Read view of a student order cart with derived total amount. */ +public record Cart(String cartId, List items, BigDecimal total) { + + /** Constructs a defensive copy of cart line items and sums line totals. */ + public static Cart fromItems(final String cartId, final List sourceItems) { + List copy = List.copyOf(sourceItems); + BigDecimal total = copy.stream() + .map(CartItem::lineTotal) + .reduce(BigDecimal.ZERO, BigDecimal::add); + return new Cart(cartId, copy, total); + } +} diff --git a/order-cart/src/main/java/io/cloudops/ordercart/CartController.java b/order-cart/src/main/java/io/cloudops/ordercart/CartController.java new file mode 100644 index 0000000..a310897 --- /dev/null +++ b/order-cart/src/main/java/io/cloudops/ordercart/CartController.java @@ -0,0 +1,55 @@ +package io.cloudops.ordercart; + +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** REST API endpoints for managing Campus Ops shopping carts. */ +@RestController +@RequestMapping("/api/carts") +public class CartController { + + private final CartService cartService; + + /** + * Creates a CartController backed by CartService. + * + * @param cartService cart domain service + */ + public CartController(final CartService cartService) { + this.cartService = cartService; + } + + /** Retrieves the contents and total of a cart. */ + @GetMapping("/{cartId}") + public Cart getCart(@PathVariable final String cartId) { + return cartService.getCart(cartId); + } + + /** Adds an item to the cart and returns HTTP 201 Created. */ + @PostMapping("/{cartId}/items") + public ResponseEntity addItem(@PathVariable final String cartId, @RequestBody final CartItem item) { + return ResponseEntity.status(HttpStatus.CREATED).body(cartService.addItem(cartId, item)); + } + + /** Clears all items from the cart. */ + @DeleteMapping("/{cartId}") + public ResponseEntity clearCart(@PathVariable final String cartId) { + cartService.clearCart(cartId); + return ResponseEntity.noContent().build(); + } + + /** Translates validation errors to HTTP 400 JSON payloads. */ + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleValidation(final IllegalArgumentException ex) { + return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage())); + } +} diff --git a/order-cart/src/main/java/io/cloudops/ordercart/CartItem.java b/order-cart/src/main/java/io/cloudops/ordercart/CartItem.java new file mode 100644 index 0000000..33a22ee --- /dev/null +++ b/order-cart/src/main/java/io/cloudops/ordercart/CartItem.java @@ -0,0 +1,25 @@ +package io.cloudops.ordercart; + +import java.math.BigDecimal; + +/** Immutable line item stored inside a shopping cart. */ +public record CartItem(String sku, int quantity, BigDecimal unitPrice) { + + /** Canonical constructor enforcing non-blank SKU and positive pricing constraints. */ + public CartItem { + if (sku == null || sku.isBlank()) { + throw new IllegalArgumentException("SKU must not be blank"); + } + if (quantity <= 0) { + throw new IllegalArgumentException("Quantity must be positive"); + } + if (unitPrice == null || unitPrice.compareTo(BigDecimal.ZERO) < 0) { + throw new IllegalArgumentException("Unit price must be non-negative"); + } + } + + /** Computes subtotal for this item line. */ + public BigDecimal lineTotal() { + return unitPrice.multiply(BigDecimal.valueOf(quantity)); + } +} diff --git a/order-cart/src/main/java/io/cloudops/ordercart/CartService.java b/order-cart/src/main/java/io/cloudops/ordercart/CartService.java new file mode 100644 index 0000000..1a50996 --- /dev/null +++ b/order-cart/src/main/java/io/cloudops/ordercart/CartService.java @@ -0,0 +1,78 @@ +package io.cloudops.ordercart; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.stereotype.Service; + +/** In-memory shopping cart state manager for Campus Ops orders. */ +@Service +public class CartService { + + private final Map> carts = new ConcurrentHashMap<>(); + + /** + * Appends an item to the specified cart, merging matching SKUs at the same price. + * + * @param cartId cart identifier + * @param item item to add + * @return updated Cart snapshot + */ + public Cart addItem(final String cartId, final CartItem item) { + String normalizedId = normalizeCartId(cartId); + List items = carts.computeIfAbsent(normalizedId, ignored -> new ArrayList<>()); + synchronized (items) { + int existingIdx = findSkuIndex(items, item.sku()); + if (existingIdx >= 0) { + CartItem existing = items.get(existingIdx); + items.set(existingIdx, new CartItem( + existing.sku(), + existing.quantity() + item.quantity(), + item.unitPrice())); + } else { + items.add(item); + } + return Cart.fromItems(normalizedId, items); + } + } + + /** + * Fetches the current snapshot of a cart. + * + * @param cartId cart identifier + * @return Cart view (empty list when unknown) + */ + public Cart getCart(final String cartId) { + String normalizedId = normalizeCartId(cartId); + List items = carts.getOrDefault(normalizedId, List.of()); + synchronized (items) { + return Cart.fromItems(normalizedId, items); + } + } + + /** + * Removes all items stored under the specified cart. + * + * @param cartId cart identifier + */ + public void clearCart(final String cartId) { + carts.remove(normalizeCartId(cartId)); + } + + private int findSkuIndex(final List items, final String sku) { + for (int i = 0; i < items.size(); i++) { + if (items.get(i).sku().equals(sku)) { + return i; + } + } + return -1; + } + + private String normalizeCartId(final String cartId) { + if (cartId == null || cartId.isBlank()) { + throw new IllegalArgumentException("cartId must not be blank"); + } + return cartId.trim(); + } +} diff --git a/order-cart/src/main/java/io/cloudops/ordercart/OrderCartApplication.java b/order-cart/src/main/java/io/cloudops/ordercart/OrderCartApplication.java new file mode 100644 index 0000000..cf778bb --- /dev/null +++ b/order-cart/src/main/java/io/cloudops/ordercart/OrderCartApplication.java @@ -0,0 +1,18 @@ +package io.cloudops.ordercart; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** Entry point for the Campus Ops Order Cart microservice. */ +@SpringBootApplication +public class OrderCartApplication { + + /** + * Launches the Order Cart Spring Boot application. + * + * @param args CLI arguments + */ + public static void main(final String[] args) { + SpringApplication.run(OrderCartApplication.class, args); + } +} diff --git a/order-cart/src/test/java/io/cloudops/ordercart/CartApiIT.java b/order-cart/src/test/java/io/cloudops/ordercart/CartApiIT.java new file mode 100644 index 0000000..c6f2730 --- /dev/null +++ b/order-cart/src/test/java/io/cloudops/ordercart/CartApiIT.java @@ -0,0 +1,51 @@ +package io.cloudops.ordercart; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +class CartApiIT { + + @Autowired + private MockMvc mockMvc; + + @Test + void cartLifecycleWorksEndToEndOverHttp() throws Exception { + mockMvc.perform(post("/api/carts/it-cart/items") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"sku\":\"LAB-HOODIE\",\"quantity\":2,\"unitPrice\":35.00}")) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.cartId").value("it-cart")) + .andExpect(jsonPath("$.total").value(70.00)); + + mockMvc.perform(get("/api/carts/it-cart")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].sku").value("LAB-HOODIE")); + + mockMvc.perform(delete("/api/carts/it-cart")) + .andExpect(status().isNoContent()); + + mockMvc.perform(get("/api/carts/it-cart")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items.length()").value(0)); + } + + @Test + void invalidPayloadReturnsBadRequest() throws Exception { + mockMvc.perform(post("/api/carts/bad-cart/items") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"sku\":\"BAD-QTY\",\"quantity\":-2,\"unitPrice\":10.00}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/order-cart/src/test/java/io/cloudops/ordercart/CartServiceTest.java b/order-cart/src/test/java/io/cloudops/ordercart/CartServiceTest.java new file mode 100644 index 0000000..2dcec6b --- /dev/null +++ b/order-cart/src/test/java/io/cloudops/ordercart/CartServiceTest.java @@ -0,0 +1,45 @@ +package io.cloudops.ordercart; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigDecimal; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CartServiceTest { + + private CartService cartService; + + @BeforeEach + void setUp() { + cartService = new CartService(); + } + + @Test + void mergesMatchingSkuAndTotalsProperly() { + cartService.addItem("c-101", new CartItem("NOTEBOOK", 2, new BigDecimal("4.50"))); + Cart cart = cartService.addItem("c-101", new CartItem("NOTEBOOK", 1, new BigDecimal("4.50"))); + + assertEquals(1, cart.items().size()); + assertEquals(3, cart.items().getFirst().quantity()); + assertEquals(new BigDecimal("13.50"), cart.total()); + } + + @Test + void clearCartEmptiesLineItems() { + cartService.addItem("c-102", new CartItem("PEN", 4, new BigDecimal("1.25"))); + cartService.clearCart("c-102"); + + Cart empty = cartService.getCart("c-102"); + assertEquals(0, empty.items().size()); + assertEquals(BigDecimal.ZERO, empty.total()); + } + + @Test + void rejectsNegativeQuantityAndBlankSku() { + assertThrows(IllegalArgumentException.class, () -> new CartItem("", 1, BigDecimal.ONE)); + assertThrows(IllegalArgumentException.class, () -> new CartItem("PEN", 0, BigDecimal.ONE)); + assertThrows(IllegalArgumentException.class, () -> cartService.getCart(" ")); + } +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..5362f51 --- /dev/null +++ b/pom.xml @@ -0,0 +1,178 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + + + + io.cloudops + campus-ops-parent + 1.0.0-SNAPSHOT + pom + Campus Ops Java Parent + + + library-service + order-cart + math-microservices + freight-calculator + + + + 21 + UTF-8 + false + 0.00 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.1 + + ${skipUnitTests} + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.1 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.1 + + ${skipUnitTests} + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.1 + + + + integration-test + verify + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.5.0 + + + com.puppycrawl.tools + checkstyle + 10.18.2 + + + + ${maven.multiModuleProjectDirectory}/checkstyle.xml + UTF-8 + true + true + warning + false + + + + checkstyle-verify + verify + + check + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 3.25.0 + + false + true + true + 35 + + + + pmd-verify + verify + + check + cpd-check + + + + + + + org.jacoco + jacoco-maven-plugin + 0.8.12 + + + **/*Application.class + + + + + prepare-agent + + prepare-agent + + + + report + test + + report + + + + jacoco-check + verify + + check + + + ${skipUnitTests} + + + BUNDLE + + + LINE + COVEREDRATIO + ${jacoco.min.line.ratio} + + + + + + + + + + +