feat: initial starter state for campus-ops-java

This commit is contained in:
CloudOps Lab Bot 2026-11-24 11:13:59 +08:00
commit 9e45154fdd
33 changed files with 1188 additions and 0 deletions

1
.mvn/maven.config Normal file
View File

@ -0,0 +1 @@
# Ensures maven.multiModuleProjectDirectory resolves to campus-ops-java even inside -pl runs

24
Jenkinsfile vendored Normal file
View File

@ -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()
}
}
}

9
README.md Normal file
View File

@ -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`

38
checkstyle.xml Normal file
View File

@ -0,0 +1,38 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://"/>
</module>
<module name="TreeWalker">
<module name="UnusedImports"/>
<module name="RedundantImport"/>
<module name="NeedBraces"/>
<module name="EmptyBlock"/>
<module name="EqualsHashCode"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<module name="MethodLength">
<property name="max" value="50"/>
</module>
<module name="ParameterNumber">
<property name="max" value="6"/>
</module>
<module name="CyclomaticComplexity">
<property name="max" value="10"/>
</module>
</module>
</module>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.cloudops</groupId>
<artifactId>campus-ops-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>freight-calculator</artifactId>
<name>Freight Calculator</name>
<properties>
<jacoco.min.line.ratio>0.85</jacoco.min.line.ratio>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -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<Region, BigDecimal> 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);
}
}

View File

@ -0,0 +1,8 @@
package io.cloudops.freight;
/** Supported shipping destination zones for Campus Ops freight quotes. */
public enum Region {
DOMESTIC,
REGIONAL,
INTERNATIONAL
}

View File

@ -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);
}
}

View File

@ -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));
}
}

23
library-service/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.cloudops</groupId>
<artifactId>campus-ops-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>library-service</artifactId>
<name>Library Service</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -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) {
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -0,0 +1,5 @@
package io.cloudops.library;
/** Receipt issued after a successful book checkout. */
public record LoanReceipt(String isbn, String memberId, String confirmationCode) {
}

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.cloudops</groupId>
<artifactId>campus-ops-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>math-microservices</artifactId>
<name>Math Microservices Lab</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<String, Integer> 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());
}
}

View File

@ -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.
*
* <p>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<String, Integer> mulPayload = Map.of("factorA", a, "factorB", x);
Map<?, ?> mulResponse = restTemplate.postForObject(
multiplierBaseUrl + "/api/mul", mulPayload, Map.class);
int product = extractResult(mulResponse, "multiplier");
Map<String, Integer> 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();
}
}

View File

@ -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();
}
}

View File

@ -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<String, Integer> 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());
}
}

View File

@ -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<String, Integer> solve(@RequestBody final SolveRequest request) {
return Map.of("result", solverService.solveLinear(request.a(), request.x(), request.b()));
}
}

View File

@ -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.
*
* <p>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();
}
}

36
order-cart/pom.xml Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.cloudops</groupId>
<artifactId>campus-ops-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>order-cart</artifactId>
<name>Order Cart Service</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<CartItem> items, BigDecimal total) {
/** Constructs a defensive copy of cart line items and sums line totals. */
public static Cart fromItems(final String cartId, final List<CartItem> sourceItems) {
List<CartItem> copy = List.copyOf(sourceItems);
BigDecimal total = copy.stream()
.map(CartItem::lineTotal)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return new Cart(cartId, copy, total);
}
}

View File

@ -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<Cart> 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<Void> 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<Map<String, String>> handleValidation(final IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}

View File

@ -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));
}
}

View File

@ -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<String, List<CartItem>> 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<CartItem> 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<CartItem> 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<CartItem> 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();
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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(" "));
}
}

178
pom.xml Normal file
View File

@ -0,0 +1,178 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
<relativePath/>
</parent>
<groupId>io.cloudops</groupId>
<artifactId>campus-ops-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Campus Ops Java Parent</name>
<modules>
<module>library-service</module>
<module>order-cart</module>
<module>math-microservices</module>
<module>freight-calculator</module>
</modules>
<properties>
<java.version>21</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<skipUnitTests>false</skipUnitTests>
<jacoco.min.line.ratio>0.00</jacoco.min.line.ratio>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<skipTests>${skipUnitTests}</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<skipTests>${skipUnitTests}</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.5.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.18.2</version>
</dependency>
</dependencies>
<configuration>
<configLocation>${maven.multiModuleProjectDirectory}/checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<violationSeverity>warning</violationSeverity>
<linkXRef>false</linkXRef>
</configuration>
<executions>
<execution>
<id>checkstyle-verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.25.0</version>
<configuration>
<linkXRef>false</linkXRef>
<failOnViolation>true</failOnViolation>
<printFailingErrors>true</printFailingErrors>
<minimumTokens>35</minimumTokens>
</configuration>
<executions>
<execution>
<id>pmd-verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
<goal>cpd-check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.12</version>
<configuration>
<excludes>
<exclude>**/*Application.class</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<skip>${skipUnitTests}</skip>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco.min.line.ratio}</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>