Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ This repo contains the sample for [Keploy's](https://keploy.io) Java Application
9. [Simple Java Dynamic Deduplication](https://github.com/keploy/samples-java/tree/main/simple-java-dedup) - A minimal plain-Java HTTP server used to smoke-test Java dynamic dedup on Java 8 and Java 17 in native and Docker launch modes.
10. [MySQL CRUD](https://github.com/keploy/samples-java/tree/main/mysql-crud) - A minimal Spring Boot + JDBC CRUD app used by Enterprise CI to validate the self-hosted cloud-replay pipeline's JDBC secret-obfuscation and object-storage mock upload/download paths against a real MySQL 8 backend.
11. [Springboot Product Catalog](https://github.com/keploy/samples-java/tree/main/spring-boot-product-catalog) - A Spring Boot + PostgreSQL product-catalog REST API shipping a committed 57-case Keploy test set and 190 Postgres mocks. Includes an app-only docker-compose with no database service at all, so the whole suite replays green with Postgres absent.
12. [Kubernetes: Gravitee + Solace PubSub+ + ModSecurity WAF + PostgreSQL + Redis](https://github.com/keploy/samples-java/tree/main/k8s-gravitee-solace-waf) - A Spring Boot 3.3 / Java 21 `orders-api` deployed on Kind behind a ModSecurity / OWASP CRS WAF and Gravitee API Gateway, integrating with PostgreSQL, Redis, an internal `inventory-api` through Gravitee, a partner `payments-api` through a WAF, and Solace PubSub+ over native SMF v3 (publish and consume). Demonstrates Keploy Kubernetes DaemonSet recording and sandbox replay across all five mock kinds, multi-dependency regression detection (`2.0`), strict mock noise (`2.1`), and intended response changes (`2.2`).

## Community Support ❤️

Expand Down
8 changes: 8 additions & 0 deletions k8s-gravitee-solace-waf/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
target/
*.jar
*.log
/keploy/
/keploy.yml
.DS_Store
.idea/
*.iml
318 changes: 318 additions & 0 deletions k8s-gravitee-solace-waf/README.md

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions k8s-gravitee-solace-waf/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Build: docker build -t orders-api:1.0 .
# docker build --build-arg VARIANT=v2 -t orders-api:2.0 . (v2: breaks Solace + Gravitee/inventory + Postgres)
# docker build --build-arg VARIANT=v3 -t orders-api:2.1 . (v3: upper-cases channel in Solace event for strict-mode demo)
# docker build --build-arg VARIANT=v4 -t orders-api:2.2 . (v4: an EXPECTED change: cancel returns status REFUND_PENDING)
FROM maven:3.9.16-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -q -B dependency:go-offline
ARG VARIANT=v1
COPY src ./src
COPY v2.patch v3.patch v4.patch ./
RUN if [ "$VARIANT" != "v1" ]; then apt-get -qq update >/dev/null && apt-get -qq install -y patch >/dev/null; patch -p1 < $VARIANT.patch; fi \
&& mvn -q -B -DskipTests package

FROM eclipse-temurin:21.0.13_9-jre
WORKDIR /app
COPY --from=build /src/target/orders-api.jar /app/orders-api.jar
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=70", "-Djdk.httpclient.allowRestrictedHeaders=host", "-jar", "/app/orders-api.jar"]
51 changes: 51 additions & 0 deletions k8s-gravitee-solace-waf/app/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?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.keploy.demo</groupId>
<artifactId>orders-api</artifactId>
<version>1.0.0</version>
<name>orders-api</name>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.solacesystems</groupId>
<artifactId>sol-jcsmp</artifactId>
<version>10.24.0</version>
</dependency>
</dependencies>
<build>
<finalName>orders-api</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package io.keploy.demo.orders;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* Calls internal inventory-api OUTBOUND through Gravitee APIM Gateway (/inventory/reserve).
*/
@Component
class InventoryClient {
private static final Logger log = LoggerFactory.getLogger(InventoryClient.class);

record Result(int status, String reservationId, String gatewayTxId) {}

private final HttpClient http = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(3))
.build();
private final ObjectMapper mapper;
private final String reserveUrl;
private final String apiKey;

InventoryClient(ObjectMapper mapper,
@Value("${inventory.url}") String reserveUrl,
@Value("${inventory.api-key}") String apiKey) {
this.mapper = mapper;
this.reserveUrl = reserveUrl;
this.apiKey = apiKey;
}

Result reserve(String orderId, List<Map<String, Object>> items, String correlationId) throws Exception {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("orderId", orderId);
payload.put("warehouse", "EU-WEST-1");
payload.put("items", items);
String body = mapper.writeValueAsString(payload);

HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(reserveUrl))
.timeout(Duration.ofSeconds(5))
.header("Content-Type", "application/json")
.header("X-Api-Key", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(body));
if (correlationId != null && !correlationId.isBlank()) {
req.header("X-Correlation-ID", correlationId);
}
HttpResponse<String> resp = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
String gwTx = resp.headers().firstValue("X-Gravitee-Transaction-Id").orElse(null);
String resId = null;
if (resp.statusCode() / 100 == 2 && resp.body() != null && !resp.body().isBlank()) {
JsonNode node = mapper.readTree(resp.body());
if (node.hasNonNull("reservationId")) {
resId = node.get("reservationId").asText();
}
}
log.info("inventory reserve {} via Gravitee -> HTTP {} resId={} gwTx={}", orderId, resp.statusCode(), resId, gwTx);
return new Result(resp.statusCode(), resId, gwTx);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
package io.keploy.demo.orders;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

@RestController
public class OrderController {
private static final Logger log = LoggerFactory.getLogger(OrderController.class);
private static final Set<String> CURRENCIES = Set.of("EUR", "USD", "GBP", "INR");
private static final TypeReference<LinkedHashMap<String, Object>> MAP_TYPE = new TypeReference<>() {};

private final OrderRepository repository;
private final RedisCacheClient redis;
private final InventoryClient inventory;
private final PaymentsClient payments;
private final SolacePublisher publisher;
private final ObjectMapper mapper;
private final String topic;

OrderController(OrderRepository repository,
RedisCacheClient redis,
InventoryClient inventory,
PaymentsClient payments,
SolacePublisher publisher,
ObjectMapper mapper,
@Value("${orders.topic}") String topic) {
this.repository = repository;
this.redis = redis;
this.inventory = inventory;
this.payments = payments;
this.publisher = publisher;
this.mapper = mapper;
this.topic = topic;
}

@GetMapping("/health")
Map<String, String> health() {
return Map.of("status", "UP");
}

@PostMapping("/orders")
ResponseEntity<Map<String, Object>> create(@RequestBody Map<String, Object> req,
@RequestHeader(value = "X-Gravitee-Transaction-Id", required = false) String gwTx,
@RequestHeader(value = "X-Sales-Channel", required = false) String channel) throws Exception {
List<String> errors = new ArrayList<>();
String customerId = str(req.get("customerId"));
String reference = str(req.get("reference"));
String currency = Optional.ofNullable(str(req.get("currency"))).orElse("EUR");
String note = Optional.ofNullable(str(req.get("note"))).orElse("standard");
if (customerId == null || !customerId.matches("C-\\d{3,8}")) errors.add("customerId must look like C-1234");
if (reference == null || reference.isBlank()) errors.add("reference is required");
if (!CURRENCIES.contains(currency)) errors.add("currency must be one of " + new TreeSet<>(CURRENCIES));

List<Map<String, Object>> items = new ArrayList<>();
BigDecimal total = BigDecimal.ZERO;
Object rawItems = req.get("items");
if (!(rawItems instanceof List<?> list) || list.isEmpty()) {
errors.add("items must be a non-empty list");
} else {
int i = 0;
for (Object o : list) {
if (!(o instanceof Map<?, ?> m)) { errors.add("items[" + i + "] must be an object"); i++; continue; }
String sku = str(m.get("sku"));
Integer qty = m.get("quantity") instanceof Number n ? n.intValue() : null;
BigDecimal price = m.get("unitPrice") instanceof Number n ? new BigDecimal(n.toString()) : null;
if (sku == null || sku.isBlank()) errors.add("items[" + i + "].sku is required");
if (qty == null || qty < 1 || qty > 100) errors.add("items[" + i + "].quantity must be 1..100");
if (price == null || price.signum() <= 0) errors.add("items[" + i + "].unitPrice must be > 0");
if (sku != null && qty != null && price != null && qty >= 1 && price.signum() > 0) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("sku", sku);
item.put("quantity", qty);
item.put("unitPrice", price.setScale(2, RoundingMode.HALF_UP));
items.add(item);
total = total.add(price.multiply(BigDecimal.valueOf(qty)));
}
i++;
}
}
if (!errors.isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "validation_failed", "details", errors));
}

String orderId = "ORD-" + shortHash(customerId + "|" + reference);
total = total.setScale(2, RoundingMode.HALF_UP);
String ch = channel == null || channel.isBlank() ? "web" : channel;

// 1. Redis idempotency check (SET NX EX)
if (!redis.claimIdempotency(customerId, reference, orderId)) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", "duplicate_order", "orderId", orderId, "source", "redis_idempotency"));
}

// 2. Outbound partner payments authorization THROUGH the ModSecurity/CRS WAF
PaymentsClient.Result pay = payments.authorize(orderId, customerId, total, currency, note);
if (pay.status() == 403) {
redis.releaseIdempotency(customerId, reference);
Map<String, Object> rej = new LinkedHashMap<>();
rej.put("error", "payment_rejected_by_waf");
rej.put("wafStatus", 403);
rej.put("orderId", orderId);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(rej);
}
if (pay.status() / 100 != 2) {
redis.releaseIdempotency(customerId, reference);
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", "payment_failed", "paymentStatus", pay.status()));
}

// 3. Persist order in PostgreSQL
repository.insert(orderId, customerId, reference, items, total, currency, ch, pay.paymentId(), note);

// 4. Outbound inventory reservation THROUGH Gravitee + 5. Solace OrderCreated publish
// Run both so a multi-dependency regression surfaces diffs on both Gravitee/inventory and Solace.
int inventoryStatus;
String reservationId = null;
String inventoryGwTx = null;
try {
InventoryClient.Result inv = inventory.reserve(orderId, items, gwTx);
inventoryStatus = inv.status();
reservationId = inv.reservationId();
inventoryGwTx = inv.gatewayTxId();
} catch (Exception e) {
log.warn("inventory reserve failed for {}: {}", orderId, e.toString());
inventoryStatus = 502;
}

Map<String, Object> event = OrderEvents.orderCreated(orderId, customerId, items, total, currency, ch, pay.paymentId());
int brokerStatus;
try {
brokerStatus = publisher.publish(topic, event, gwTx);
} catch (Exception e) {
log.warn("solace publish failed for {}: {}", orderId, e.toString());
brokerStatus = 502;
}

if (inventoryStatus / 100 != 2 || brokerStatus / 100 != 2) {
Map<String, Object> err = new LinkedHashMap<>();
err.put("error", "downstream_failed");
err.put("inventoryStatus", inventoryStatus);
err.put("brokerStatus", brokerStatus);
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(err);
}

Map<String, Object> resp = new LinkedHashMap<>();
resp.put("orderId", orderId);
resp.put("status", "CREATED");
resp.put("customerId", customerId);
resp.put("reference", reference);
resp.put("items", items);
resp.put("totalAmount", total);
resp.put("currency", currency);
resp.put("channel", ch);
resp.put("paymentId", pay.paymentId());
resp.put("reservationId", reservationId);
resp.put("note", note);
resp.put("publishedTo", topic);
resp.put("gatewayTransactionId", gwTx);
if (inventoryGwTx != null) {
resp.put("inventoryGatewayTransactionId", inventoryGwTx);
}
return ResponseEntity.status(HttpStatus.CREATED).body(resp);
}

@GetMapping("/orders/{id}")
ResponseEntity<Map<String, Object>> get(@PathVariable String id) throws Exception {
String cached = redis.getOrder(id);
if (cached != null) {
Map<String, Object> o = mapper.readValue(cached, MAP_TYPE);
o.put("cache", "HIT");
return ResponseEntity.ok(o);
}
Optional<Map<String, Object>> found = repository.findById(id);
if (found.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found", "orderId", id));
}
Map<String, Object> order = found.get();
redis.putOrder(id, mapper.writeValueAsString(order));
Map<String, Object> resp = new LinkedHashMap<>(order);
resp.put("cache", "MISS");
return ResponseEntity.ok(resp);
}

/**
* Cancels an order end-to-end over native Solace SMF: publishes OrderCancelled to orders/cancelled,
* consumes the broker-pushed SMF delivery via JCSMP XMLMessageConsumer, updates Postgres, and evicts Redis.
*/
@PostMapping("/orders/{id}/cancel")
ResponseEntity<Map<String, Object>> cancelOrder(@PathVariable String id,
@RequestBody(required = false) Map<String, Object> body,
@RequestHeader(value = "X-Gravitee-Transaction-Id", required = false) String gwTx) throws Exception {
String reason = body != null && body.get("reason") != null ? body.get("reason").toString() : "customer_requested";
String via = publisher.publishAndConsumeCancel(id, reason, gwTx);
int updated = repository.cancel(id);
redis.evictOrder(id);
log.info("cancelled order {} via {} (reason={}, updated={})", id, via, reason, updated);
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("orderId", id);
resp.put("status", "CANCELLED");
resp.put("reason", reason);
resp.put("consumedVia", via);
resp.put("updated", updated);
return ResponseEntity.ok(resp);
}

private static String str(Object o) {
return o == null ? null : o.toString();
}

private static String shortHash(String s) throws Exception {
byte[] d = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().withUpperCase().formatHex(d, 0, 5);
}
}
Loading
Loading